System.register("chunks:///main.js", ['cc', './rollupPluginModLoBabelHelpers-0157841a.js'], function (exports, module) {
  var cclegacy, director, Component, _decorator, Enum, KeyCode, input, Input, find$1, Vec3, Camera, EventMouse, Quat, toDegree, PolygonCollider2D, RigidBody2D, Contact2DType, ERigidBody2DType, Label, Collider2D, Vec2, Node, ProgressBar, clamp$1, toRadian, v2, instantiate, UITransform, Color, Sprite, Joint2D, CCInteger, RichText, Sorting2D, settings, Prefab, math$1, Widget, tween, Mask, Graphics, macro, Tween, view, PhysicsSystem2D, ERaycast2DType, ParticleSystem2D, _createForOfIteratorHelperLoose, _extends, _regeneratorRuntime, _createClass, _objectWithoutPropertiesLoose, _inheritsLoose, _asyncToGenerator, _applyDecoratedDescriptor, _initializerDefineProperty, _assertThisInitialized;
  return {
    setters: [function (module) {
      cclegacy = module.cclegacy;
      director = module.director;
      Component = module.Component;
      _decorator = module._decorator;
      Enum = module.Enum;
      KeyCode = module.KeyCode;
      input = module.input;
      Input = module.Input;
      find$1 = module.find;
      Vec3 = module.Vec3;
      Camera = module.Camera;
      EventMouse = module.EventMouse;
      Quat = module.Quat;
      toDegree = module.toDegree;
      PolygonCollider2D = module.PolygonCollider2D;
      RigidBody2D = module.RigidBody2D;
      Contact2DType = module.Contact2DType;
      ERigidBody2DType = module.ERigidBody2DType;
      Label = module.Label;
      Collider2D = module.Collider2D;
      Vec2 = module.Vec2;
      Node = module.Node;
      ProgressBar = module.ProgressBar;
      clamp$1 = module.clamp;
      toRadian = module.toRadian;
      v2 = module.v2;
      instantiate = module.instantiate;
      UITransform = module.UITransform;
      Color = module.Color;
      Sprite = module.Sprite;
      Joint2D = module.Joint2D;
      CCInteger = module.CCInteger;
      RichText = module.RichText;
      Sorting2D = module.Sorting2D;
      settings = module.settings;
      Prefab = module.Prefab;
      math$1 = module.math;
      Widget = module.Widget;
      tween = module.tween;
      Mask = module.Mask;
      Graphics = module.Graphics;
      macro = module.macro;
      Tween = module.Tween;
      view = module.view;
      PhysicsSystem2D = module.PhysicsSystem2D;
      ERaycast2DType = module.ERaycast2DType;
      ParticleSystem2D = module.ParticleSystem2D;
    }, function (module) {
      _createForOfIteratorHelperLoose = module.e;
      _extends = module.f;
      _regeneratorRuntime = module.g;
      _createClass = module.d;
      _objectWithoutPropertiesLoose = module.h;
      _inheritsLoose = module.a;
      _asyncToGenerator = module.i;
      _applyDecoratedDescriptor = module._;
      _initializerDefineProperty = module.b;
      _assertThisInitialized = module.c;
    }],
    execute: function () {
      cclegacy._RF.push({}, "9ce45UziSVBup9LmTcxb+m8", "ISchema", undefined);
      /**
       * 工具类型：获取路径的前缀，并且只保留字符和数字
       */
      /**
       * 工具类型：将嵌套的树结构类型扁平化为映射类型
       * 将树形结构如 { a: { b: [string] } , c: string } 转换为扁平结构如 { "a.b": [string] } |  {c: string}
       *
       * @template T - 需要被扁平化的树形结构类型
       * @template Prefix - 当前遍历路径的前缀，默认为空字符串
       */
      /**
       * 辅助类型：将联合类型转换为交叉类型
       * 例如：将 A | B | C 转换为 A & B & C
       *
       * 工作原理：
       * 1. `U extends unknown ? (k: U) => void : never` 将联合类型的每个成员转换为函数类型
       *    例如：(A | B | C) 变成 ((k: A) => void) | ((k: B) => void) | ((k: C) => void)
       * 2. 然后利用 TypeScript 的逆变位置推断特性，当多个函数类型作为参数时，
       *    TypeScript 会尝试找到这些函数参数类型的交叉类型
       * 3. 使用 `infer I` 提取这个交叉类型作为最终结果
       *
       * @template U - 需要转换的联合类型
       */
      /**
       * 辅助类型：数组转交叉类型
       */
      /**
       * 将嵌套的树结构类型扁平化为映射类型
       * 将树形结构如 { a: { b: [string] } , c: string } 转换为扁平结构如 { "a.b": [string] ,"c": string}
       *
       * @template T - 需要被扁平化的树形结构类型
       * @template Prefix - 当前遍历路径的前缀，默认为空字符串
       */
      /**
       * 在扁平的基础上添加任意路径的支持
       */
      /**
       * 创建路径对象的类型
       * 生成一个可用于访问事件路径的对象，提供编译时类型检查和IDE自动补全
       *
       * @template T - 原始树形结构类型
       * @template Prefix - 当前路径前缀，默认为空字符串
       */
      cclegacy._RF.pop();
      var CjsLoader = /*#__PURE__*/function () {
        function CjsLoader() {
          this._registry = {};
          this._moduleCache = {};
        }

        /**
         * Defines a CommonJS module.
         * @param id Module ID.
         * @param factory The factory.
         * @param resolveMap An object or a function returning object which records the module specifier resolve result.
         * The later is called as "deferred resolve map" and would be invocated right before CommonJS code execution.
         */
        var _proto = CjsLoader.prototype;
        _proto.define = function define(id, factory, resolveMap) {
          this._registry[id] = {
            factory: factory,
            resolveMap: resolveMap
          };
        }

        /**
         * Requires a CommonJS module.
         * @param id Module ID.
         * @returns The module's `module.exports`.
         */;
        _proto.require = function require(id) {
          return this._require(id);
        };
        _proto.throwInvalidWrapper = function throwInvalidWrapper(requestTarget, from) {
          throw new Error("Module '" + requestTarget + "' imported from '" + from + "' is expected be an ESM-wrapped CommonJS module but it doesn't.");
        };
        _proto._require = function _require(id, parent) {
          var cachedModule = this._moduleCache[id];
          if (cachedModule) {
            return cachedModule.exports;
          }
          var module = {
            id: id,
            exports: {}
          };
          this._moduleCache[id] = module;
          this._tryModuleLoad(module, id);
          return module.exports;
        };
        _proto._resolve = function _resolve(specifier, parent) {
          return this._resolveFromInfos(specifier, parent) || this._throwUnresolved(specifier, parent);
        };
        _proto._resolveFromInfos = function _resolveFromInfos(specifier, parent) {
          var _cjsInfos$parent$reso, _cjsInfos$parent;
          if (specifier in cjsInfos) {
            return specifier;
          }
          if (!parent) {
            return;
          }
          return (_cjsInfos$parent$reso = (_cjsInfos$parent = cjsInfos[parent]) == null ? void 0 : _cjsInfos$parent.resolveCache[specifier]) != null ? _cjsInfos$parent$reso : undefined;
        };
        _proto._tryModuleLoad = function _tryModuleLoad(module, id) {
          var threw = true;
          try {
            this._load(module, id);
            threw = false;
          } finally {
            if (threw) {
              delete this._moduleCache[id];
            }
          }
        };
        _proto._load = function _load(module, id) {
          var _this$_loadWrapper = this._loadWrapper(id),
            factory = _this$_loadWrapper.factory,
            resolveMap = _this$_loadWrapper.resolveMap;
          var vendorRequire = this._createRequire(module);
          var require = resolveMap ? this._createRequireWithResolveMap(typeof resolveMap === 'function' ? resolveMap() : resolveMap, vendorRequire) : vendorRequire;
          factory(module.exports, require, module);
        };
        _proto._loadWrapper = function _loadWrapper(id) {
          if (id in this._registry) {
            return this._registry[id];
          } else {
            return this._loadHostProvidedModules(id);
          }
        };
        _proto._loadHostProvidedModules = function _loadHostProvidedModules(id) {
          return {
            factory: function factory(_exports, _require, module) {
              if (typeof require === 'undefined') {
                throw new Error("Current environment does not provide a require() for requiring '" + id + "'.");
              }
              try {
                module.exports = require(id);
              } catch (err) {
                throw new Error("Exception thrown when calling host defined require('" + id + "').", {
                  cause: err
                });
              }
            }
          };
        };
        _proto._createRequire = function _createRequire(module) {
          var _this = this;
          return function (specifier) {
            return _this._require(specifier, module);
          };
        };
        _proto._createRequireWithResolveMap = function _createRequireWithResolveMap(requireMap, originalRequire) {
          return function (specifier) {
            var resolved = requireMap[specifier];
            if (resolved) {
              return originalRequire(resolved);
            } else {
              throw new Error('Unresolved specifier ' + specifier);
            }
          };
        };
        _proto._throwUnresolved = function _throwUnresolved(specifier, parentUrl) {
          throw new Error("Unable to resolve " + specifier + " from " + parent + ".");
        };
        return CjsLoader;
      }();
      var loader = new CjsLoader();
      var __cjsMetaURL = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/set.js';
      loader.define(__cjsMetaURL, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Set
         * ==============
         *
         * Useful function related to sets such as union, intersection and so on...
         */

        // TODO: optimize versions for less variadicities

        /**
         * Variadic function computing the intersection of multiple sets.
         *
         * @param  {...Set} sets - Sets to intersect.
         * @return {Set}         - The intesection.
         */
        exports.intersection = function () {
          if (arguments.length < 2) throw new Error('mnemonist/Set.intersection: needs at least two arguments.');
          var I = new Set();

          // First we need to find the smallest set
          var smallestSize = Infinity,
            smallestSet = null;
          var s,
            i,
            l = arguments.length;
          for (i = 0; i < l; i++) {
            s = arguments[i];

            // If one of the set has no items, we can stop right there
            if (s.size === 0) return I;
            if (s.size < smallestSize) {
              smallestSize = s.size;
              smallestSet = s;
            }
          }

          // Now we need to intersect this set with the others
          var iterator = smallestSet.values(),
            step,
            item,
            add,
            set;

          // TODO: we can optimize by iterating each next time over the current intersection
          // but this probably means more RAM to consume since we'll create n-1 sets rather than
          // only the one.
          while (step = iterator.next(), !step.done) {
            item = step.value;
            add = true;
            for (i = 0; i < l; i++) {
              set = arguments[i];
              if (set === smallestSet) continue;
              if (!set.has(item)) {
                add = false;
                break;
              }
            }
            if (add) I.add(item);
          }
          return I;
        };

        /**
         * Variadic function computing the union of multiple sets.
         *
         * @param  {...Set} sets - Sets to unite.
         * @return {Set}         - The union.
         */
        exports.union = function () {
          if (arguments.length < 2) throw new Error('mnemonist/Set.union: needs at least two arguments.');
          var U = new Set();
          var i,
            l = arguments.length;
          var iterator, step;
          for (i = 0; i < l; i++) {
            iterator = arguments[i].values();
            while (step = iterator.next(), !step.done) U.add(step.value);
          }
          return U;
        };

        /**
         * Function computing the difference between two sets.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {Set}   - The difference.
         */
        exports.difference = function (A, B) {
          // If first set is empty
          if (!A.size) return new Set();
          if (!B.size) return new Set(A);
          var D = new Set();
          var iterator = A.values(),
            step;
          while (step = iterator.next(), !step.done) {
            if (!B.has(step.value)) D.add(step.value);
          }
          return D;
        };

        /**
         * Function computing the symmetric difference between two sets.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {Set}   - The symmetric difference.
         */
        exports.symmetricDifference = function (A, B) {
          var S = new Set();
          var iterator = A.values(),
            step;
          while (step = iterator.next(), !step.done) {
            if (!B.has(step.value)) S.add(step.value);
          }
          iterator = B.values();
          while (step = iterator.next(), !step.done) {
            if (!A.has(step.value)) S.add(step.value);
          }
          return S;
        };

        /**
         * Function returning whether A is a subset of B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {boolean}
         */
        exports.isSubset = function (A, B) {
          var iterator = A.values(),
            step;

          // Shortcuts
          if (A === B) return true;
          if (A.size > B.size) return false;
          while (step = iterator.next(), !step.done) {
            if (!B.has(step.value)) return false;
          }
          return true;
        };

        /**
         * Function returning whether A is a superset of B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {boolean}
         */
        exports.isSuperset = function (A, B) {
          return exports.isSubset(B, A);
        };

        /**
         * Function adding the items of set B to the set A.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         */
        exports.add = function (A, B) {
          var iterator = B.values(),
            step;
          while (step = iterator.next(), !step.done) A.add(step.value);
          return;
        };

        /**
         * Function subtracting the items of set B from the set A.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         */
        exports.subtract = function (A, B) {
          var iterator = B.values(),
            step;
          while (step = iterator.next(), !step.done) A.delete(step.value);
          return;
        };

        /**
         * Function intersecting the items of A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         */
        exports.intersect = function (A, B) {
          var iterator = A.values(),
            step;
          while (step = iterator.next(), !step.done) {
            if (!B.has(step.value)) A.delete(step.value);
          }
          return;
        };

        /**
         * Function disjuncting the items of A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         */
        exports.disjunct = function (A, B) {
          var iterator = A.values(),
            step;
          var toRemove = [];
          while (step = iterator.next(), !step.done) {
            if (B.has(step.value)) toRemove.push(step.value);
          }
          iterator = B.values();
          while (step = iterator.next(), !step.done) {
            if (!A.has(step.value)) A.add(step.value);
          }
          for (var i = 0, l = toRemove.length; i < l; i++) A.delete(toRemove[i]);
          return;
        };

        /**
         * Function returning the size of the intersection of A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {number}
         */
        exports.intersectionSize = function (A, B) {
          var tmp;

          // We need to know the smallest set
          if (A.size > B.size) {
            tmp = A;
            A = B;
            B = tmp;
          }
          if (A.size === 0) return 0;
          if (A === B) return A.size;
          var iterator = A.values(),
            step;
          var I = 0;
          while (step = iterator.next(), !step.done) {
            if (B.has(step.value)) I++;
          }
          return I;
        };

        /**
         * Function returning the size of the union of A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {number}
         */
        exports.unionSize = function (A, B) {
          var I = exports.intersectionSize(A, B);
          return A.size + B.size - I;
        };

        /**
         * Function returning the Jaccard similarity between A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {number}
         */
        exports.jaccard = function (A, B) {
          var I = exports.intersectionSize(A, B);
          if (I === 0) return 0;
          var U = A.size + B.size - I;
          return I / U;
        };

        /**
         * Function returning the overlap coefficient between A & B.
         *
         * @param  {Set} A - First set.
         * @param  {Set} B - Second set.
         * @return {number}
         */
        exports.overlap = function (A, B) {
          var I = exports.intersectionSize(A, B);
          if (I === 0) return 0;
          return I / Math.min(A.size, B.size);
        };

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.intersection;
        module.exports.union;
        module.exports.difference;
        module.exports.symmetricDifference;
        module.exports.isSubset;
        module.exports.isSuperset;
        module.exports.add;
        module.exports.subtract;
        module.exports.intersect;
        module.exports.disjunct;
        module.exports.intersectionSize;
        module.exports.unionSize;
        module.exports.jaccard;
        module.exports.overlap;
      }, {});

      // I am the facade module who provides access to the CommonJS module './set.js'~
      if (!__cjsMetaURL) {
        loader.throwInvalidWrapper('./set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL);
      var __cjsMetaURL$1 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/comparators.js';
      loader.define(__cjsMetaURL$1, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Heap Comparators
         * ===========================
         *
         * Default comparators & functions dealing with comparators reversing etc.
         */
        var DEFAULT_COMPARATOR = function DEFAULT_COMPARATOR(a, b) {
          if (a < b) return -1;
          if (a > b) return 1;
          return 0;
        };
        var DEFAULT_REVERSE_COMPARATOR = function DEFAULT_REVERSE_COMPARATOR(a, b) {
          if (a < b) return 1;
          if (a > b) return -1;
          return 0;
        };

        /**
         * Function used to reverse a comparator.
         */
        function reverseComparator(comparator) {
          return function (a, b) {
            return comparator(b, a);
          };
        }

        /**
         * Function returning a tuple comparator.
         */
        function createTupleComparator(size) {
          if (size === 2) {
            return function (a, b) {
              if (a[0] < b[0]) return -1;
              if (a[0] > b[0]) return 1;
              if (a[1] < b[1]) return -1;
              if (a[1] > b[1]) return 1;
              return 0;
            };
          }
          return function (a, b) {
            var i = 0;
            while (i < size) {
              if (a[i] < b[i]) return -1;
              if (a[i] > b[i]) return 1;
              i++;
            }
            return 0;
          };
        }

        /**
         * Exporting.
         */
        exports.DEFAULT_COMPARATOR = DEFAULT_COMPARATOR;
        exports.DEFAULT_REVERSE_COMPARATOR = DEFAULT_REVERSE_COMPARATOR;
        exports.reverseComparator = reverseComparator;
        exports.createTupleComparator = createTupleComparator;

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.DEFAULT_COMPARATOR;
        module.exports.DEFAULT_REVERSE_COMPARATOR;
        module.exports.reverseComparator;
        module.exports.createTupleComparator;
      }, {});
      var __cjsMetaURL$2 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/obliterator@2.0.5/node_modules/obliterator/support.js';
      loader.define(__cjsMetaURL$2, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        exports.ARRAY_BUFFER_SUPPORT = typeof ArrayBuffer !== 'undefined';
        exports.SYMBOL_SUPPORT = typeof Symbol !== 'undefined';

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.ARRAY_BUFFER_SUPPORT;
        module.exports.SYMBOL_SUPPORT;
      }, {});
      var __cjsMetaURL$3 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/obliterator@2.0.5/node_modules/obliterator/foreach.js';
      loader.define(__cjsMetaURL$3, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Obliterator ForEach Function
         * =============================
         *
         * Helper function used to easily iterate over mixed values.
         */
        var support = require('./support.js');
        var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT;
        var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT;

        /**
         * Function able to iterate over almost any iterable JS value.
         *
         * @param  {any}      iterable - Iterable value.
         * @param  {function} callback - Callback function.
         */
        module.exports = function forEach(iterable, callback) {
          var iterator, k, i, l, s;
          if (!iterable) throw new Error('obliterator/forEach: invalid iterable.');
          if (typeof callback !== 'function') throw new Error('obliterator/forEach: expecting a callback.');

          // The target is an array or a string or function arguments
          if (Array.isArray(iterable) || ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable) || typeof iterable === 'string' || iterable.toString() === '[object Arguments]') {
            for (i = 0, l = iterable.length; i < l; i++) callback(iterable[i], i);
            return;
          }

          // The target has a #.forEach method
          if (typeof iterable.forEach === 'function') {
            iterable.forEach(callback);
            return;
          }

          // The target is iterable
          if (SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== 'function') {
            iterable = iterable[Symbol.iterator]();
          }

          // The target is an iterator
          if (typeof iterable.next === 'function') {
            iterator = iterable;
            i = 0;
            while (s = iterator.next(), s.done !== true) {
              callback(s.value, i);
              i++;
            }
            return;
          }

          // The target is a plain object
          for (k in iterable) {
            if (iterable.hasOwnProperty(k)) {
              callback(iterable[k], k);
            }
          }
          return;
        };

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './support.js': __cjsMetaURL$2
        };
      });
      var _cjsExports;
      var __cjsMetaURL$4 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fibonacci-heap.js';
      loader.define(__cjsMetaURL$4, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-constant-condition: 0 */
        /**
         * Mnemonist Fibonacci Heap
         * =========================
         *
         * Fibonacci heap implementation.
         */
        var comparators = require('./utils/comparators.js'),
          forEach = require('obliterator/foreach');
        var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR,
          reverseComparator = comparators.reverseComparator;

        /**
         * Fibonacci Heap.
         *
         * @constructor
         */
        function FibonacciHeap(comparator) {
          this.clear();
          this.comparator = comparator || DEFAULT_COMPARATOR;
          if (typeof this.comparator !== 'function') throw new Error('mnemonist/FibonacciHeap.constructor: given comparator should be a function.');
        }

        /**
         * Method used to clear the heap.
         *
         * @return {undefined}
         */
        FibonacciHeap.prototype.clear = function () {
          // Properties
          this.root = null;
          this.min = null;
          this.size = 0;
        };

        /**
         * Function used to create a node.
         *
         * @param  {any}    item - Target item.
         * @return {object}
         */
        function createNode(item) {
          return {
            item: item,
            degree: 0
          };
        }

        /**
         * Function used to merge the given node with the root list.
         *
         * @param {FibonacciHeap} heap - Target heap.
         * @param {Node}          node - Target node.
         */
        function mergeWithRoot(heap, node) {
          if (!heap.root) {
            heap.root = node;
          } else {
            node.right = heap.root.right;
            node.left = heap.root;
            heap.root.right.left = node;
            heap.root.right = node;
          }
        }

        /**
         * Method used to push an item into the heap.
         *
         * @param  {any}    item - Item to push.
         * @return {number}
         */
        FibonacciHeap.prototype.push = function (item) {
          var node = createNode(item);
          node.left = node;
          node.right = node;
          mergeWithRoot(this, node);
          if (!this.min || this.comparator(node.item, this.min.item) <= 0) this.min = node;
          return ++this.size;
        };

        /**
         * Method used to get the "first" item of the heap.
         *
         * @return {any}
         */
        FibonacciHeap.prototype.peek = function () {
          return this.min ? this.min.item : undefined;
        };

        /**
         * Function used to consume the given linked list.
         *
         * @param {Node} head - Head node.
         * @param {array}
         */
        function consumeLinkedList(head) {
          var nodes = [],
            node = head,
            flag = false;
          while (true) {
            if (node === head && flag) break;else if (node === head) flag = true;
            nodes.push(node);
            node = node.right;
          }
          return nodes;
        }

        /**
         * Function used to remove the target node from the root list.
         *
         * @param {FibonacciHeap} heap - Target heap.
         * @param {Node}          node - Target node.
         */
        function removeFromRoot(heap, node) {
          if (heap.root === node) heap.root = node.right;
          node.left.right = node.right;
          node.right.left = node.left;
        }

        /**
         * Function used to merge the given node with the child list of a root node.
         *
         * @param {Node} parent - Parent node.
         * @param {Node} node   - Target node.
         */
        function mergeWithChild(parent, node) {
          if (!parent.child) {
            parent.child = node;
          } else {
            node.right = parent.child.right;
            node.left = parent.child;
            parent.child.right.left = node;
            parent.child.right = node;
          }
        }

        /**
         * Function used to link one node to another in the root list.
         *
         * @param {FibonacciHeap} heap - Target heap.
         * @param {Node}          y - Y node.
         * @param {Node}          x - X node.
         */
        function link(heap, y, x) {
          removeFromRoot(heap, y);
          y.left = y;
          y.right = y;
          mergeWithChild(x, y);
          x.degree++;
          y.parent = x;
        }

        /**
         * Function used to consolidate the heap.
         *
         * @param {FibonacciHeap} heap - Target heap.
         */
        function consolidate(heap) {
          var A = new Array(heap.size),
            nodes = consumeLinkedList(heap.root),
            i,
            l,
            x,
            y,
            d,
            t;
          for (i = 0, l = nodes.length; i < l; i++) {
            x = nodes[i];
            d = x.degree;
            while (A[d]) {
              y = A[d];
              if (heap.comparator(x.item, y.item) > 0) {
                t = x;
                x = y;
                y = t;
              }
              link(heap, y, x);
              A[d] = null;
              d++;
            }
            A[d] = x;
          }
          for (i = 0; i < heap.size; i++) {
            if (A[i] && heap.comparator(A[i].item, heap.min.item) <= 0) heap.min = A[i];
          }
        }

        /**
         * Method used to retrieve & remove the "first" item of the heap.
         *
         * @return {any}
         */
        FibonacciHeap.prototype.pop = function () {
          if (!this.size) return undefined;
          var z = this.min;
          if (z.child) {
            var nodes = consumeLinkedList(z.child),
              node,
              i,
              l;
            for (i = 0, l = nodes.length; i < l; i++) {
              node = nodes[i];
              mergeWithRoot(this, node);
              delete node.parent;
            }
          }
          removeFromRoot(this, z);
          if (z === z.right) {
            this.min = null;
            this.root = null;
          } else {
            this.min = z.right;
            consolidate(this);
          }
          this.size--;
          return z.item;
        };

        /**
         * Convenience known methods.
         */
        FibonacciHeap.prototype.inspect = function () {
          var proxy = {
            size: this.size
          };
          if (this.min && 'item' in this.min) proxy.top = this.min.item;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: FibonacciHeap,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') FibonacciHeap.prototype[Symbol.for('nodejs.util.inspect.custom')] = FibonacciHeap.prototype.inspect;

        /**
         * Fibonacci Maximum Heap.
         *
         * @constructor
         */
        function MaxFibonacciHeap(comparator) {
          this.clear();
          this.comparator = comparator || DEFAULT_COMPARATOR;
          if (typeof this.comparator !== 'function') throw new Error('mnemonist/FibonacciHeap.constructor: given comparator should be a function.');
          this.comparator = reverseComparator(this.comparator);
        }
        MaxFibonacciHeap.prototype = FibonacciHeap.prototype;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a heap.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} comparator - Custom comparator function.
         * @return {FibonacciHeap}
         */
        FibonacciHeap.from = function (iterable, comparator) {
          var heap = new FibonacciHeap(comparator);
          forEach(iterable, function (value) {
            heap.push(value);
          });
          return heap;
        };
        MaxFibonacciHeap.from = function (iterable, comparator) {
          var heap = new MaxFibonacciHeap(comparator);
          forEach(iterable, function (value) {
            heap.push(value);
          });
          return heap;
        };

        /**
         * Exporting.
         */
        FibonacciHeap.MinFibonacciHeap = FibonacciHeap;
        FibonacciHeap.MaxFibonacciHeap = MaxFibonacciHeap;
        module.exports = FibonacciHeap;

        // #endregion ORIGINAL CODE

        _cjsExports = module.exports;
      }, function () {
        return {
          './utils/comparators.js': __cjsMetaURL$1,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './fibonacci-heap.js'~
      if (!__cjsMetaURL$4) {
        loader.throwInvalidWrapper('./fibonacci-heap.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fibonacci-heap.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$4);
      var __cjsMetaURL$5 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/typed-arrays.js';
      loader.define(__cjsMetaURL$5, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Typed Array Helpers
         * ==============================
         *
         * Miscellaneous helpers related to typed arrays.
         */

        /**
         * When using an unsigned integer array to store pointers, one might want to
         * choose the optimal word size in regards to the actual numbers of pointers
         * to store.
         *
         * This helpers does just that.
         *
         * @param  {number} size - Expected size of the array to map.
         * @return {TypedArray}
         */
        var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1,
          MAX_16BIT_INTEGER = Math.pow(2, 16) - 1,
          MAX_32BIT_INTEGER = Math.pow(2, 32) - 1;
        var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1,
          MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1,
          MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1;
        exports.getPointerArray = function (size) {
          var maxIndex = size - 1;
          if (maxIndex <= MAX_8BIT_INTEGER) return Uint8Array;
          if (maxIndex <= MAX_16BIT_INTEGER) return Uint16Array;
          if (maxIndex <= MAX_32BIT_INTEGER) return Uint32Array;
          throw new Error('mnemonist: Pointer Array of size > 4294967295 is not supported.');
        };
        exports.getSignedPointerArray = function (size) {
          var maxIndex = size - 1;
          if (maxIndex <= MAX_SIGNED_8BIT_INTEGER) return Int8Array;
          if (maxIndex <= MAX_SIGNED_16BIT_INTEGER) return Int16Array;
          if (maxIndex <= MAX_SIGNED_32BIT_INTEGER) return Int32Array;
          return Float64Array;
        };

        /**
         * Function returning the minimal type able to represent the given number.
         *
         * @param  {number} value - Value to test.
         * @return {TypedArrayClass}
         */
        exports.getNumberType = function (value) {
          // <= 32 bits itnteger?
          if (value === (value | 0)) {
            // Negative
            if (Math.sign(value) === -1) {
              if (value <= 127 && value >= -128) return Int8Array;
              if (value <= 32767 && value >= -32768) return Int16Array;
              return Int32Array;
            } else {
              if (value <= 255) return Uint8Array;
              if (value <= 65535) return Uint16Array;
              return Uint32Array;
            }
          }

          // 53 bits integer & floats
          // NOTE: it's kinda hard to tell whether we could use 32bits or not...
          return Float64Array;
        };

        /**
         * Function returning the minimal type able to represent the given array
         * of JavaScript numbers.
         *
         * @param  {array}    array  - Array to represent.
         * @param  {function} getter - Optional getter.
         * @return {TypedArrayClass}
         */
        var TYPE_PRIORITY = {
          Uint8Array: 1,
          Int8Array: 2,
          Uint16Array: 3,
          Int16Array: 4,
          Uint32Array: 5,
          Int32Array: 6,
          Float32Array: 7,
          Float64Array: 8
        };

        // TODO: make this a one-shot for one value
        exports.getMinimalRepresentation = function (array, getter) {
          var maxType = null,
            maxPriority = 0,
            p,
            t,
            v,
            i,
            l;
          for (i = 0, l = array.length; i < l; i++) {
            v = getter ? getter(array[i]) : array[i];
            t = exports.getNumberType(v);
            p = TYPE_PRIORITY[t.name];
            if (p > maxPriority) {
              maxPriority = p;
              maxType = t;
            }
          }
          return maxType;
        };

        /**
         * Function returning whether the given value is a typed array.
         *
         * @param  {any} value - Value to test.
         * @return {boolean}
         */
        exports.isTypedArray = function (value) {
          return typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value);
        };

        /**
         * Function used to concat byte arrays.
         *
         * @param  {...ByteArray}
         * @return {ByteArray}
         */
        exports.concat = function () {
          var length = 0,
            i,
            o,
            l;
          for (i = 0, l = arguments.length; i < l; i++) length += arguments[i].length;
          var array = new arguments[0].constructor(length);
          for (i = 0, o = 0; i < l; i++) {
            array.set(arguments[i], o);
            o += arguments[i].length;
          }
          return array;
        };

        /**
         * Function used to initialize a byte array of indices.
         *
         * @param  {number}    length - Length of target.
         * @return {ByteArray}
         */
        exports.indices = function (length) {
          var PointerArray = exports.getPointerArray(length);
          var array = new PointerArray(length);
          for (var i = 0; i < length; i++) array[i] = i;
          return array;
        };

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.getPointerArray;
        module.exports.getSignedPointerArray;
        module.exports.getNumberType;
        module.exports.getMinimalRepresentation;
        module.exports.isTypedArray;
        module.exports.concat;
        module.exports.indices;
      }, {});
      var __cjsMetaURL$6 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/iterables.js';
      loader.define(__cjsMetaURL$6, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Iterable Function
         * ============================
         *
         * Harmonized iteration helpers over mixed iterable targets.
         */
        var forEach = require('obliterator/foreach');
        var typed = require('./typed-arrays.js');

        /**
         * Function used to determine whether the given object supports array-like
         * random access.
         *
         * @param  {any} target - Target object.
         * @return {boolean}
         */
        function isArrayLike(target) {
          return Array.isArray(target) || typed.isTypedArray(target);
        }

        /**
         * Function used to guess the length of the structure over which we are going
         * to iterate.
         *
         * @param  {any} target - Target object.
         * @return {number|undefined}
         */
        function guessLength(target) {
          if (typeof target.length === 'number') return target.length;
          if (typeof target.size === 'number') return target.size;
          return;
        }

        /**
         * Function used to convert an iterable to an array.
         *
         * @param  {any}   target - Iteration target.
         * @return {array}
         */
        function toArray(target) {
          var l = guessLength(target);
          var array = typeof l === 'number' ? new Array(l) : [];
          var i = 0;

          // TODO: we could optimize when given target is array like
          forEach(target, function (value) {
            array[i++] = value;
          });
          return array;
        }

        /**
         * Same as above but returns a supplementary indices array.
         *
         * @param  {any}   target - Iteration target.
         * @return {array}
         */
        function toArrayWithIndices(target) {
          var l = guessLength(target);
          var IndexArray = typeof l === 'number' ? typed.getPointerArray(l) : Array;
          var array = typeof l === 'number' ? new Array(l) : [];
          var indices = typeof l === 'number' ? new IndexArray(l) : [];
          var i = 0;

          // TODO: we could optimize when given target is array like
          forEach(target, function (value) {
            array[i] = value;
            indices[i] = i++;
          });
          return [array, indices];
        }

        /**
         * Exporting.
         */
        exports.isArrayLike = isArrayLike;
        exports.guessLength = guessLength;
        exports.toArray = toArray;
        exports.toArrayWithIndices = toArrayWithIndices;

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.isArrayLike;
        module.exports.guessLength;
        module.exports.toArray;
        module.exports.toArrayWithIndices;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3,
          './typed-arrays.js': __cjsMetaURL$5
        };
      });
      var _cjsExports$1;
      var __cjsMetaURL$7 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/heap.js';
      loader.define(__cjsMetaURL$7, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Binary Heap
         * ======================
         *
         * Binary heap implementation.
         */
        var forEach = require('obliterator/foreach'),
          comparators = require('./utils/comparators.js'),
          iterables = require('./utils/iterables.js');
        var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR,
          reverseComparator = comparators.reverseComparator;

        /**
         * Heap helper functions.
         */

        /**
         * Function used to sift down.
         *
         * @param {function} compare    - Comparison function.
         * @param {array}    heap       - Array storing the heap's data.
         * @param {number}   startIndex - Starting index.
         * @param {number}   i          - Index.
         */
        function siftDown(compare, heap, startIndex, i) {
          var item = heap[i],
            parentIndex,
            parent;
          while (i > startIndex) {
            parentIndex = i - 1 >> 1;
            parent = heap[parentIndex];
            if (compare(item, parent) < 0) {
              heap[i] = parent;
              i = parentIndex;
              continue;
            }
            break;
          }
          heap[i] = item;
        }

        /**
         * Function used to sift up.
         *
         * @param {function} compare - Comparison function.
         * @param {array}    heap    - Array storing the heap's data.
         * @param {number}   i       - Index.
         */
        function siftUp(compare, heap, i) {
          var endIndex = heap.length,
            startIndex = i,
            item = heap[i],
            childIndex = 2 * i + 1,
            rightIndex;
          while (childIndex < endIndex) {
            rightIndex = childIndex + 1;
            if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
              childIndex = rightIndex;
            }
            heap[i] = heap[childIndex];
            i = childIndex;
            childIndex = 2 * i + 1;
          }
          heap[i] = item;
          siftDown(compare, heap, startIndex, i);
        }

        /**
         * Function used to push an item into a heap represented by a raw array.
         *
         * @param {function} compare - Comparison function.
         * @param {array}    heap    - Array storing the heap's data.
         * @param {any}      item    - Item to push.
         */
        function push(compare, heap, item) {
          heap.push(item);
          siftDown(compare, heap, 0, heap.length - 1);
        }

        /**
         * Function used to pop an item from a heap represented by a raw array.
         *
         * @param  {function} compare - Comparison function.
         * @param  {array}    heap    - Array storing the heap's data.
         * @return {any}
         */
        function pop(compare, heap) {
          var lastItem = heap.pop();
          if (heap.length !== 0) {
            var item = heap[0];
            heap[0] = lastItem;
            siftUp(compare, heap, 0);
            return item;
          }
          return lastItem;
        }

        /**
         * Function used to pop the heap then push a new value into it, thus "replacing"
         * it.
         *
         * @param  {function} compare - Comparison function.
         * @param  {array}    heap    - Array storing the heap's data.
         * @param  {any}      item    - The item to push.
         * @return {any}
         */
        function replace(compare, heap, item) {
          if (heap.length === 0) throw new Error('mnemonist/heap.replace: cannot pop an empty heap.');
          var popped = heap[0];
          heap[0] = item;
          siftUp(compare, heap, 0);
          return popped;
        }

        /**
         * Function used to push an item in the heap then pop the heap and return the
         * popped value.
         *
         * @param  {function} compare - Comparison function.
         * @param  {array}    heap    - Array storing the heap's data.
         * @param  {any}      item    - The item to push.
         * @return {any}
         */
        function pushpop(compare, heap, item) {
          var tmp;
          if (heap.length !== 0 && compare(heap[0], item) < 0) {
            tmp = heap[0];
            heap[0] = item;
            item = tmp;
            siftUp(compare, heap, 0);
          }
          return item;
        }

        /**
         * Converts and array into an abstract heap in linear time.
         *
         * @param {function} compare - Comparison function.
         * @param {array}    array   - Target array.
         */
        function heapify(compare, array) {
          var n = array.length,
            l = n >> 1,
            i = l;
          while (--i >= 0) siftUp(compare, array, i);
        }

        /**
         * Fully consumes the given heap.
         *
         * @param  {function} compare - Comparison function.
         * @param  {array}    heap    - Array storing the heap's data.
         * @return {array}
         */
        function consume(compare, heap) {
          var l = heap.length,
            i = 0;
          var array = new Array(l);
          while (i < l) array[i++] = pop(compare, heap);
          return array;
        }

        /**
         * Function used to retrieve the n smallest items from the given iterable.
         *
         * @param {function} compare  - Comparison function.
         * @param {number}   n        - Number of top items to retrieve.
         * @param {any}      iterable - Arbitrary iterable.
         * @param {array}
         */
        function nsmallest(compare, n, iterable) {
          if (arguments.length === 2) {
            iterable = n;
            n = compare;
            compare = DEFAULT_COMPARATOR;
          }
          var reverseCompare = reverseComparator(compare);
          var i, l, v;
          var min = Infinity;
          var result;

          // If n is equal to 1, it's just a matter of finding the minimum
          if (n === 1) {
            if (iterables.isArrayLike(iterable)) {
              for (i = 0, l = iterable.length; i < l; i++) {
                v = iterable[i];
                if (min === Infinity || compare(v, min) < 0) min = v;
              }
              result = new iterable.constructor(1);
              result[0] = min;
              return result;
            }
            forEach(iterable, function (value) {
              if (min === Infinity || compare(value, min) < 0) min = value;
            });
            return [min];
          }
          if (iterables.isArrayLike(iterable)) {
            // If n > iterable length, we just clone and sort
            if (n >= iterable.length) return iterable.slice().sort(compare);
            result = iterable.slice(0, n);
            heapify(reverseCompare, result);
            for (i = n, l = iterable.length; i < l; i++) if (reverseCompare(iterable[i], result[0]) > 0) replace(reverseCompare, result, iterable[i]);

            // NOTE: if n is over some number, it becomes faster to consume the heap
            return result.sort(compare);
          }

          // Correct for size
          var size = iterables.guessLength(iterable);
          if (size !== null && size < n) n = size;
          result = new Array(n);
          i = 0;
          forEach(iterable, function (value) {
            if (i < n) {
              result[i] = value;
            } else {
              if (i === n) heapify(reverseCompare, result);
              if (reverseCompare(value, result[0]) > 0) replace(reverseCompare, result, value);
            }
            i++;
          });
          if (result.length > i) result.length = i;

          // NOTE: if n is over some number, it becomes faster to consume the heap
          return result.sort(compare);
        }

        /**
         * Function used to retrieve the n largest items from the given iterable.
         *
         * @param {function} compare  - Comparison function.
         * @param {number}   n        - Number of top items to retrieve.
         * @param {any}      iterable - Arbitrary iterable.
         * @param {array}
         */
        function nlargest(compare, n, iterable) {
          if (arguments.length === 2) {
            iterable = n;
            n = compare;
            compare = DEFAULT_COMPARATOR;
          }
          var reverseCompare = reverseComparator(compare);
          var i, l, v;
          var max = -Infinity;
          var result;

          // If n is equal to 1, it's just a matter of finding the maximum
          if (n === 1) {
            if (iterables.isArrayLike(iterable)) {
              for (i = 0, l = iterable.length; i < l; i++) {
                v = iterable[i];
                if (max === -Infinity || compare(v, max) > 0) max = v;
              }
              result = new iterable.constructor(1);
              result[0] = max;
              return result;
            }
            forEach(iterable, function (value) {
              if (max === -Infinity || compare(value, max) > 0) max = value;
            });
            return [max];
          }
          if (iterables.isArrayLike(iterable)) {
            // If n > iterable length, we just clone and sort
            if (n >= iterable.length) return iterable.slice().sort(reverseCompare);
            result = iterable.slice(0, n);
            heapify(compare, result);
            for (i = n, l = iterable.length; i < l; i++) if (compare(iterable[i], result[0]) > 0) replace(compare, result, iterable[i]);

            // NOTE: if n is over some number, it becomes faster to consume the heap
            return result.sort(reverseCompare);
          }

          // Correct for size
          var size = iterables.guessLength(iterable);
          if (size !== null && size < n) n = size;
          result = new Array(n);
          i = 0;
          forEach(iterable, function (value) {
            if (i < n) {
              result[i] = value;
            } else {
              if (i === n) heapify(compare, result);
              if (compare(value, result[0]) > 0) replace(compare, result, value);
            }
            i++;
          });
          if (result.length > i) result.length = i;

          // NOTE: if n is over some number, it becomes faster to consume the heap
          return result.sort(reverseCompare);
        }

        /**
         * Binary Minimum Heap.
         *
         * @constructor
         * @param {function} comparator - Comparator function to use.
         */
        function Heap(comparator) {
          this.clear();
          this.comparator = comparator || DEFAULT_COMPARATOR;
          if (typeof this.comparator !== 'function') throw new Error('mnemonist/Heap.constructor: given comparator should be a function.');
        }

        /**
         * Method used to clear the heap.
         *
         * @return {undefined}
         */
        Heap.prototype.clear = function () {
          // Properties
          this.items = [];
          this.size = 0;
        };

        /**
         * Method used to push an item into the heap.
         *
         * @param  {any}    item - Item to push.
         * @return {number}
         */
        Heap.prototype.push = function (item) {
          push(this.comparator, this.items, item);
          return ++this.size;
        };

        /**
         * Method used to retrieve the "first" item of the heap.
         *
         * @return {any}
         */
        Heap.prototype.peek = function () {
          return this.items[0];
        };

        /**
         * Method used to retrieve & remove the "first" item of the heap.
         *
         * @return {any}
         */
        Heap.prototype.pop = function () {
          if (this.size !== 0) this.size--;
          return pop(this.comparator, this.items);
        };

        /**
         * Method used to pop the heap, then push an item and return the popped
         * item.
         *
         * @param  {any} item - Item to push into the heap.
         * @return {any}
         */
        Heap.prototype.replace = function (item) {
          return replace(this.comparator, this.items, item);
        };

        /**
         * Method used to push the heap, the pop it and return the pooped item.
         *
         * @param  {any} item - Item to push into the heap.
         * @return {any}
         */
        Heap.prototype.pushpop = function (item) {
          return pushpop(this.comparator, this.items, item);
        };

        /**
         * Method used to consume the heap fully and return its items as a sorted array.
         *
         * @return {array}
         */
        Heap.prototype.consume = function () {
          this.size = 0;
          return consume(this.comparator, this.items);
        };

        /**
         * Method used to convert the heap to an array. Note that it basically clone
         * the heap and consumes it completely. This is hardly performant.
         *
         * @return {array}
         */
        Heap.prototype.toArray = function () {
          return consume(this.comparator, this.items.slice());
        };

        /**
         * Convenience known methods.
         */
        Heap.prototype.inspect = function () {
          var proxy = this.toArray();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: Heap,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') Heap.prototype[Symbol.for('nodejs.util.inspect.custom')] = Heap.prototype.inspect;

        /**
         * Binary Maximum Heap.
         *
         * @constructor
         * @param {function} comparator - Comparator function to use.
         */
        function MaxHeap(comparator) {
          this.clear();
          this.comparator = comparator || DEFAULT_COMPARATOR;
          if (typeof this.comparator !== 'function') throw new Error('mnemonist/MaxHeap.constructor: given comparator should be a function.');
          this.comparator = reverseComparator(this.comparator);
        }
        MaxHeap.prototype = Heap.prototype;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a heap.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} comparator - Custom comparator function.
         * @return {Heap}
         */
        Heap.from = function (iterable, comparator) {
          var heap = new Heap(comparator);
          var items;

          // If iterable is an array, we can be clever about it
          if (iterables.isArrayLike(iterable)) items = iterable.slice();else items = iterables.toArray(iterable);
          heapify(heap.comparator, items);
          heap.items = items;
          heap.size = items.length;
          return heap;
        };
        MaxHeap.from = function (iterable, comparator) {
          var heap = new MaxHeap(comparator);
          var items;

          // If iterable is an array, we can be clever about it
          if (iterables.isArrayLike(iterable)) items = iterable.slice();else items = iterables.toArray(iterable);
          heapify(heap.comparator, items);
          heap.items = items;
          heap.size = items.length;
          return heap;
        };

        /**
         * Exporting.
         */
        Heap.siftUp = siftUp;
        Heap.siftDown = siftDown;
        Heap.push = push;
        Heap.pop = pop;
        Heap.replace = replace;
        Heap.pushpop = pushpop;
        Heap.heapify = heapify;
        Heap.consume = consume;
        Heap.nsmallest = nsmallest;
        Heap.nlargest = nlargest;
        Heap.MinHeap = Heap;
        Heap.MaxHeap = MaxHeap;
        module.exports = Heap;

        // #endregion ORIGINAL CODE

        _cjsExports$1 = module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/comparators.js': __cjsMetaURL$1,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });

      // I am the facade module who provides access to the CommonJS module './heap.js'~
      if (!__cjsMetaURL$7) {
        loader.throwInvalidWrapper('./heap.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/heap.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$7);
      var _cjsExports$2;
      var __cjsMetaURL$8 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/suffix-array.js';
      loader.define(__cjsMetaURL$8, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Suffix Array
         * =======================
         *
         * Linear time implementation of a suffix array using the recursive
         * method by Karkkainen and Sanders.
         *
         * [References]:
         * https://www.cs.helsinki.fi/u/tpkarkka/publications/jacm05-revised.pdf
         * http://people.mpi-inf.mpg.de/~sanders/programs/suffix/
         * http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.184.442&rep=rep1&type=pdf
         *
         * [Article]:
         * "Simple Linear Work Suffix Array Construction", Karkkainen and Sanders.
         *
         * [Note]:
         * A paper by Simon J. Puglisi, William F. Smyth & Andrew Turpin named
         * "The Performance of Linear Time Suffix Sorting Algorithms" seems to
         * prove that supralinear algorithm are in fact better faring for
         * "real" world use cases. It would be nice to check this out in JavaScript
         * because the high level of the language could change a lot to the fact.
         *
         * The current code is largely inspired by the following:
         * https://github.com/tixxit/suffixarray/blob/master/suffixarray.js
         */

        /**
         * Constants.
         */
        var SEPARATOR = "\x01";

        /**
         * Function used to sort the triples.
         *
         * @param {string|array} string - Padded sequence.
         * @param {array}        array  - Array to sort (will be mutated).
         * @param {number}       offset - Index offset.
         */
        function sort(string, array, offset) {
          var l = array.length,
            buckets = [],
            i = l,
            j = -1,
            b,
            d = 0,
            bits;
          while (i--) j = Math.max(string[array[i] + offset], j);
          bits = j >> 24 && 32 || j >> 16 && 24 || j >> 8 && 16 || 8;
          for (; d < bits; d += 4) {
            for (i = 16; i--;) buckets[i] = [];
            for (i = l; i--;) buckets[string[array[i] + offset] >> d & 15].push(array[i]);
            for (b = 0; b < 16; b++) {
              for (j = buckets[b].length; j--;) array[++i] = buckets[b][j];
            }
          }
        }

        /**
         * Comparison helper.
         */
        function compare(string, lookup, m, n) {
          return string[m] - string[n] || (m % 3 === 2 ? string[m + 1] - string[n + 1] || lookup[m + 2] - lookup[n + 2] : lookup[m + 1] - lookup[n + 1]);
        }

        /**
         * Recursive function used to build the suffix tree in linear time.
         *
         * @param  {string|array} string - Padded sequence.
         * @param  {number}       l      - True length of sequence (unpadded).
         * @return {array}
         */
        function build(string, l) {
          var a = [],
            b = [],
            al = 2 * l / 3 | 0,
            bl = l - al,
            r = al + 1 >> 1,
            i = al,
            j = 0,
            k,
            lookup = [],
            result = [];
          if (l === 1) return [0];
          while (i--) a[i] = (i * 3 >> 1) + 1;
          for (i = 3; i--;) sort(string, a, i);
          j = b[(a[0] / 3 | 0) + (a[0] % 3 === 1 ? 0 : r)] = 1;
          for (i = 1; i < al; i++) {
            if (string[a[i]] !== string[a[i - 1]] || string[a[i] + 1] !== string[a[i - 1] + 1] || string[a[i] + 2] !== string[a[i - 1] + 2]) j++;
            b[(a[i] / 3 | 0) + (a[i] % 3 === 1 ? 0 : r)] = j;
          }
          if (j < al) {
            b = build(b, al);
            for (i = al; i--;) a[i] = b[i] < r ? b[i] * 3 + 1 : (b[i] - r) * 3 + 2;
          }
          for (i = al; i--;) lookup[a[i]] = i;
          lookup[l] = -1;
          lookup[l + 1] = -2;
          b = l % 3 === 1 ? [l - 1] : [];
          for (i = 0; i < al; i++) {
            if (a[i] % 3 === 1) b.push(a[i] - 1);
          }
          sort(string, b, 0);
          for (i = 0, j = 0, k = 0; i < al && j < bl;) result[k++] = compare(string, lookup, a[i], b[j]) < 0 ? a[i++] : b[j++];
          while (i < al) result[k++] = a[i++];
          while (j < bl) result[k++] = b[j++];
          return result;
        }

        /**
         * Function used to create the array we are going to work on.
         *
         * @param  {string|array} target - Target sequence.
         * @return {array}
         */
        function convert(target) {
          // Creating the alphabet array
          var length = target.length,
            paddingOffset = length % 3,
            array = new Array(length + paddingOffset),
            l,
            i;

          // If we have an arbitrary sequence, we need to transform it
          if (typeof target !== 'string') {
            var uniqueTokens = Object.create(null);
            for (i = 0; i < length; i++) {
              if (!uniqueTokens[target[i]]) uniqueTokens[target[i]] = true;
            }
            var alphabet = Object.create(null),
              sortedUniqueTokens = Object.keys(uniqueTokens).sort();
            for (i = 0, l = sortedUniqueTokens.length; i < l; i++) alphabet[sortedUniqueTokens[i]] = i + 1;
            for (i = 0; i < length; i++) {
              array[i] = alphabet[target[i]];
            }
          } else {
            for (i = 0; i < length; i++) array[i] = target.charCodeAt(i);
          }

          // Padding the array
          for (i = length; i < length + paddingOffset; i++) array[i] = 0;
          return array;
        }

        /**
         * Suffix Array.
         *
         * @constructor
         * @param {string|array} string - Sequence for which to build the suffix array.
         */
        function SuffixArray(string) {
          // Properties
          this.hasArbitrarySequence = typeof string !== 'string';
          this.string = string;
          this.length = string.length;

          // Building the array
          this.array = build(convert(string), this.length);
        }

        /**
         * Convenience known methods.
         */
        SuffixArray.prototype.toString = function () {
          return this.array.join(',');
        };
        SuffixArray.prototype.toJSON = function () {
          return this.array;
        };
        SuffixArray.prototype.inspect = function () {
          var array = new Array(this.length);
          for (var i = 0; i < this.length; i++) array[i] = this.string.slice(this.array[i]);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: SuffixArray,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') SuffixArray.prototype[Symbol.for('nodejs.util.inspect.custom')] = SuffixArray.prototype.inspect;

        /**
         * Generalized Suffix Array.
         *
         * @constructor
         */
        function GeneralizedSuffixArray(strings) {
          // Properties
          this.hasArbitrarySequence = typeof strings[0] !== 'string';
          this.size = strings.length;
          if (this.hasArbitrarySequence) {
            this.text = [];
            for (var i = 0, l = this.size; i < l; i++) {
              this.text.push.apply(this.text, strings[i]);
              if (i < l - 1) this.text.push(SEPARATOR);
            }
          } else {
            this.text = strings.join(SEPARATOR);
          }
          this.firstLength = strings[0].length;
          this.length = this.text.length;

          // Building the array
          this.array = build(convert(this.text), this.length);
        }

        /**
         * Method used to retrieve the longest common subsequence of the generalized
         * suffix array.
         *
         * @return {string|array}
         */
        GeneralizedSuffixArray.prototype.longestCommonSubsequence = function () {
          var lcs = this.hasArbitrarySequence ? [] : '',
            lcp,
            i,
            j,
            s,
            t;
          for (i = 1; i < this.length; i++) {
            s = this.array[i];
            t = this.array[i - 1];
            if (s < this.firstLength && t < this.firstLength) continue;
            if (s > this.firstLength && t > this.firstLength) continue;
            lcp = Math.min(this.length - s, this.length - t);
            for (j = 0; j < lcp; j++) {
              if (this.text[s + j] !== this.text[t + j]) {
                lcp = j;
                break;
              }
            }
            if (lcp > lcs.length) lcs = this.text.slice(s, s + lcp);
          }
          return lcs;
        };

        /**
         * Convenience known methods.
         */
        GeneralizedSuffixArray.prototype.toString = function () {
          return this.array.join(',');
        };
        GeneralizedSuffixArray.prototype.toJSON = function () {
          return this.array;
        };
        GeneralizedSuffixArray.prototype.inspect = function () {
          var array = new Array(this.length);
          for (var i = 0; i < this.length; i++) array[i] = this.text.slice(this.array[i]);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: GeneralizedSuffixArray,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') GeneralizedSuffixArray.prototype[Symbol.for('nodejs.util.inspect.custom')] = GeneralizedSuffixArray.prototype.inspect;

        /**
         * Exporting.
         */
        SuffixArray.GeneralizedSuffixArray = GeneralizedSuffixArray;
        module.exports = SuffixArray;

        // #endregion ORIGINAL CODE

        _cjsExports$2 = module.exports;
      }, {});

      // I am the facade module who provides access to the CommonJS module './suffix-array.js'~
      if (!__cjsMetaURL$8) {
        loader.throwInvalidWrapper('./suffix-array.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/suffix-array.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$8);
      var __cjsMetaURL$9 = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/obliterator@2.0.5/node_modules/obliterator/iterator.js';
      loader.define(__cjsMetaURL$9, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Obliterator Iterator Class
         * ===========================
         *
         * Simple class representing the library's iterators.
         */

        /**
         * Iterator class.
         *
         * @constructor
         * @param {function} next - Next function.
         */
        function Iterator(next) {
          if (typeof next !== 'function') throw new Error('obliterator/iterator: expecting a function!');
          this.next = next;
        }

        /**
         * If symbols are supported, we add `next` to `Symbol.iterator`.
         */
        if (typeof Symbol !== 'undefined') Iterator.prototype[Symbol.iterator] = function () {
          return this;
        };

        /**
         * Returning an iterator of the given values.
         *
         * @param  {any...} values - Values.
         * @return {Iterator}
         */
        Iterator.of = function () {
          var args = arguments,
            l = args.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            return {
              done: false,
              value: args[i++]
            };
          });
        };

        /**
         * Returning an empty iterator.
         *
         * @return {Iterator}
         */
        Iterator.empty = function () {
          var iterator = new Iterator(function () {
            return {
              done: true
            };
          });
          return iterator;
        };

        /**
         * Returning an iterator over the given indexed sequence.
         *
         * @param  {string|Array} sequence - Target sequence.
         * @return {Iterator}
         */
        Iterator.fromSequence = function (sequence) {
          var i = 0,
            l = sequence.length;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            return {
              done: false,
              value: sequence[i++]
            };
          });
        };

        /**
         * Returning whether the given value is an iterator.
         *
         * @param  {any} value - Value.
         * @return {boolean}
         */
        Iterator.is = function (value) {
          if (value instanceof Iterator) return true;
          return typeof value === 'object' && value !== null && typeof value.next === 'function';
        };

        /**
         * Exporting.
         */
        module.exports = Iterator;

        // #endregion ORIGINAL CODE

        module.exports;
      }, {});
      var _cjsExports$3;
      var __cjsMetaURL$a = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/vector.js';
      loader.define(__cjsMetaURL$a, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Vector
         * =================
         *
         * Abstract implementation of a growing array that can be used with JavaScript
         * typed arrays and other array-like structures.
         *
         * Note: should try and use ArrayBuffer.transfer when it will be available.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach'),
          iterables = require('./utils/iterables.js'),
          typed = require('./utils/typed-arrays.js');

        /**
         * Defaults.
         */
        var DEFAULT_GROWING_POLICY = function DEFAULT_GROWING_POLICY(currentCapacity) {
          return Math.max(1, Math.ceil(currentCapacity * 1.5));
        };
        var pointerArrayFactory = function pointerArrayFactory(capacity) {
          var PointerArray = typed.getPointerArray(capacity);
          return new PointerArray(capacity);
        };

        /**
         * Vector.
         *
         * @constructor
         * @param {function}      ArrayClass             - An array constructor.
         * @param {number|object} initialCapacityOrOptions - Self-explanatory:
         * @param {number}        initialCapacity          - Initial capacity.
         * @param {number}        initialLength            - Initial length.
         * @param {function}      policy                   - Allocation policy.
         */
        function Vector(ArrayClass, initialCapacityOrOptions) {
          if (arguments.length < 1) throw new Error('mnemonist/vector: expecting at least a byte array constructor.');
          var initialCapacity = initialCapacityOrOptions || 0,
            policy = DEFAULT_GROWING_POLICY,
            initialLength = 0,
            factory = false;
          if (typeof initialCapacityOrOptions === 'object') {
            initialCapacity = initialCapacityOrOptions.initialCapacity || 0;
            initialLength = initialCapacityOrOptions.initialLength || 0;
            policy = initialCapacityOrOptions.policy || policy;
            factory = initialCapacityOrOptions.factory === true;
          }
          this.factory = factory ? ArrayClass : null;
          this.ArrayClass = ArrayClass;
          this.length = initialLength;
          this.capacity = Math.max(initialLength, initialCapacity);
          this.policy = policy;
          this.array = new ArrayClass(this.capacity);
        }

        /**
         * Method used to set a value.
         *
         * @param  {number} index - Index to edit.
         * @param  {any}    value - Value.
         * @return {Vector}
         */
        Vector.prototype.set = function (index, value) {
          // Out of bounds?
          if (this.length < index) throw new Error('Vector(' + this.ArrayClass.name + ').set: index out of bounds.');

          // Updating value
          this.array[index] = value;
          return this;
        };

        /**
         * Method used to get a value.
         *
         * @param  {number} index - Index to retrieve.
         * @return {any}
         */
        Vector.prototype.get = function (index) {
          if (this.length < index) return undefined;
          return this.array[index];
        };

        /**
         * Method used to apply the growing policy.
         *
         * @param  {number} [override] - Override capacity.
         * @return {number}
         */
        Vector.prototype.applyPolicy = function (override) {
          var newCapacity = this.policy(override || this.capacity);
          if (typeof newCapacity !== 'number' || newCapacity < 0) throw new Error('mnemonist/vector.applyPolicy: policy returned an invalid value (expecting a positive integer).');
          if (newCapacity <= this.capacity) throw new Error('mnemonist/vector.applyPolicy: policy returned a less or equal capacity to allocate.');

          // TODO: we should probably check that the returned number is an integer
          return newCapacity;
        };

        /**
         * Method used to reallocate the underlying array.
         *
         * @param  {number}       capacity - Target capacity.
         * @return {Vector}
         */
        Vector.prototype.reallocate = function (capacity) {
          if (capacity === this.capacity) return this;
          var oldArray = this.array;
          if (capacity < this.length) this.length = capacity;
          if (capacity > this.capacity) {
            if (this.factory === null) this.array = new this.ArrayClass(capacity);else this.array = this.factory(capacity);
            if (typed.isTypedArray(this.array)) {
              this.array.set(oldArray, 0);
            } else {
              for (var i = 0, l = this.length; i < l; i++) this.array[i] = oldArray[i];
            }
          } else {
            this.array = oldArray.slice(0, capacity);
          }
          this.capacity = capacity;
          return this;
        };

        /**
         * Method used to grow the array.
         *
         * @param  {number}       [capacity] - Optional capacity to match.
         * @return {Vector}
         */
        Vector.prototype.grow = function (capacity) {
          var newCapacity;
          if (typeof capacity === 'number') {
            if (this.capacity >= capacity) return this;

            // We need to match the given capacity
            newCapacity = this.capacity;
            while (newCapacity < capacity) newCapacity = this.applyPolicy(newCapacity);
            this.reallocate(newCapacity);
            return this;
          }

          // We need to run the policy once
          newCapacity = this.applyPolicy();
          this.reallocate(newCapacity);
          return this;
        };

        /**
         * Method used to resize the array. Won't deallocate.
         *
         * @param  {number}       length - Target length.
         * @return {Vector}
         */
        Vector.prototype.resize = function (length) {
          if (length === this.length) return this;
          if (length < this.length) {
            this.length = length;
            return this;
          }
          this.length = length;
          this.reallocate(length);
          return this;
        };

        /**
         * Method used to push a value into the array.
         *
         * @param  {any}    value - Value to push.
         * @return {number}       - Length of the array.
         */
        Vector.prototype.push = function (value) {
          if (this.capacity === this.length) this.grow();
          this.array[this.length++] = value;
          return this.length;
        };

        /**
         * Method used to pop the last value of the array.
         *
         * @return {number} - The popped value.
         */
        Vector.prototype.pop = function () {
          if (this.length === 0) return;
          return this.array[--this.length];
        };

        /**
         * Method used to create an iterator over a vector's values.
         *
         * @return {Iterator}
         */
        Vector.prototype.values = function () {
          var items = this.array,
            l = this.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[i];
            i++;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over a vector's entries.
         *
         * @return {Iterator}
         */
        Vector.prototype.entries = function () {
          var items = this.array,
            l = this.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[i];
            return {
              value: [i++, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') Vector.prototype[Symbol.iterator] = Vector.prototype.values;

        /**
         * Convenience known methods.
         */
        Vector.prototype.inspect = function () {
          var proxy = this.array.slice(0, this.length);
          proxy.type = this.array.constructor.name;
          proxy.items = this.length;
          proxy.capacity = this.capacity;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: Vector,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') Vector.prototype[Symbol.for('nodejs.util.inspect.custom')] = Vector.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a vector.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} ArrayClass - Byte array class.
         * @param  {number}   capacity   - Desired capacity.
         * @return {Vector}
         */
        Vector.from = function (iterable, ArrayClass, capacity) {
          if (arguments.length < 3) {
            // Attempting to guess the needed capacity
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/vector.from: could not guess iterable length. Please provide desired capacity as last argument.');
          }
          var vector = new Vector(ArrayClass, capacity);
          forEach(iterable, function (value) {
            vector.push(value);
          });
          return vector;
        };

        /**
         * Exporting.
         */
        function subClass(ArrayClass) {
          var SubClass = function SubClass(initialCapacityOrOptions) {
            Vector.call(this, ArrayClass, initialCapacityOrOptions);
          };
          for (var k in Vector.prototype) {
            if (Vector.prototype.hasOwnProperty(k)) SubClass.prototype[k] = Vector.prototype[k];
          }
          SubClass.from = function (iterable, capacity) {
            return Vector.from(iterable, ArrayClass, capacity);
          };
          if (typeof Symbol !== 'undefined') SubClass.prototype[Symbol.iterator] = SubClass.prototype.values;
          return SubClass;
        }
        Vector.Int8Vector = subClass(Int8Array);
        Vector.Uint8Vector = subClass(Uint8Array);
        Vector.Uint8ClampedVector = subClass(Uint8ClampedArray);
        Vector.Int16Vector = subClass(Int16Array);
        Vector.Uint16Vector = subClass(Uint16Array);
        Vector.Int32Vector = subClass(Int32Array);
        Vector.Uint32Vector = subClass(Uint32Array);
        Vector.Float32Vector = subClass(Float32Array);
        Vector.Float64Vector = subClass(Float64Array);
        Vector.PointerVector = subClass(pointerArrayFactory);
        module.exports = Vector;

        // #endregion ORIGINAL CODE

        _cjsExports$3 = module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/iterables.js': __cjsMetaURL$6,
          './utils/typed-arrays.js': __cjsMetaURL$5
        };
      });

      // I am the facade module who provides access to the CommonJS module './vector.js'~
      if (!__cjsMetaURL$a) {
        loader.throwInvalidWrapper('./vector.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/vector.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$a);
      var __cjsMetaURL$b = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bi-map.js';
      loader.define(__cjsMetaURL$b, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist BiMap
         * ================
         *
         * JavaScript implementation of a BiMap.
         */
        var forEach = require('obliterator/foreach');

        /**
         * Inverse Map.
         *
         * @constructor
         */
        function InverseMap(original) {
          this.size = 0;
          this.items = new Map();
          this.inverse = original;
        }

        /**
         * BiMap.
         *
         * @constructor
         */
        function BiMap() {
          this.size = 0;
          this.items = new Map();
          this.inverse = new InverseMap(this);
        }

        /**
         * Method used to clear the map.
         *
         * @return {undefined}
         */
        function clear() {
          this.size = 0;
          this.items.clear();
          this.inverse.items.clear();
        }
        BiMap.prototype.clear = clear;
        InverseMap.prototype.clear = clear;

        /**
         * Method used to set a relation.
         *
         * @param  {any} key - Key.
         * @param  {any} value - Value.
         * @return {BiMap|InverseMap}
         */
        function set(key, value) {
          // First we need to attempt to see if the relation is not flawed
          if (this.items.has(key)) {
            var currentValue = this.items.get(key);

            // The relation already exists, we do nothing
            if (currentValue === value) return this;else this.inverse.items.delete(currentValue);
          }
          if (this.inverse.items.has(value)) {
            var currentKey = this.inverse.items.get(value);
            if (currentKey === key) return this;else this.items.delete(currentKey);
          }

          // Here we actually add the relation
          this.items.set(key, value);
          this.inverse.items.set(value, key);

          // Size
          this.size = this.items.size;
          this.inverse.size = this.inverse.items.size;
          return this;
        }
        BiMap.prototype.set = set;
        InverseMap.prototype.set = set;

        /**
         * Method used to delete a relation.
         *
         * @param  {any} key - Key.
         * @return {boolean}
         */
        function del(key) {
          if (this.items.has(key)) {
            var currentValue = this.items.get(key);
            this.items.delete(key);
            this.inverse.items.delete(currentValue);

            // Size
            this.size = this.items.size;
            this.inverse.size = this.inverse.items.size;
            return true;
          }
          return false;
        }
        BiMap.prototype.delete = del;
        InverseMap.prototype.delete = del;

        /**
         * Mapping some Map prototype function unto our two classes.
         */
        var METHODS = ['has', 'get', 'forEach', 'keys', 'values', 'entries'];
        METHODS.forEach(function (name) {
          BiMap.prototype[name] = InverseMap.prototype[name] = function () {
            return Map.prototype[name].apply(this.items, arguments);
          };
        });

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') {
          BiMap.prototype[Symbol.iterator] = BiMap.prototype.entries;
          InverseMap.prototype[Symbol.iterator] = InverseMap.prototype.entries;
        }

        /**
         * Convenience known methods.
         */
        BiMap.prototype.inspect = function () {
          var dummy = {
            left: this.items,
            right: this.inverse.items
          };

          // Trick so that node displays the name of the constructor
          Object.defineProperty(dummy, 'constructor', {
            value: BiMap,
            enumerable: false
          });
          return dummy;
        };
        if (typeof Symbol !== 'undefined') BiMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = BiMap.prototype.inspect;
        InverseMap.prototype.inspect = function () {
          var dummy = {
            left: this.inverse.items,
            right: this.items
          };

          // Trick so that node displays the name of the constructor
          Object.defineProperty(dummy, 'constructor', {
            value: InverseMap,
            enumerable: false
          });
          return dummy;
        };
        if (typeof Symbol !== 'undefined') InverseMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = InverseMap.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a bimap.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @return {BiMap}
         */
        BiMap.from = function (iterable) {
          var bimap = new BiMap();
          forEach(iterable, function (value, key) {
            bimap.set(key, value);
          });
          return bimap;
        };

        /**
         * Exporting.
         */
        module.exports = BiMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './bi-map.js'~
      if (!__cjsMetaURL$b) {
        loader.throwInvalidWrapper('./bi-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bi-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$b);
      var __cjsMetaURL$c = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/bitwise.js';
      loader.define(__cjsMetaURL$c, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Bitwise Helpers
         * ==========================
         *
         * Miscellaneous helpers helping with bitwise operations.
         */

        /**
         * Takes a 32 bits integer and returns its MSB using SWAR strategy.
         *
         * @param  {number} x - Target number.
         * @return {number}
         */
        function msb32(x) {
          x |= x >> 1;
          x |= x >> 2;
          x |= x >> 4;
          x |= x >> 8;
          x |= x >> 16;
          return x & ~(x >> 1);
        }
        exports.msb32 = msb32;

        /**
         * Takes a byte and returns its MSB using SWAR strategy.
         *
         * @param  {number} x - Target number.
         * @return {number}
         */
        function msb8(x) {
          x |= x >> 1;
          x |= x >> 2;
          x |= x >> 4;
          return x & ~(x >> 1);
        }
        exports.msb8 = msb8;

        /**
         * Takes a number and return bit at position.
         *
         * @param  {number} x   - Target number.
         * @param  {number} pos - Position.
         * @return {number}
         */
        exports.test = function (x, pos) {
          return x >> pos & 1;
        };

        /**
         * Compare two bytes and return their critical bit.
         *
         * @param  {number} a - First byte.
         * @param  {number} b - Second byte.
         * @return {number}
         */
        exports.criticalBit8 = function (a, b) {
          return msb8(a ^ b);
        };
        exports.criticalBit8Mask = function (a, b) {
          return ~msb8(a ^ b) >>> 0 & 0xff;
        };
        exports.testCriticalBit8 = function (x, mask) {
          return 1 + (x | mask) >> 8;
        };
        exports.criticalBit32Mask = function (a, b) {
          return ~msb32(a ^ b) >>> 0 & 0xffffffff;
        };

        /**
         * Takes a 32 bits integer and returns its population count (number of 1 of
         * the binary representation).
         *
         * @param  {number} x - Target number.
         * @return {number}
         */
        exports.popcount = function (x) {
          x -= x >> 1 & 0x55555555;
          x = (x & 0x33333333) + (x >> 2 & 0x33333333);
          x = x + (x >> 4) & 0x0f0f0f0f;
          x += x >> 8;
          x += x >> 16;
          return x & 0x7f;
        };

        /**
         * Slightly faster popcount function based on a precomputed table of 8bits
         * words.
         *
         * @param  {number} x - Target number.
         * @return {number}
         */
        var TABLE8 = new Uint8Array(Math.pow(2, 8));
        for (var i = 0, l = TABLE8.length; i < l; i++) TABLE8[i] = exports.popcount(i);
        exports.table8Popcount = function (x) {
          return TABLE8[x & 0xff] + TABLE8[x >> 8 & 0xff] + TABLE8[x >> 16 & 0xff] + TABLE8[x >> 24 & 0xff];
        };

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.msb32;
        module.exports.msb8;
        module.exports.test;
        module.exports.criticalBit8;
        module.exports.criticalBit8Mask;
        module.exports.testCriticalBit8;
        module.exports.criticalBit32Mask;
        module.exports.popcount;
        module.exports.table8Popcount;
      }, {});
      var __cjsMetaURL$d = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bit-set.js';
      loader.define(__cjsMetaURL$d, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist BitSet
         * =================
         *
         * JavaScript implementation of a fixed-size BitSet based upon a Uint32Array.
         *
         * Notes:
         *   - (i >> 5) is the same as ((i / 32) | 0)
         *   - (i & 0x0000001f) is the same as (i % 32)
         *   - I could use a Float64Array to store more in less blocks but I would lose
         *     the benefits of byte comparison to keep track of size without popcounts.
         */
        var Iterator = require('obliterator/iterator'),
          bitwise = require('./utils/bitwise.js');

        /**
         * BitSet.
         *
         * @constructor
         */
        function BitSet(length) {
          // Properties
          this.length = length;
          this.clear();

          // Methods

          // Statics
        }

        /**
         * Method used to clear the bit set.
         *
         * @return {undefined}
         */
        BitSet.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.array = new Uint32Array(Math.ceil(this.length / 32));
        };

        /**
         * Method used to set the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @param  {number} value - Value to set.
         * @return {BitSet}
         */
        BitSet.prototype.set = function (index, value) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex],
            newBytes;
          if (value === 0 || value === false) newBytes = this.array[byteIndex] &= ~(1 << pos);else newBytes = this.array[byteIndex] |= 1 << pos;

          // The operands of all bitwise operators are converted to *signed* 32-bit integers.
          // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
          // Shifting by 31 changes the sign (i.e. 1 << 31 = -2147483648).
          // Therefore, get unsigned representation by applying '>>> 0'.
          newBytes = newBytes >>> 0;

          // Updating size
          if (newBytes > oldBytes) this.size++;else if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
        * Method used to reset the given bit's value.
        *
        * @param  {number} index - Target bit index.
        * @return {BitSet}
        */
        BitSet.prototype.reset = function (index) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex],
            newBytes;
          newBytes = this.array[byteIndex] &= ~(1 << pos);

          // Updating size
          if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
         * Method used to flip the value of the given bit.
         *
         * @param  {number} index - Target bit index.
         * @return {BitSet}
         */
        BitSet.prototype.flip = function (index) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex];
          var newBytes = this.array[byteIndex] ^= 1 << pos;

          // Get unsigned representation.
          newBytes = newBytes >>> 0;

          // Updating size
          if (newBytes > oldBytes) this.size++;else if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
         * Method used to get the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @return {number}
         */
        BitSet.prototype.get = function (index) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f;
          return this.array[byteIndex] >> pos & 1;
        };

        /**
         * Method used to test the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @return {BitSet}
         */
        BitSet.prototype.test = function (index) {
          return Boolean(this.get(index));
        };

        /**
         * Method used to return the number of 1 from the beginning of the set up to
         * the ith index.
         *
         * @param  {number} i - Ith index (cannot be > length).
         * @return {number}
         */
        BitSet.prototype.rank = function (i) {
          if (this.size === 0) return 0;
          var byteIndex = i >> 5,
            pos = i & 0x0000001f,
            r = 0;

          // Accessing the bytes before the last one
          for (var j = 0; j < byteIndex; j++) r += bitwise.table8Popcount(this.array[j]);

          // Handling masked last byte
          var maskedByte = this.array[byteIndex] & (1 << pos) - 1;
          r += bitwise.table8Popcount(maskedByte);
          return r;
        };

        /**
         * Method used to return the position of the rth 1 in the set or -1 if the
         * set is empty.
         *
         * Note: usually select is implemented using binary search over rank but I
         * tend to think the following linear implementation is faster since here
         * rank is O(n) anyway.
         *
         * @param  {number} r - Rth 1 to select (should be < length).
         * @return {number}
         */
        BitSet.prototype.select = function (r) {
          if (this.size === 0) return -1;

          // TODO: throw?
          if (r >= this.length) return -1;
          var byte,
            b = 32,
            p = 0,
            c = 0;
          for (var i = 0, l = this.array.length; i < l; i++) {
            byte = this.array[i];

            // The byte is empty, let's continue
            if (byte === 0) continue;

            // TODO: This branching might not be useful here
            if (i === l - 1) b = this.length % 32 || 32;

            // TODO: popcount should speed things up here

            for (var j = 0; j < b; j++, p++) {
              c += byte >> j & 1;
              if (c === r) return p;
            }
          }
        };

        /**
         * Method used to iterate over the bit set's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        BitSet.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var length = this.length,
            byte,
            bit,
            b = 32;
          for (var i = 0, l = this.array.length; i < l; i++) {
            byte = this.array[i];
            if (i === l - 1) b = length % 32 || 32;
            for (var j = 0; j < b; j++) {
              bit = byte >> j & 1;
              callback.call(scope, bit, i * 32 + j);
            }
          }
        };

        /**
         * Method used to create an iterator over a set's values.
         *
         * @return {Iterator}
         */
        BitSet.prototype.values = function () {
          var length = this.length,
            inner = false,
            byte,
            bit,
            array = this.array,
            l = array.length,
            i = 0,
            j = -1,
            b = 32;
          return new Iterator(function next() {
            if (!inner) {
              if (i >= l) return {
                done: true
              };
              if (i === l - 1) b = length % 32 || 32;
              byte = array[i++];
              inner = true;
              j = -1;
            }
            j++;
            if (j >= b) {
              inner = false;
              return next();
            }
            bit = byte >> j & 1;
            return {
              value: bit
            };
          });
        };

        /**
         * Method used to create an iterator over a set's entries.
         *
         * @return {Iterator}
         */
        BitSet.prototype.entries = function () {
          var length = this.length,
            inner = false,
            byte,
            bit,
            array = this.array,
            index,
            l = array.length,
            i = 0,
            j = -1,
            b = 32;
          return new Iterator(function next() {
            if (!inner) {
              if (i >= l) return {
                done: true
              };
              if (i === l - 1) b = length % 32 || 32;
              byte = array[i++];
              inner = true;
              j = -1;
            }
            j++;
            index = ~-i * 32 + j;
            if (j >= b) {
              inner = false;
              return next();
            }
            bit = byte >> j & 1;
            return {
              value: [index, bit]
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') BitSet.prototype[Symbol.iterator] = BitSet.prototype.values;

        /**
         * Convenience known methods.
         */
        BitSet.prototype.inspect = function () {
          var proxy = new Uint8Array(this.length);
          this.forEach(function (bit, i) {
            proxy[i] = bit;
          });

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: BitSet,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') BitSet.prototype[Symbol.for('nodejs.util.inspect.custom')] = BitSet.prototype.inspect;
        BitSet.prototype.toJSON = function () {
          return Array.from(this.array);
        };

        /**
         * Exporting.
         */
        module.exports = BitSet;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/bitwise.js': __cjsMetaURL$c
        };
      });

      // I am the facade module who provides access to the CommonJS module './bit-set.js'~
      if (!__cjsMetaURL$d) {
        loader.throwInvalidWrapper('./bit-set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bit-set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$d);
      var __cjsMetaURL$e = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bit-vector.js';
      loader.define(__cjsMetaURL$e, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist BitVector
         * ====================
         *
         * JavaScript implementation of a dynamic BitSet based upon a Uint32Array.
         *
         * Notes:
         *   - (i >> 5) is the same as ((i / 32) | 0)
         *   - (i & 0x0000001f) is the same as (i % 32)
         *   - I could use a Float64Array to store more in less blocks but I would lose
         *     the benefits of byte comparison to keep track of size without popcounts.
         */
        var Iterator = require('obliterator/iterator'),
          bitwise = require('./utils/bitwise.js');

        /**
         * Constants.
         */
        var DEFAULT_GROWING_POLICY = function DEFAULT_GROWING_POLICY(capacity) {
          return Math.max(1, Math.ceil(capacity * 1.5));
        };

        /**
         * Helpers.
         */
        function createByteArray(capacity) {
          return new Uint32Array(Math.ceil(capacity / 32));
        }

        /**
         * BitVector.
         *
         * @constructor
         */
        function BitVector(initialLengthOrOptions) {
          var initialLength = initialLengthOrOptions || 0,
            policy = DEFAULT_GROWING_POLICY;
          if (typeof initialLengthOrOptions === 'object') {
            initialLength = initialLengthOrOptions.initialLength || initialLengthOrOptions.initialCapacity || 0;
            policy = initialLengthOrOptions.policy || policy;
          }
          this.size = 0;
          this.length = initialLength;
          this.capacity = Math.ceil(this.length / 32) * 32;
          this.policy = policy;
          this.array = createByteArray(this.capacity);
        }

        /**
         * Method used to set the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @param  {number|boolean} value - Value to set.
         * @return {BitVector}
         */
        BitVector.prototype.set = function (index, value) {
          // Out of bounds?
          if (this.length < index) throw new Error('BitVector.set: index out of bounds.');
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex],
            newBytes;
          if (value === 0 || value === false) newBytes = this.array[byteIndex] &= ~(1 << pos);else newBytes = this.array[byteIndex] |= 1 << pos;

          // Get unsigned representation.
          newBytes = newBytes >>> 0;

          // Updating size
          if (newBytes > oldBytes) this.size++;else if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
        * Method used to reset the given bit's value.
        *
        * @param  {number} index - Target bit index.
        * @return {BitVector}
        */
        BitVector.prototype.reset = function (index) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex],
            newBytes;
          newBytes = this.array[byteIndex] &= ~(1 << pos);

          // Updating size
          if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
         * Method used to flip the value of the given bit.
         *
         * @param  {number} index - Target bit index.
         * @return {BitVector}
         */
        BitVector.prototype.flip = function (index) {
          var byteIndex = index >> 5,
            pos = index & 0x0000001f,
            oldBytes = this.array[byteIndex];
          var newBytes = this.array[byteIndex] ^= 1 << pos;

          // Get unsigned representation.
          newBytes = newBytes >>> 0;

          // Updating size
          if (newBytes > oldBytes) this.size++;else if (newBytes < oldBytes) this.size--;
          return this;
        };

        /**
         * Method used to apply the growing policy.
         *
         * @param  {number} [override] - Override capacity.
         * @return {number}
         */
        BitVector.prototype.applyPolicy = function (override) {
          var newCapacity = this.policy(override || this.capacity);
          if (typeof newCapacity !== 'number' || newCapacity < 0) throw new Error('mnemonist/bit-vector.applyPolicy: policy returned an invalid value (expecting a positive integer).');
          if (newCapacity <= this.capacity) throw new Error('mnemonist/bit-vector.applyPolicy: policy returned a less or equal capacity to allocate.');

          // TODO: we should probably check that the returned number is an integer

          // Ceil to nearest 32
          return Math.ceil(newCapacity / 32) * 32;
        };

        /**
         * Method used to reallocate the underlying array.
         *
         * @param  {number}       capacity - Target capacity.
         * @return {BitVector}
         */
        BitVector.prototype.reallocate = function (capacity) {
          var virtualCapacity = capacity;
          capacity = Math.ceil(capacity / 32) * 32;
          if (virtualCapacity < this.length) this.length = virtualCapacity;
          if (capacity === this.capacity) return this;
          var oldArray = this.array;
          var storageLength = capacity / 32;
          if (storageLength === this.array.length) return this;
          if (storageLength > this.array.length) {
            this.array = new Uint32Array(storageLength);
            this.array.set(oldArray, 0);
          } else {
            this.array = oldArray.slice(0, storageLength);
          }
          this.capacity = capacity;
          return this;
        };

        /**
         * Method used to grow the array.
         *
         * @param  {number}       [capacity] - Optional capacity to match.
         * @return {BitVector}
         */
        BitVector.prototype.grow = function (capacity) {
          var newCapacity;
          if (typeof capacity === 'number') {
            if (this.capacity >= capacity) return this;

            // We need to match the given capacity
            newCapacity = this.capacity;
            while (newCapacity < capacity) newCapacity = this.applyPolicy(newCapacity);
            this.reallocate(newCapacity);
            return this;
          }

          // We need to run the policy once
          newCapacity = this.applyPolicy();
          this.reallocate(newCapacity);
          return this;
        };

        /**
         * Method used to resize the array. Won't deallocate.
         *
         * @param  {number}       length - Target length.
         * @return {BitVector}
         */
        BitVector.prototype.resize = function (length) {
          if (length === this.length) return this;
          if (length < this.length) {
            this.length = length;
            return this;
          }
          this.length = length;
          this.reallocate(length);
          return this;
        };

        /**
         * Method used to push a value in the set.
         *
         * @param  {number|boolean} value
         * @return {BitVector}
         */
        BitVector.prototype.push = function (value) {
          if (this.capacity === this.length) this.grow();
          if (value === 0 || value === false) return ++this.length;
          this.size++;
          var index = this.length++,
            byteIndex = index >> 5,
            pos = index & 0x0000001f;
          this.array[byteIndex] |= 1 << pos;
          return this.length;
        };

        /**
         * Method used to pop the last value of the set.
         *
         * @return {number} - The popped value.
         */
        BitVector.prototype.pop = function () {
          if (this.length === 0) return;
          var index = --this.length;
          var byteIndex = index >> 5,
            pos = index & 0x0000001f;
          return this.array[byteIndex] >> pos & 1;
        };

        /**
         * Method used to get the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @return {number}
         */
        BitVector.prototype.get = function (index) {
          if (this.length < index) return undefined;
          var byteIndex = index >> 5,
            pos = index & 0x0000001f;
          return this.array[byteIndex] >> pos & 1;
        };

        /**
         * Method used to test the given bit's value.
         *
         * @param  {number} index - Target bit index.
         * @return {BitVector}
         */
        BitVector.prototype.test = function (index) {
          if (this.length < index) return false;
          return Boolean(this.get(index));
        };

        /**
         * Method used to return the number of 1 from the beginning of the set up to
         * the ith index.
         *
         * @param  {number} i - Ith index (cannot be > length).
         * @return {number}
         */
        BitVector.prototype.rank = function (i) {
          if (this.size === 0) return 0;
          var byteIndex = i >> 5,
            pos = i & 0x0000001f,
            r = 0;

          // Accessing the bytes before the last one
          for (var j = 0; j < byteIndex; j++) r += bitwise.table8Popcount(this.array[j]);

          // Handling masked last byte
          var maskedByte = this.array[byteIndex] & (1 << pos) - 1;
          r += bitwise.table8Popcount(maskedByte);
          return r;
        };

        /**
         * Method used to return the position of the rth 1 in the set or -1 if the
         * set is empty.
         *
         * Note: usually select is implemented using binary search over rank but I
         * tend to think the following linear implementation is faster since here
         * rank is O(n) anyway.
         *
         * @param  {number} r - Rth 1 to select (should be < length).
         * @return {number}
         */
        BitVector.prototype.select = function (r) {
          if (this.size === 0) return -1;

          // TODO: throw?
          if (r >= this.length) return -1;
          var byte,
            b = 32,
            p = 0,
            c = 0;
          for (var i = 0, l = this.array.length; i < l; i++) {
            byte = this.array[i];

            // The byte is empty, let's continue
            if (byte === 0) continue;

            // TODO: This branching might not be useful here
            if (i === l - 1) b = this.length % 32 || 32;

            // TODO: popcount should speed things up here

            for (var j = 0; j < b; j++, p++) {
              c += byte >> j & 1;
              if (c === r) return p;
            }
          }
        };

        /**
         * Method used to iterate over the bit set's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        BitVector.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var length = this.length,
            byte,
            bit,
            b = 32;
          for (var i = 0, l = this.array.length; i < l; i++) {
            byte = this.array[i];
            if (i === l - 1) b = length % 32 || 32;
            for (var j = 0; j < b; j++) {
              bit = byte >> j & 1;
              callback.call(scope, bit, i * 32 + j);
            }
          }
        };

        /**
         * Method used to create an iterator over a set's values.
         *
         * @return {Iterator}
         */
        BitVector.prototype.values = function () {
          var length = this.length,
            inner = false,
            byte,
            bit,
            array = this.array,
            l = array.length,
            i = 0,
            j = -1,
            b = 32;
          return new Iterator(function next() {
            if (!inner) {
              if (i >= l) return {
                done: true
              };
              if (i === l - 1) b = length % 32 || 32;
              byte = array[i++];
              inner = true;
              j = -1;
            }
            j++;
            if (j >= b) {
              inner = false;
              return next();
            }
            bit = byte >> j & 1;
            return {
              value: bit
            };
          });
        };

        /**
         * Method used to create an iterator over a set's entries.
         *
         * @return {Iterator}
         */
        BitVector.prototype.entries = function () {
          var length = this.length,
            inner = false,
            byte,
            bit,
            array = this.array,
            index,
            l = array.length,
            i = 0,
            j = -1,
            b = 32;
          return new Iterator(function next() {
            if (!inner) {
              if (i >= l) return {
                done: true
              };
              if (i === l - 1) b = length % 32 || 32;
              byte = array[i++];
              inner = true;
              j = -1;
            }
            j++;
            index = ~-i * 32 + j;
            if (j >= b) {
              inner = false;
              return next();
            }
            bit = byte >> j & 1;
            return {
              value: [index, bit]
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') BitVector.prototype[Symbol.iterator] = BitVector.prototype.values;

        /**
         * Convenience known methods.
         */
        BitVector.prototype.inspect = function () {
          var proxy = new Uint8Array(this.length);
          this.forEach(function (bit, i) {
            proxy[i] = bit;
          });

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: BitVector,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') BitVector.prototype[Symbol.for('nodejs.util.inspect.custom')] = BitVector.prototype.inspect;
        BitVector.prototype.toJSON = function () {
          return Array.from(this.array.slice(0, (this.length >> 5) + 1));
        };

        /**
         * Exporting.
         */
        module.exports = BitVector;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/bitwise.js': __cjsMetaURL$c
        };
      });

      // I am the facade module who provides access to the CommonJS module './bit-vector.js'~
      if (!__cjsMetaURL$e) {
        loader.throwInvalidWrapper('./bit-vector.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bit-vector.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$e);
      var __cjsMetaURL$f = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/murmurhash3.js';
      loader.define(__cjsMetaURL$f, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-fallthrough: 0 */
        /**
         * Mnemonist MurmurHash 3
         * =======================
         *
         * Straightforward implementation of the third version of MurmurHash.
         *
         * Note: this piece of code belong to haschisch.
         */

        /**
         * Various helpers.
         */
        function mul32(a, b) {
          return (a & 0xffff) * b + (((a >>> 16) * b & 0xffff) << 16) & 0xffffffff;
        }
        function sum32(a, b) {
          return (a & 0xffff) + (b >>> 16) + (((a >>> 16) + b & 0xffff) << 16) & 0xffffffff;
        }
        function rotl32(a, b) {
          return a << b | a >>> 32 - b;
        }

        /**
         * MumurHash3 function.
         *
         * @param  {number}    seed - Seed.
         * @param  {ByteArray} data - Data.
         */
        module.exports = function murmurhash3(seed, data) {
          var c1 = 0xcc9e2d51,
            c2 = 0x1b873593,
            r1 = 15,
            r2 = 13,
            m = 5,
            n = 0x6b64e654;
          var hash = seed,
            k1,
            i,
            l;
          for (i = 0, l = data.length - 4; i <= l; i += 4) {
            k1 = data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24;
            k1 = mul32(k1, c1);
            k1 = rotl32(k1, r1);
            k1 = mul32(k1, c2);
            hash ^= k1;
            hash = rotl32(hash, r2);
            hash = mul32(hash, m);
            hash = sum32(hash, n);
          }
          k1 = 0;
          switch (data.length & 3) {
            case 3:
              k1 ^= data[i + 2] << 16;
            case 2:
              k1 ^= data[i + 1] << 8;
            case 1:
              k1 ^= data[i];
              k1 = mul32(k1, c1);
              k1 = rotl32(k1, r1);
              k1 = mul32(k1, c2);
              hash ^= k1;
          }
          hash ^= data.length;
          hash ^= hash >>> 16;
          hash = mul32(hash, 0x85ebca6b);
          hash ^= hash >>> 13;
          hash = mul32(hash, 0xc2b2ae35);
          hash ^= hash >>> 16;
          return hash >>> 0;
        };

        // #endregion ORIGINAL CODE

        module.exports;
      }, {});
      var __cjsMetaURL$g = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bloom-filter.js';
      loader.define(__cjsMetaURL$g, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Bloom Filter
         * =======================
         *
         * Bloom Filter implementation relying on MurmurHash3.
         */
        var murmurhash3 = require('./utils/murmurhash3.js'),
          forEach = require('obliterator/foreach');

        /**
         * Constants.
         */
        var LN2_SQUARED = Math.LN2 * Math.LN2;

        /**
         * Defaults.
         */
        var DEFAULTS = {
          errorRate: 0.005
        };

        /**
         * Function used to convert a string into a Uint16 byte array.
         *
         * @param  {string}      string - Target string.
         * @return {Uint16Array}
         */
        function stringToByteArray(string) {
          var array = new Uint16Array(string.length),
            i,
            l;
          for (i = 0, l = string.length; i < l; i++) array[i] = string.charCodeAt(i);
          return array;
        }

        /**
         * Function used to hash the given byte array.
         *
         * @param  {number}      length - Length of the filter's byte array.
         * @param  {number}      seed   - Seed to use for the hash function.
         * @param  {Uint16Array}        - Byte array representing the string.
         * @return {number}             - The hash.
         *
         * @note length * 8 should probably already be computed as well as seeds.
         */
        function hashArray(length, seed, array) {
          var hash = murmurhash3(seed * 0xFBA4C795 & 0xFFFFFFFF, array);
          return hash % (length * 8);
        }

        /**
         * Bloom Filter.
         *
         * @constructor
         * @param {number|object} capacityOrOptions - Capacity or options.
         */
        function BloomFilter(capacityOrOptions) {
          var options = {};
          if (!capacityOrOptions) throw new Error('mnemonist/BloomFilter.constructor: a BloomFilter must be created with a capacity.');
          if (typeof capacityOrOptions === 'object') options = capacityOrOptions;else options.capacity = capacityOrOptions;

          // Handling capacity
          if (typeof options.capacity !== 'number' || options.capacity <= 0) throw new Error('mnemonist/BloomFilter.constructor: `capacity` option should be a positive integer.');
          this.capacity = options.capacity;

          // Handling error rate
          this.errorRate = options.errorRate || DEFAULTS.errorRate;
          if (typeof this.errorRate !== 'number' || options.errorRate <= 0) throw new Error('mnemonist/BloomFilter.constructor: `errorRate` option should be a positive float.');
          this.clear();
        }

        /**
         * Method used to clear the filter.
         *
         * @return {undefined}
         */
        BloomFilter.prototype.clear = function () {
          // Optimizing number of bits & number of hash functions
          var bits = -1 / LN2_SQUARED * this.capacity * Math.log(this.errorRate),
            length = bits / 8 | 0;
          this.hashFunctions = length * 8 / this.capacity * Math.LN2 | 0;

          // Creating the data array
          this.data = new Uint8Array(length);
          return;
        };

        /**
         * Method used to add an string to the filter.
         *
         * @param  {string} string - Item to add.
         * @return {BloomFilter}
         *
         * @note Should probably create a hash function working directly on a string.
         */
        BloomFilter.prototype.add = function (string) {
          // Converting the string to a byte array
          var array = stringToByteArray(string);

          // Applying the n hash functions
          for (var i = 0, l = this.hashFunctions; i < l; i++) {
            var index = hashArray(this.data.length, i, array),
              position = 1 << (7 & index);
            this.data[index >> 3] |= position;
          }
          return this;
        };

        /**
         * Method used to test the given string.
         *
         * @param  {string} string - Item to test.
         * @return {boolean}
         */
        BloomFilter.prototype.test = function (string) {
          // Converting the string to a byte array
          var array = stringToByteArray(string);

          // Applying the n hash functions
          for (var i = 0, l = this.hashFunctions; i < l; i++) {
            var index = hashArray(this.data.length, i, array);
            if (!(this.data[index >> 3] & 1 << (7 & index))) return false;
          }
          return true;
        };

        /**
         * Convenience known methods.
         */
        BloomFilter.prototype.toJSON = function () {
          return this.data;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a filter.
         *
         * @param  {Iterable}    iterable - Target iterable.
         * @return {BloomFilter}
         */
        BloomFilter.from = function (iterable, options) {
          if (!options) {
            options = iterable.length || iterable.size;
            if (typeof options !== 'number') throw new Error('BloomFilter.from: could not infer the filter\'s capacity. Try passing it as second argument.');
          }
          var filter = new BloomFilter(options);
          forEach(iterable, function (value) {
            filter.add(value);
          });
          return filter;
        };

        /**
         * Exporting.
         */
        module.exports = BloomFilter;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/murmurhash3.js': __cjsMetaURL$f,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './bloom-filter.js'~
      if (!__cjsMetaURL$g) {
        loader.throwInvalidWrapper('./bloom-filter.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bloom-filter.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$g);
      var __cjsMetaURL$h = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bk-tree.js';
      loader.define(__cjsMetaURL$h, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-constant-condition: 0 */
        /**
         * Mnemonist BK Tree
         * ==================
         *
         * Implementation of a Burkhard-Keller tree, allowing fast lookups of words
         * that lie within a specified distance of the query word.
         *
         * [Reference]:
         * https://en.wikipedia.org/wiki/BK-tree
         *
         * [Article]:
         * W. Burkhard and R. Keller. Some approaches to best-match file searching,
         * CACM, 1973
         */
        var forEach = require('obliterator/foreach');

        /**
         * BK Tree.
         *
         * @constructor
         * @param {function} distance - Distance function to use.
         */
        function BKTree(distance) {
          if (typeof distance !== 'function') throw new Error('mnemonist/BKTree.constructor: given `distance` should be a function.');
          this.distance = distance;
          this.clear();
        }

        /**
         * Method used to add an item to the tree.
         *
         * @param  {any} item - Item to add.
         * @return {BKTree}
         */
        BKTree.prototype.add = function (item) {
          // Initializing the tree with the first given word
          if (!this.root) {
            this.root = {
              item: item,
              children: {}
            };
            this.size++;
            return this;
          }
          var node = this.root,
            d;
          while (true) {
            d = this.distance(item, node.item);
            if (!node.children[d]) break;
            node = node.children[d];
          }
          node.children[d] = {
            item: item,
            children: {}
          };
          this.size++;
          return this;
        };

        /**
         * Method used to query the tree.
         *
         * @param  {number} n     - Maximum distance between query & item.
         * @param  {any}    query - Query
         * @return {BKTree}
         */
        BKTree.prototype.search = function (n, query) {
          if (!this.root) return [];
          var found = [],
            stack = [this.root],
            node,
            child,
            d,
            i,
            l;
          while (stack.length) {
            node = stack.pop();
            d = this.distance(query, node.item);
            if (d <= n) found.push({
              item: node.item,
              distance: d
            });
            for (i = d - n, l = d + n + 1; i < l; i++) {
              child = node.children[i];
              if (child) stack.push(child);
            }
          }
          return found;
        };

        /**
         * Method used to clear the tree.
         *
         * @return {undefined}
         */
        BKTree.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.root = null;
        };

        /**
         * Convenience known methods.
         */
        BKTree.prototype.toJSON = function () {
          return this.root;
        };
        BKTree.prototype.inspect = function () {
          var array = [],
            stack = [this.root],
            node,
            d;
          while (stack.length) {
            node = stack.pop();
            if (!node) continue;
            array.push(node.item);
            for (d in node.children) stack.push(node.children[d]);
          }

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: BKTree,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') BKTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = BKTree.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a tree.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} distance - Distance function.
         * @return {Heap}
         */
        BKTree.from = function (iterable, distance) {
          var tree = new BKTree(distance);
          forEach(iterable, function (value) {
            tree.add(value);
          });
          return tree;
        };

        /**
         * Exporting.
         */
        module.exports = BKTree;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './bk-tree.js'~
      if (!__cjsMetaURL$h) {
        loader.throwInvalidWrapper('./bk-tree.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/bk-tree.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$h);
      var __cjsMetaURL$i = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-deque.js';
      loader.define(__cjsMetaURL$i, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist FixedDeque
         * =====================
         *
         * Fixed capacity double-ended queue implemented as ring deque.
         */
        var iterables = require('./utils/iterables.js'),
          Iterator = require('obliterator/iterator');

        /**
         * FixedDeque.
         *
         * @constructor
         */
        function FixedDeque(ArrayClass, capacity) {
          if (arguments.length < 2) throw new Error('mnemonist/fixed-deque: expecting an Array class and a capacity.');
          if (typeof capacity !== 'number' || capacity <= 0) throw new Error('mnemonist/fixed-deque: `capacity` should be a positive number.');
          this.ArrayClass = ArrayClass;
          this.capacity = capacity;
          this.items = new ArrayClass(this.capacity);
          this.clear();
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        FixedDeque.prototype.clear = function () {
          // Properties
          this.start = 0;
          this.size = 0;
        };

        /**
         * Method used to append a value to the deque.
         *
         * @param  {any}    item - Item to append.
         * @return {number}      - Returns the new size of the deque.
         */
        FixedDeque.prototype.push = function (item) {
          if (this.size === this.capacity) throw new Error('mnemonist/fixed-deque.push: deque capacity (' + this.capacity + ') exceeded!');
          var index = this.start + this.size;
          if (index >= this.capacity) index -= this.capacity;
          this.items[index] = item;
          return ++this.size;
        };

        /**
         * Method used to prepend a value to the deque.
         *
         * @param  {any}    item - Item to prepend.
         * @return {number}      - Returns the new size of the deque.
         */
        FixedDeque.prototype.unshift = function (item) {
          if (this.size === this.capacity) throw new Error('mnemonist/fixed-deque.unshift: deque capacity (' + this.capacity + ') exceeded!');
          var index = this.start - 1;
          if (this.start === 0) index = this.capacity - 1;
          this.items[index] = item;
          this.start = index;
          return ++this.size;
        };

        /**
         * Method used to pop the deque.
         *
         * @return {any} - Returns the popped item.
         */
        FixedDeque.prototype.pop = function () {
          if (this.size === 0) return;
          this.size--;
          var index = this.start + this.size;
          if (index >= this.capacity) index -= this.capacity;
          return this.items[index];
        };

        /**
         * Method used to shift the deque.
         *
         * @return {any} - Returns the shifted item.
         */
        FixedDeque.prototype.shift = function () {
          if (this.size === 0) return;
          var index = this.start;
          this.size--;
          this.start++;
          if (this.start === this.capacity) this.start = 0;
          return this.items[index];
        };

        /**
         * Method used to peek the first value of the deque.
         *
         * @return {any}
         */
        FixedDeque.prototype.peekFirst = function () {
          if (this.size === 0) return;
          return this.items[this.start];
        };

        /**
         * Method used to peek the last value of the deque.
         *
         * @return {any}
         */
        FixedDeque.prototype.peekLast = function () {
          if (this.size === 0) return;
          var index = this.start + this.size - 1;
          if (index >= this.capacity) index -= this.capacity;
          return this.items[index];
        };

        /**
         * Method used to get the desired value of the deque.
         *
         * @param  {number} index
         * @return {any}
         */
        FixedDeque.prototype.get = function (index) {
          if (this.size === 0 || index >= this.capacity) return;
          index = this.start + index;
          if (index >= this.capacity) index -= this.capacity;
          return this.items[index];
        };

        /**
         * Method used to iterate over the deque.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        FixedDeque.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          while (j < l) {
            callback.call(scope, this.items[i], j, this);
            i++;
            j++;
            if (i === c) i = 0;
          }
        };

        /**
         * Method used to convert the deque to a JavaScript array.
         *
         * @return {array}
         */
        // TODO: optional array class as argument?
        FixedDeque.prototype.toArray = function () {
          // Optimization
          var offset = this.start + this.size;
          if (offset < this.capacity) return this.items.slice(this.start, offset);
          var array = new this.ArrayClass(this.size),
            c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          while (j < l) {
            array[j] = this.items[i];
            i++;
            j++;
            if (i === c) i = 0;
          }
          return array;
        };

        /**
         * Method used to create an iterator over the deque's values.
         *
         * @return {Iterator}
         */
        FixedDeque.prototype.values = function () {
          var items = this.items,
            c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          return new Iterator(function () {
            if (j >= l) return {
              done: true
            };
            var value = items[i];
            i++;
            j++;
            if (i === c) i = 0;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over the deque's entries.
         *
         * @return {Iterator}
         */
        FixedDeque.prototype.entries = function () {
          var items = this.items,
            c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          return new Iterator(function () {
            if (j >= l) return {
              done: true
            };
            var value = items[i];
            i++;
            if (i === c) i = 0;
            return {
              value: [j++, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') FixedDeque.prototype[Symbol.iterator] = FixedDeque.prototype.values;

        /**
         * Convenience known methods.
         */
        FixedDeque.prototype.inspect = function () {
          var array = this.toArray();
          array.type = this.ArrayClass.name;
          array.capacity = this.capacity;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: FixedDeque,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') FixedDeque.prototype[Symbol.for('nodejs.util.inspect.custom')] = FixedDeque.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a deque.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} ArrayClass - Array class to use.
         * @param  {number}   capacity   - Desired capacity.
         * @return {FiniteStack}
         */
        FixedDeque.from = function (iterable, ArrayClass, capacity) {
          if (arguments.length < 3) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/fixed-deque.from: could not guess iterable length. Please provide desired capacity as last argument.');
          }
          var deque = new FixedDeque(ArrayClass, capacity);
          if (iterables.isArrayLike(iterable)) {
            var i, l;
            for (i = 0, l = iterable.length; i < l; i++) deque.items[i] = iterable[i];
            deque.size = l;
            return deque;
          }
          iterables.forEach(iterable, function (value) {
            deque.push(value);
          });
          return deque;
        };

        /**
         * Exporting.
         */
        module.exports = FixedDeque;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/iterables.js': __cjsMetaURL$6,
          'obliterator/iterator': __cjsMetaURL$9
        };
      });
      var _cjsExports$4;
      var __cjsMetaURL$j = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/circular-buffer.js';
      loader.define(__cjsMetaURL$j, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist CircularBuffer
         * =========================
         *
         * Circular buffer implementation fit to use as a finite deque.
         */
        var iterables = require('./utils/iterables.js'),
          FixedDeque = require('./fixed-deque');

        /**
         * CircularBuffer.
         *
         * @constructor
         */
        function CircularBuffer(ArrayClass, capacity) {
          if (arguments.length < 2) throw new Error('mnemonist/circular-buffer: expecting an Array class and a capacity.');
          if (typeof capacity !== 'number' || capacity <= 0) throw new Error('mnemonist/circular-buffer: `capacity` should be a positive number.');
          this.ArrayClass = ArrayClass;
          this.capacity = capacity;
          this.items = new ArrayClass(this.capacity);
          this.clear();
        }

        /**
         * Pasting most of the prototype from FixedDeque.
         */
        function paste(name) {
          CircularBuffer.prototype[name] = FixedDeque.prototype[name];
        }
        Object.keys(FixedDeque.prototype).forEach(paste);
        if (typeof Symbol !== 'undefined') Object.getOwnPropertySymbols(FixedDeque.prototype).forEach(paste);

        /**
         * Method used to append a value to the buffer.
         *
         * @param  {any}    item - Item to append.
         * @return {number}      - Returns the new size of the buffer.
         */
        CircularBuffer.prototype.push = function (item) {
          var index = this.start + this.size;
          if (index >= this.capacity) index -= this.capacity;
          this.items[index] = item;

          // Overwriting?
          if (this.size === this.capacity) {
            index++;

            // Wrapping around?
            if (index >= this.capacity) {
              this.start = 0;
            } else {
              this.start = index;
            }
            return this.size;
          }
          return ++this.size;
        };

        /**
         * Method used to prepend a value to the buffer.
         *
         * @param  {any}    item - Item to prepend.
         * @return {number}      - Returns the new size of the buffer.
         */
        CircularBuffer.prototype.unshift = function (item) {
          var index = this.start - 1;
          if (this.start === 0) index = this.capacity - 1;
          this.items[index] = item;

          // Overwriting
          if (this.size === this.capacity) {
            this.start = index;
            return this.size;
          }
          this.start = index;
          return ++this.size;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a circular buffer.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} ArrayClass - Array class to use.
         * @param  {number}   capacity   - Desired capacity.
         * @return {FiniteStack}
         */
        CircularBuffer.from = function (iterable, ArrayClass, capacity) {
          if (arguments.length < 3) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/circular-buffer.from: could not guess iterable length. Please provide desired capacity as last argument.');
          }
          var buffer = new CircularBuffer(ArrayClass, capacity);
          if (iterables.isArrayLike(iterable)) {
            var i, l;
            for (i = 0, l = iterable.length; i < l; i++) buffer.items[i] = iterable[i];
            buffer.size = l;
            return buffer;
          }
          iterables.forEach(iterable, function (value) {
            buffer.push(value);
          });
          return buffer;
        };

        /**
         * Exporting.
         */
        module.exports = CircularBuffer;

        // #endregion ORIGINAL CODE

        _cjsExports$4 = module.exports;
      }, function () {
        return {
          './utils/iterables.js': __cjsMetaURL$6,
          './fixed-deque': __cjsMetaURL$i
        };
      });

      // I am the facade module who provides access to the CommonJS module './circular-buffer.js'~
      if (!__cjsMetaURL$j) {
        loader.throwInvalidWrapper('./circular-buffer.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/circular-buffer.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$j);
      var __cjsMetaURL$k = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/default-map.js';
      loader.define(__cjsMetaURL$k, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist DefaultMap
         * =====================
         *
         * JavaScript implementation of a default map that will return a constructed
         * value any time one tries to access an inexisting key. It's quite similar
         * to python's defaultdict.
         */

        /**
         * DefaultMap.
         *
         * @constructor
         */
        function DefaultMap(factory) {
          if (typeof factory !== 'function') throw new Error('mnemonist/DefaultMap.constructor: expecting a function.');
          this.items = new Map();
          this.factory = factory;
          this.size = 0;
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        DefaultMap.prototype.clear = function () {
          // Properties
          this.items.clear();
          this.size = 0;
        };

        /**
         * Method used to get the value set for given key. If the key does not exist,
         * the value will be created using the provided factory.
         *
         * @param  {any} key - Target key.
         * @return {any}
         */
        DefaultMap.prototype.get = function (key) {
          var value = this.items.get(key);
          if (typeof value === 'undefined') {
            value = this.factory(key, this.size);
            this.items.set(key, value);
            this.size++;
          }
          return value;
        };

        /**
         * Method used to get the value set for given key. If the key does not exist,
         * a value won't be created.
         *
         * @param  {any} key - Target key.
         * @return {any}
         */
        DefaultMap.prototype.peek = function (key) {
          return this.items.get(key);
        };

        /**
         * Method used to set a value for given key.
         *
         * @param  {any} key   - Target key.
         * @param  {any} value - Value.
         * @return {DefaultMap}
         */
        DefaultMap.prototype.set = function (key, value) {
          this.items.set(key, value);
          this.size = this.items.size;
          return this;
        };

        /**
         * Method used to test the existence of a key in the map.
         *
         * @param  {any} key   - Target key.
         * @return {boolean}
         */
        DefaultMap.prototype.has = function (key) {
          return this.items.has(key);
        };

        /**
         * Method used to delete target key.
         *
         * @param  {any} key   - Target key.
         * @return {boolean}
         */
        DefaultMap.prototype.delete = function (key) {
          var deleted = this.items.delete(key);
          this.size = this.items.size;
          return deleted;
        };

        /**
         * Method used to iterate over each of the key/value pairs.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        DefaultMap.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          this.items.forEach(callback, scope);
        };

        /**
         * Iterators.
         */
        DefaultMap.prototype.entries = function () {
          return this.items.entries();
        };
        DefaultMap.prototype.keys = function () {
          return this.items.keys();
        };
        DefaultMap.prototype.values = function () {
          return this.items.values();
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') DefaultMap.prototype[Symbol.iterator] = DefaultMap.prototype.entries;

        /**
         * Convenience known methods.
         */
        DefaultMap.prototype.inspect = function () {
          return this.items;
        };
        if (typeof Symbol !== 'undefined') DefaultMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = DefaultMap.prototype.inspect;

        /**
         * Typical factories.
         */
        DefaultMap.autoIncrement = function () {
          var i = 0;
          return function () {
            return i++;
          };
        };

        /**
         * Exporting.
         */
        module.exports = DefaultMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, {});

      // I am the facade module who provides access to the CommonJS module './default-map.js'~
      if (!__cjsMetaURL$k) {
        loader.throwInvalidWrapper('./default-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/default-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$k);
      var __cjsMetaURL$l = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/default-weak-map.js';
      loader.define(__cjsMetaURL$l, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist DefaultWeakMap
         * =========================
         *
         * JavaScript implementation of a default weak map that will return a constructed
         * value any time one tries to access an non-existing key. It is similar to
         * DefaultMap but uses ES6 WeakMap that only holds weak reference to keys.
         */

        /**
         * DefaultWeakMap.
         *
         * @constructor
         */
        function DefaultWeakMap(factory) {
          if (typeof factory !== 'function') throw new Error('mnemonist/DefaultWeakMap.constructor: expecting a function.');
          this.items = new WeakMap();
          this.factory = factory;
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        DefaultWeakMap.prototype.clear = function () {
          // Properties
          this.items = new WeakMap();
        };

        /**
         * Method used to get the value set for given key. If the key does not exist,
         * the value will be created using the provided factory.
         *
         * @param  {any} key - Target key.
         * @return {any}
         */
        DefaultWeakMap.prototype.get = function (key) {
          var value = this.items.get(key);
          if (typeof value === 'undefined') {
            value = this.factory(key);
            this.items.set(key, value);
          }
          return value;
        };

        /**
         * Method used to get the value set for given key. If the key does not exist,
         * a value won't be created.
         *
         * @param  {any} key - Target key.
         * @return {any}
         */
        DefaultWeakMap.prototype.peek = function (key) {
          return this.items.get(key);
        };

        /**
         * Method used to set a value for given key.
         *
         * @param  {any} key   - Target key.
         * @param  {any} value - Value.
         * @return {DefaultMap}
         */
        DefaultWeakMap.prototype.set = function (key, value) {
          this.items.set(key, value);
          return this;
        };

        /**
         * Method used to test the existence of a key in the map.
         *
         * @param  {any} key   - Target key.
         * @return {boolean}
         */
        DefaultWeakMap.prototype.has = function (key) {
          return this.items.has(key);
        };

        /**
         * Method used to delete target key.
         *
         * @param  {any} key   - Target key.
         * @return {boolean}
         */
        DefaultWeakMap.prototype.delete = function (key) {
          return this.items.delete(key);
        };

        /**
         * Convenience known methods.
         */
        DefaultWeakMap.prototype.inspect = function () {
          return this.items;
        };
        if (typeof Symbol !== 'undefined') DefaultWeakMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = DefaultWeakMap.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = DefaultWeakMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, {});

      // I am the facade module who provides access to the CommonJS module './default-weak-map.js'~
      if (!__cjsMetaURL$l) {
        loader.throwInvalidWrapper('./default-weak-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/default-weak-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$l);

      // I am the facade module who provides access to the CommonJS module './fixed-deque.js'~
      if (!__cjsMetaURL$i) {
        loader.throwInvalidWrapper('./fixed-deque.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-deque.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$i);
      var __cjsMetaURL$m = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/static-disjoint-set.js';
      loader.define(__cjsMetaURL$m, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-constant-condition: 0 */
        /**
         * Mnemonist StaticDisjointSet
         * ============================
         *
         * JavaScript implementation of a static disjoint set (union-find).
         *
         * Note that to remain performant, this implementation needs to know a size
         * beforehand.
         */
        var helpers = require('./utils/typed-arrays.js');

        /**
         * StaticDisjointSet.
         *
         * @constructor
         */
        function StaticDisjointSet(size) {
          // Optimizing the typed array types
          var ParentsTypedArray = helpers.getPointerArray(size),
            RanksTypedArray = helpers.getPointerArray(Math.log2(size));

          // Properties
          this.size = size;
          this.dimension = size;
          this.parents = new ParentsTypedArray(size);
          this.ranks = new RanksTypedArray(size);

          // Initializing parents
          for (var i = 0; i < size; i++) this.parents[i] = i;
        }

        /**
         * Method used to find the root of the given item.
         *
         * @param  {number} x - Target item.
         * @return {number}
         */
        StaticDisjointSet.prototype.find = function (x) {
          var y = x;
          var c, p;
          while (true) {
            c = this.parents[y];
            if (y === c) break;
            y = c;
          }

          // Path compression
          while (true) {
            p = this.parents[x];
            if (p === y) break;
            this.parents[x] = y;
            x = p;
          }
          return y;
        };

        /**
         * Method used to perform the union of two items.
         *
         * @param  {number} x - First item.
         * @param  {number} y - Second item.
         * @return {StaticDisjointSet}
         */
        StaticDisjointSet.prototype.union = function (x, y) {
          var xRoot = this.find(x),
            yRoot = this.find(y);

          // x and y are already in the same set
          if (xRoot === yRoot) return this;
          this.dimension--;

          // x and y are not in the same set, we merge them
          var xRank = this.ranks[x],
            yRank = this.ranks[y];
          if (xRank < yRank) {
            this.parents[xRoot] = yRoot;
          } else if (xRank > yRank) {
            this.parents[yRoot] = xRoot;
          } else {
            this.parents[yRoot] = xRoot;
            this.ranks[xRoot]++;
          }
          return this;
        };

        /**
         * Method returning whether two items are connected.
         *
         * @param  {number} x - First item.
         * @param  {number} y - Second item.
         * @return {boolean}
         */
        StaticDisjointSet.prototype.connected = function (x, y) {
          var xRoot = this.find(x);
          return xRoot === this.find(y);
        };

        /**
         * Method returning the set mapping.
         *
         * @return {TypedArray}
         */
        StaticDisjointSet.prototype.mapping = function () {
          var MappingClass = helpers.getPointerArray(this.dimension);
          var ids = {},
            mapping = new MappingClass(this.size),
            c = 0;
          var r;
          for (var i = 0, l = this.parents.length; i < l; i++) {
            r = this.find(i);
            if (typeof ids[r] === 'undefined') {
              mapping[i] = c;
              ids[r] = c++;
            } else {
              mapping[i] = ids[r];
            }
          }
          return mapping;
        };

        /**
         * Method used to compile the disjoint set into an array of arrays.
         *
         * @return {array}
         */
        StaticDisjointSet.prototype.compile = function () {
          var ids = {},
            result = new Array(this.dimension),
            c = 0;
          var r;
          for (var i = 0, l = this.parents.length; i < l; i++) {
            r = this.find(i);
            if (typeof ids[r] === 'undefined') {
              result[c] = [i];
              ids[r] = c++;
            } else {
              result[ids[r]].push(i);
            }
          }
          return result;
        };

        /**
         * Convenience known methods.
         */
        StaticDisjointSet.prototype.inspect = function () {
          var array = this.compile();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: StaticDisjointSet,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') StaticDisjointSet.prototype[Symbol.for('nodejs.util.inspect.custom')] = StaticDisjointSet.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = StaticDisjointSet;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/typed-arrays.js': __cjsMetaURL$5
        };
      });

      // I am the facade module who provides access to the CommonJS module './static-disjoint-set.js'~
      if (!__cjsMetaURL$m) {
        loader.throwInvalidWrapper('./static-disjoint-set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/static-disjoint-set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$m);
      var __cjsMetaURL$n = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-reverse-heap.js';
      loader.define(__cjsMetaURL$n, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Fixed Reverse Heap
         * =============================
         *
         * Static heap implementation with fixed capacity. It's a "reverse" heap
         * because it stores the elements in reverse so we can replace the worst
         * item in logarithmic time. As such, one cannot pop this heap but can only
         * consume it at the end. This structure is very efficient when trying to
         * find the n smallest/largest items from a larger query (k nearest neigbors
         * for instance).
         */
        var comparators = require('./utils/comparators.js'),
          Heap = require('./heap.js');
        var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR,
          reverseComparator = comparators.reverseComparator;

        /**
         * Helper functions.
         */

        /**
         * Function used to sift up.
         *
         * @param {function} compare - Comparison function.
         * @param {array}    heap    - Array storing the heap's data.
         * @param {number}   size    - Heap's true size.
         * @param {number}   i       - Index.
         */
        function siftUp(compare, heap, size, i) {
          var endIndex = size,
            startIndex = i,
            item = heap[i],
            childIndex = 2 * i + 1,
            rightIndex;
          while (childIndex < endIndex) {
            rightIndex = childIndex + 1;
            if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
              childIndex = rightIndex;
            }
            heap[i] = heap[childIndex];
            i = childIndex;
            childIndex = 2 * i + 1;
          }
          heap[i] = item;
          Heap.siftDown(compare, heap, startIndex, i);
        }

        /**
         * Fully consumes the given heap.
         *
         * @param  {function} ArrayClass - Array class to use.
         * @param  {function} compare    - Comparison function.
         * @param  {array}    heap       - Array storing the heap's data.
         * @param  {number}   size       - True size of the heap.
         * @return {array}
         */
        function consume(ArrayClass, compare, heap, size) {
          var l = size,
            i = l;
          var array = new ArrayClass(size),
            lastItem,
            item;
          while (i > 0) {
            lastItem = heap[--i];
            if (i !== 0) {
              item = heap[0];
              heap[0] = lastItem;
              siftUp(compare, heap, --size, 0);
              lastItem = item;
            }
            array[i] = lastItem;
          }
          return array;
        }

        /**
         * Binary Minimum FixedReverseHeap.
         *
         * @constructor
         * @param {function} ArrayClass - The class of array to use.
         * @param {function} comparator - Comparator function.
         * @param {number}   capacity   - Maximum number of items to keep.
         */
        function FixedReverseHeap(ArrayClass, comparator, capacity) {
          // Comparator can be omitted
          if (arguments.length === 2) {
            capacity = comparator;
            comparator = null;
          }
          this.ArrayClass = ArrayClass;
          this.capacity = capacity;
          this.items = new ArrayClass(capacity);
          this.clear();
          this.comparator = comparator || DEFAULT_COMPARATOR;
          if (typeof capacity !== 'number' && capacity <= 0) throw new Error('mnemonist/FixedReverseHeap.constructor: capacity should be a number > 0.');
          if (typeof this.comparator !== 'function') throw new Error('mnemonist/FixedReverseHeap.constructor: given comparator should be a function.');
          this.comparator = reverseComparator(this.comparator);
        }

        /**
         * Method used to clear the heap.
         *
         * @return {undefined}
         */
        FixedReverseHeap.prototype.clear = function () {
          // Properties
          this.size = 0;
        };

        /**
         * Method used to push an item into the heap.
         *
         * @param  {any}    item - Item to push.
         * @return {number}
         */
        FixedReverseHeap.prototype.push = function (item) {
          // Still some place
          if (this.size < this.capacity) {
            this.items[this.size] = item;
            Heap.siftDown(this.comparator, this.items, 0, this.size);
            this.size++;
          }

          // Heap is full, we need to replace worst item
          else {
            if (this.comparator(item, this.items[0]) > 0) Heap.replace(this.comparator, this.items, item);
          }
          return this.size;
        };

        /**
         * Method used to peek the worst item in the heap.
         *
         * @return {any}
         */
        FixedReverseHeap.prototype.peek = function () {
          return this.items[0];
        };

        /**
         * Method used to consume the heap fully and return its items as a sorted array.
         *
         * @return {array}
         */
        FixedReverseHeap.prototype.consume = function () {
          var items = consume(this.ArrayClass, this.comparator, this.items, this.size);
          this.size = 0;
          return items;
        };

        /**
         * Method used to convert the heap to an array. Note that it basically clone
         * the heap and consumes it completely. This is hardly performant.
         *
         * @return {array}
         */
        FixedReverseHeap.prototype.toArray = function () {
          return consume(this.ArrayClass, this.comparator, this.items.slice(0, this.size), this.size);
        };

        /**
         * Convenience known methods.
         */
        FixedReverseHeap.prototype.inspect = function () {
          var proxy = this.toArray();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: FixedReverseHeap,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') FixedReverseHeap.prototype[Symbol.for('nodejs.util.inspect.custom')] = FixedReverseHeap.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = FixedReverseHeap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/comparators.js': __cjsMetaURL$1,
          './heap.js': __cjsMetaURL$7
        };
      });

      // I am the facade module who provides access to the CommonJS module './fixed-reverse-heap.js'~
      if (!__cjsMetaURL$n) {
        loader.throwInvalidWrapper('./fixed-reverse-heap.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-reverse-heap.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$n);
      var __cjsMetaURL$o = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fuzzy-map.js';
      loader.define(__cjsMetaURL$o, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Fuzzy Map
         * ====================
         *
         * The fuzzy map is a map whose keys are processed by a function before
         * read/write operations. This can often result in multiple keys accessing
         * the same resource (example: a map with lowercased keys).
         */
        var forEach = require('obliterator/foreach');
        var identity = function identity(x) {
          return x;
        };

        /**
         * FuzzyMap.
         *
         * @constructor
         * @param {array|function} descriptor - Hash functions descriptor.
         */
        function FuzzyMap(descriptor) {
          this.items = new Map();
          this.clear();
          if (Array.isArray(descriptor)) {
            this.writeHashFunction = descriptor[0];
            this.readHashFunction = descriptor[1];
          } else {
            this.writeHashFunction = descriptor;
            this.readHashFunction = descriptor;
          }
          if (!this.writeHashFunction) this.writeHashFunction = identity;
          if (!this.readHashFunction) this.readHashFunction = identity;
          if (typeof this.writeHashFunction !== 'function') throw new Error('mnemonist/FuzzyMap.constructor: invalid hash function given.');
          if (typeof this.readHashFunction !== 'function') throw new Error('mnemonist/FuzzyMap.constructor: invalid hash function given.');
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        FuzzyMap.prototype.clear = function () {
          this.items.clear();

          // Properties
          this.size = 0;
        };

        /**
         * Method used to add an item to the FuzzyMap.
         *
         * @param  {any} item - Item to add.
         * @return {FuzzyMap}
         */
        FuzzyMap.prototype.add = function (item) {
          var key = this.writeHashFunction(item);
          this.items.set(key, item);
          this.size = this.items.size;
          return this;
        };

        /**
         * Method used to set an item in the FuzzyMap using the given key.
         *
         * @param  {any} key  - Key to use.
         * @param  {any} item - Item to add.
         * @return {FuzzyMap}
         */
        FuzzyMap.prototype.set = function (key, item) {
          key = this.writeHashFunction(key);
          this.items.set(key, item);
          this.size = this.items.size;
          return this;
        };

        /**
         * Method used to retrieve an item from the FuzzyMap.
         *
         * @param  {any} key - Key to use.
         * @return {any}
         */
        FuzzyMap.prototype.get = function (key) {
          key = this.readHashFunction(key);
          return this.items.get(key);
        };

        /**
         * Method used to test the existence of an item in the map.
         *
         * @param  {any} key - Key to check.
         * @return {boolean}
         */
        FuzzyMap.prototype.has = function (key) {
          key = this.readHashFunction(key);
          return this.items.has(key);
        };

        /**
         * Method used to iterate over each of the FuzzyMap's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        FuzzyMap.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          this.items.forEach(function (value) {
            callback.call(scope, value, value);
          });
        };

        /**
         * Method returning an iterator over the FuzzyMap's values.
         *
         * @return {FuzzyMapIterator}
         */
        FuzzyMap.prototype.values = function () {
          return this.items.values();
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') FuzzyMap.prototype[Symbol.iterator] = FuzzyMap.prototype.values;

        /**
         * Convenience known method.
         */
        FuzzyMap.prototype.inspect = function () {
          var array = Array.from(this.items.values());
          Object.defineProperty(array, 'constructor', {
            value: FuzzyMap,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') FuzzyMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = FuzzyMap.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable}       iterable   - Target iterable.
         * @param  {array|function} descriptor - Hash functions descriptor.
         * @param  {boolean}        useSet     - Whether to use #.set or #.add
         * @return {FuzzyMap}
         */
        FuzzyMap.from = function (iterable, descriptor, useSet) {
          var map = new FuzzyMap(descriptor);
          forEach(iterable, function (value, key) {
            if (useSet) map.set(key, value);else map.add(value);
          });
          return map;
        };

        /**
         * Exporting.
         */
        module.exports = FuzzyMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './fuzzy-map.js'~
      if (!__cjsMetaURL$o) {
        loader.throwInvalidWrapper('./fuzzy-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fuzzy-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$o);
      var __cjsMetaURL$p = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/multi-map.js';
      loader.define(__cjsMetaURL$p, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist MultiMap
         * ===================
         *
         * Implementation of a MultiMap with custom container.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach');

        /**
         * MultiMap.
         *
         * @constructor
         */
        function MultiMap(Container) {
          this.Container = Container || Array;
          this.items = new Map();
          this.clear();
          Object.defineProperty(this.items, 'constructor', {
            value: MultiMap,
            enumerable: false
          });
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        MultiMap.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.dimension = 0;
          this.items.clear();
        };

        /**
         * Method used to set a value.
         *
         * @param  {any}      key   - Key.
         * @param  {any}      value - Value to add.
         * @return {MultiMap}
         */
        MultiMap.prototype.set = function (key, value) {
          var container = this.items.get(key),
            sizeBefore;
          if (!container) {
            this.dimension++;
            container = new this.Container();
            this.items.set(key, container);
          }
          if (this.Container === Set) {
            sizeBefore = container.size;
            container.add(value);
            if (sizeBefore < container.size) this.size++;
          } else {
            container.push(value);
            this.size++;
          }
          return this;
        };

        /**
         * Method used to delete the given key.
         *
         * @param  {any}     key - Key to delete.
         * @return {boolean}
         */
        MultiMap.prototype.delete = function (key) {
          var container = this.items.get(key);
          if (!container) return false;
          this.size -= this.Container === Set ? container.size : container.length;
          this.dimension--;
          this.items.delete(key);
          return true;
        };

        /**
         * Method used to delete the remove an item in the container stored at the
         * given key.
         *
         * @param  {any}     key - Key to delete.
         * @return {boolean}
         */
        MultiMap.prototype.remove = function (key, value) {
          var container = this.items.get(key),
            wasDeleted,
            index;
          if (!container) return false;
          if (this.Container === Set) {
            wasDeleted = container.delete(value);
            if (wasDeleted) this.size--;
            if (container.size === 0) {
              this.items.delete(key);
              this.dimension--;
            }
            return wasDeleted;
          } else {
            index = container.indexOf(value);
            if (index === -1) return false;
            this.size--;
            if (container.length === 1) {
              this.items.delete(key);
              this.dimension--;
              return true;
            }
            container.splice(index, 1);
            return true;
          }
        };

        /**
         * Method used to return whether the given keys exists in the map.
         *
         * @param  {any}     key - Key to check.
         * @return {boolean}
         */
        MultiMap.prototype.has = function (key) {
          return this.items.has(key);
        };

        /**
         * Method used to return the container stored at the given key or `undefined`.
         *
         * @param  {any}     key - Key to get.
         * @return {boolean}
         */
        MultiMap.prototype.get = function (key) {
          return this.items.get(key);
        };

        /**
         * Method used to return the multiplicity of the given key, meaning the number
         * of times it is set, or, more trivially, the size of the attached container.
         *
         * @param  {any}     key - Key to check.
         * @return {number}
         */
        MultiMap.prototype.multiplicity = function (key) {
          var container = this.items.get(key);
          if (typeof container === 'undefined') return 0;
          return this.Container === Set ? container.size : container.length;
        };
        MultiMap.prototype.count = MultiMap.prototype.multiplicity;

        /**
         * Method used to iterate over each of the key/value pairs.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        MultiMap.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;

          // Inner iteration function is created here to avoid creating it in the loop
          var key;
          function inner(value) {
            callback.call(scope, value, key);
          }
          this.items.forEach(function (container, k) {
            key = k;
            container.forEach(inner);
          });
        };

        /**
         * Method used to iterate over each of the associations.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        MultiMap.prototype.forEachAssociation = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          this.items.forEach(callback, scope);
        };

        /**
         * Method returning an iterator over the map's keys.
         *
         * @return {Iterator}
         */
        MultiMap.prototype.keys = function () {
          return this.items.keys();
        };

        /**
         * Method returning an iterator over the map's keys.
         *
         * @return {Iterator}
         */
        MultiMap.prototype.values = function () {
          var iterator = this.items.values(),
            inContainer = false,
            countainer,
            step,
            i,
            l;
          if (this.Container === Set) return new Iterator(function next() {
            if (!inContainer) {
              step = iterator.next();
              if (step.done) return {
                done: true
              };
              inContainer = true;
              countainer = step.value.values();
            }
            step = countainer.next();
            if (step.done) {
              inContainer = false;
              return next();
            }
            return {
              done: false,
              value: step.value
            };
          });
          return new Iterator(function next() {
            if (!inContainer) {
              step = iterator.next();
              if (step.done) return {
                done: true
              };
              inContainer = true;
              countainer = step.value;
              i = 0;
              l = countainer.length;
            }
            if (i >= l) {
              inContainer = false;
              return next();
            }
            return {
              done: false,
              value: countainer[i++]
            };
          });
        };

        /**
         * Method returning an iterator over the map's entries.
         *
         * @return {Iterator}
         */
        MultiMap.prototype.entries = function () {
          var iterator = this.items.entries(),
            inContainer = false,
            countainer,
            step,
            key,
            i,
            l;
          if (this.Container === Set) return new Iterator(function next() {
            if (!inContainer) {
              step = iterator.next();
              if (step.done) return {
                done: true
              };
              inContainer = true;
              key = step.value[0];
              countainer = step.value[1].values();
            }
            step = countainer.next();
            if (step.done) {
              inContainer = false;
              return next();
            }
            return {
              done: false,
              value: [key, step.value]
            };
          });
          return new Iterator(function next() {
            if (!inContainer) {
              step = iterator.next();
              if (step.done) return {
                done: true
              };
              inContainer = true;
              key = step.value[0];
              countainer = step.value[1];
              i = 0;
              l = countainer.length;
            }
            if (i >= l) {
              inContainer = false;
              return next();
            }
            return {
              done: false,
              value: [key, countainer[i++]]
            };
          });
        };

        /**
         * Method returning an iterator over the map's containers.
         *
         * @return {Iterator}
         */
        MultiMap.prototype.containers = function () {
          return this.items.values();
        };

        /**
         * Method returning an iterator over the map's associations.
         *
         * @return {Iterator}
         */
        MultiMap.prototype.associations = function () {
          return this.items.entries();
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') MultiMap.prototype[Symbol.iterator] = MultiMap.prototype.entries;

        /**
         * Convenience known methods.
         */
        MultiMap.prototype.inspect = function () {
          return this.items;
        };
        if (typeof Symbol !== 'undefined') MultiMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = MultiMap.prototype.inspect;
        MultiMap.prototype.toJSON = function () {
          return this.items;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable  - Target iterable.
         * @param  {Class}    Container - Container.
         * @return {MultiMap}
         */
        MultiMap.from = function (iterable, Container) {
          var map = new MultiMap(Container);
          forEach(iterable, function (value, key) {
            map.set(key, value);
          });
          return map;
        };

        /**
         * Exporting.
         */
        module.exports = MultiMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });
      var __cjsMetaURL$q = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fuzzy-multi-map.js';
      loader.define(__cjsMetaURL$q, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist FuzzyMultiMap
         * ========================
         *
         * Same as the fuzzy map but relying on a MultiMap rather than a Map.
         */
        var MultiMap = require('./multi-map.js'),
          forEach = require('obliterator/foreach');
        var identity = function identity(x) {
          return x;
        };

        /**
         * FuzzyMultiMap.
         *
         * @constructor
         * @param {array|function} descriptor - Hash functions descriptor.
         * @param {function}       Container  - Container to use.
         */
        function FuzzyMultiMap(descriptor, Container) {
          this.items = new MultiMap(Container);
          this.clear();
          if (Array.isArray(descriptor)) {
            this.writeHashFunction = descriptor[0];
            this.readHashFunction = descriptor[1];
          } else {
            this.writeHashFunction = descriptor;
            this.readHashFunction = descriptor;
          }
          if (!this.writeHashFunction) this.writeHashFunction = identity;
          if (!this.readHashFunction) this.readHashFunction = identity;
          if (typeof this.writeHashFunction !== 'function') throw new Error('mnemonist/FuzzyMultiMap.constructor: invalid hash function given.');
          if (typeof this.readHashFunction !== 'function') throw new Error('mnemonist/FuzzyMultiMap.constructor: invalid hash function given.');
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        FuzzyMultiMap.prototype.clear = function () {
          this.items.clear();

          // Properties
          this.size = 0;
          this.dimension = 0;
        };

        /**
         * Method used to add an item to the index.
         *
         * @param  {any} item - Item to add.
         * @return {FuzzyMultiMap}
         */
        FuzzyMultiMap.prototype.add = function (item) {
          var key = this.writeHashFunction(item);
          this.items.set(key, item);
          this.size = this.items.size;
          this.dimension = this.items.dimension;
          return this;
        };

        /**
         * Method used to set an item in the index using the given key.
         *
         * @param  {any} key  - Key to use.
         * @param  {any} item - Item to add.
         * @return {FuzzyMultiMap}
         */
        FuzzyMultiMap.prototype.set = function (key, item) {
          key = this.writeHashFunction(key);
          this.items.set(key, item);
          this.size = this.items.size;
          this.dimension = this.items.dimension;
          return this;
        };

        /**
         * Method used to retrieve an item from the index.
         *
         * @param  {any} key - Key to use.
         * @return {any}
         */
        FuzzyMultiMap.prototype.get = function (key) {
          key = this.readHashFunction(key);
          return this.items.get(key);
        };

        /**
         * Method used to test the existence of an item in the map.
         *
         * @param  {any} key - Key to check.
         * @return {boolean}
         */
        FuzzyMultiMap.prototype.has = function (key) {
          key = this.readHashFunction(key);
          return this.items.has(key);
        };

        /**
         * Method used to iterate over each of the index's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        FuzzyMultiMap.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          this.items.forEach(function (value) {
            callback.call(scope, value, value);
          });
        };

        /**
         * Method returning an iterator over the index's values.
         *
         * @return {FuzzyMultiMapIterator}
         */
        FuzzyMultiMap.prototype.values = function () {
          return this.items.values();
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') FuzzyMultiMap.prototype[Symbol.iterator] = FuzzyMultiMap.prototype.values;

        /**
         * Convenience known method.
         */
        FuzzyMultiMap.prototype.inspect = function () {
          var array = Array.from(this);
          Object.defineProperty(array, 'constructor', {
            value: FuzzyMultiMap,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') FuzzyMultiMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = FuzzyMultiMap.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable}       iterable   - Target iterable.
         * @param  {array|function} descriptor - Hash functions descriptor.
         * @param  {function}       Container  - Container to use.
         * @param  {boolean}        useSet     - Whether to use #.set or #.add
         * @return {FuzzyMultiMap}
         */
        FuzzyMultiMap.from = function (iterable, descriptor, Container, useSet) {
          if (arguments.length === 3) {
            if (typeof Container === 'boolean') {
              useSet = Container;
              Container = Array;
            }
          }
          var map = new FuzzyMultiMap(descriptor, Container);
          forEach(iterable, function (value, key) {
            if (useSet) map.set(key, value);else map.add(value);
          });
          return map;
        };

        /**
         * Exporting.
         */
        module.exports = FuzzyMultiMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './multi-map.js': __cjsMetaURL$p,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './fuzzy-multi-map.js'~
      if (!__cjsMetaURL$q) {
        loader.throwInvalidWrapper('./fuzzy-multi-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fuzzy-multi-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$q);
      var __cjsMetaURL$r = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/hashed-array-tree.js';
      loader.define(__cjsMetaURL$r, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist HashedArrayTree
         * ==========================
         *
         * Abstract implementation of a hashed array tree representing arrays growing
         * dynamically.
         */

        /**
         * Defaults.
         */
        var DEFAULT_BLOCK_SIZE = 1024;

        /**
         * Helpers.
         */
        function powerOfTwo(x) {
          return (x & x - 1) === 0;
        }

        /**
         * HashedArrayTree.
         *
         * @constructor
         * @param {function}      ArrayClass           - An array constructor.
         * @param {number|object} initialCapacityOrOptions - Self-explanatory.
         */
        function HashedArrayTree(ArrayClass, initialCapacityOrOptions) {
          if (arguments.length < 1) throw new Error('mnemonist/hashed-array-tree: expecting at least a byte array constructor.');
          var initialCapacity = initialCapacityOrOptions || 0,
            blockSize = DEFAULT_BLOCK_SIZE,
            initialLength = 0;
          if (typeof initialCapacityOrOptions === 'object') {
            initialCapacity = initialCapacityOrOptions.initialCapacity || 0;
            initialLength = initialCapacityOrOptions.initialLength || 0;
            blockSize = initialCapacityOrOptions.blockSize || DEFAULT_BLOCK_SIZE;
          }
          if (!blockSize || !powerOfTwo(blockSize)) throw new Error('mnemonist/hashed-array-tree: block size should be a power of two.');
          var capacity = Math.max(initialLength, initialCapacity),
            initialBlocks = Math.ceil(capacity / blockSize);
          this.ArrayClass = ArrayClass;
          this.length = initialLength;
          this.capacity = initialBlocks * blockSize;
          this.blockSize = blockSize;
          this.offsetMask = blockSize - 1;
          this.blockMask = Math.log2(blockSize);

          // Allocating initial blocks
          this.blocks = new Array(initialBlocks);
          for (var i = 0; i < initialBlocks; i++) this.blocks[i] = new this.ArrayClass(this.blockSize);
        }

        /**
         * Method used to set a value.
         *
         * @param  {number} index - Index to edit.
         * @param  {any}    value - Value.
         * @return {HashedArrayTree}
         */
        HashedArrayTree.prototype.set = function (index, value) {
          // Out of bounds?
          if (this.length < index) throw new Error('HashedArrayTree(' + this.ArrayClass.name + ').set: index out of bounds.');
          var block = index >> this.blockMask,
            i = index & this.offsetMask;
          this.blocks[block][i] = value;
          return this;
        };

        /**
         * Method used to get a value.
         *
         * @param  {number} index - Index to retrieve.
         * @return {any}
         */
        HashedArrayTree.prototype.get = function (index) {
          if (this.length < index) return;
          var block = index >> this.blockMask,
            i = index & this.offsetMask;
          return this.blocks[block][i];
        };

        /**
         * Method used to grow the array.
         *
         * @param  {number}          capacity - Optional capacity to accomodate.
         * @return {HashedArrayTree}
         */
        HashedArrayTree.prototype.grow = function (capacity) {
          if (typeof capacity !== 'number') capacity = this.capacity + this.blockSize;
          if (this.capacity >= capacity) return this;
          while (this.capacity < capacity) {
            this.blocks.push(new this.ArrayClass(this.blockSize));
            this.capacity += this.blockSize;
          }
          return this;
        };

        /**
         * Method used to resize the array. Won't deallocate.
         *
         * @param  {number}       length - Target length.
         * @return {HashedArrayTree}
         */
        HashedArrayTree.prototype.resize = function (length) {
          if (length === this.length) return this;
          if (length < this.length) {
            this.length = length;
            return this;
          }
          this.length = length;
          this.grow(length);
          return this;
        };

        /**
         * Method used to push a value into the array.
         *
         * @param  {any}    value - Value to push.
         * @return {number}       - Length of the array.
         */
        HashedArrayTree.prototype.push = function (value) {
          if (this.capacity === this.length) this.grow();
          var index = this.length;
          var block = index >> this.blockMask,
            i = index & this.offsetMask;
          this.blocks[block][i] = value;
          return ++this.length;
        };

        /**
         * Method used to pop the last value of the array.
         *
         * @return {number} - The popped value.
         */
        HashedArrayTree.prototype.pop = function () {
          if (this.length === 0) return;
          var lastBlock = this.blocks[this.blocks.length - 1];
          var i = --this.length & this.offsetMask;
          return lastBlock[i];
        };

        /**
         * Convenience known methods.
         */
        HashedArrayTree.prototype.inspect = function () {
          var proxy = new this.ArrayClass(this.length),
            block;
          for (var i = 0, l = this.length; i < l; i++) {
            block = i >> this.blockMask;
            proxy[i] = this.blocks[block][i & this.offsetMask];
          }
          proxy.type = this.ArrayClass.name;
          proxy.items = this.length;
          proxy.capacity = this.capacity;
          proxy.blockSize = this.blockSize;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: HashedArrayTree,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') HashedArrayTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = HashedArrayTree.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = HashedArrayTree;

        // #endregion ORIGINAL CODE

        module.exports;
      }, {});

      // I am the facade module who provides access to the CommonJS module './hashed-array-tree.js'~
      if (!__cjsMetaURL$r) {
        loader.throwInvalidWrapper('./hashed-array-tree.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/hashed-array-tree.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$r);
      var __cjsMetaURL$s = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-stack.js';
      loader.define(__cjsMetaURL$s, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist FixedStack
         * =====================
         *
         * The fixed stack is a stack whose capacity is defined beforehand and that
         * cannot be exceeded. This class is really useful when combined with
         * byte arrays to save up some memory and avoid memory re-allocation, hence
         * speeding up computations.
         *
         * This has however a downside: you need to know the maximum size you stack
         * can have during your iteration (which is not too difficult to compute when
         * performing, say, a DFS on a balanced binary tree).
         */
        var Iterator = require('obliterator/iterator'),
          iterables = require('./utils/iterables.js');

        /**
         * FixedStack
         *
         * @constructor
         * @param {function} ArrayClass - Array class to use.
         * @param {number}   capacity   - Desired capacity.
         */
        function FixedStack(ArrayClass, capacity) {
          if (arguments.length < 2) throw new Error('mnemonist/fixed-stack: expecting an Array class and a capacity.');
          if (typeof capacity !== 'number' || capacity <= 0) throw new Error('mnemonist/fixed-stack: `capacity` should be a positive number.');
          this.capacity = capacity;
          this.ArrayClass = ArrayClass;
          this.items = new this.ArrayClass(this.capacity);
          this.clear();
        }

        /**
         * Method used to clear the stack.
         *
         * @return {undefined}
         */
        FixedStack.prototype.clear = function () {
          // Properties
          this.size = 0;
        };

        /**
         * Method used to add an item to the stack.
         *
         * @param  {any}    item - Item to add.
         * @return {number}
         */
        FixedStack.prototype.push = function (item) {
          if (this.size === this.capacity) throw new Error('mnemonist/fixed-stack.push: stack capacity (' + this.capacity + ') exceeded!');
          this.items[this.size++] = item;
          return this.size;
        };

        /**
         * Method used to retrieve & remove the last item of the stack.
         *
         * @return {any}
         */
        FixedStack.prototype.pop = function () {
          if (this.size === 0) return;
          return this.items[--this.size];
        };

        /**
         * Method used to get the last item of the stack.
         *
         * @return {any}
         */
        FixedStack.prototype.peek = function () {
          return this.items[this.size - 1];
        };

        /**
         * Method used to iterate over the stack.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        FixedStack.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = 0, l = this.items.length; i < l; i++) callback.call(scope, this.items[l - i - 1], i, this);
        };

        /**
         * Method used to convert the stack to a JavaScript array.
         *
         * @return {array}
         */
        FixedStack.prototype.toArray = function () {
          var array = new this.ArrayClass(this.size),
            l = this.size - 1,
            i = this.size;
          while (i--) array[i] = this.items[l - i];
          return array;
        };

        /**
         * Method used to create an iterator over a stack's values.
         *
         * @return {Iterator}
         */
        FixedStack.prototype.values = function () {
          var items = this.items,
            l = this.size,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[l - i - 1];
            i++;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over a stack's entries.
         *
         * @return {Iterator}
         */
        FixedStack.prototype.entries = function () {
          var items = this.items,
            l = this.size,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[l - i - 1];
            return {
              value: [i++, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') FixedStack.prototype[Symbol.iterator] = FixedStack.prototype.values;

        /**
         * Convenience known methods.
         */
        FixedStack.prototype.toString = function () {
          return this.toArray().join(',');
        };
        FixedStack.prototype.toJSON = function () {
          return this.toArray();
        };
        FixedStack.prototype.inspect = function () {
          var array = this.toArray();
          array.type = this.ArrayClass.name;
          array.capacity = this.capacity;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: FixedStack,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') FixedStack.prototype[Symbol.for('nodejs.util.inspect.custom')] = FixedStack.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a stack.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {function} ArrayClass - Array class to use.
         * @param  {number}   capacity   - Desired capacity.
         * @return {FixedStack}
         */
        FixedStack.from = function (iterable, ArrayClass, capacity) {
          if (arguments.length < 3) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/fixed-stack.from: could not guess iterable length. Please provide desired capacity as last argument.');
          }
          var stack = new FixedStack(ArrayClass, capacity);
          if (iterables.isArrayLike(iterable)) {
            var i, l;
            for (i = 0, l = iterable.length; i < l; i++) stack.items[i] = iterable[i];
            stack.size = l;
            return stack;
          }
          iterables.forEach(iterable, function (value) {
            stack.push(value);
          });
          return stack;
        };

        /**
         * Exporting.
         */
        module.exports = FixedStack;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });
      var __cjsMetaURL$t = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/static-interval-tree.js';
      loader.define(__cjsMetaURL$t, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /*
         * Mnemonist StaticIntervalTree
         * =============================
         *
         * JavaScript implementation of a static interval tree. This tree is static in
         * that you are required to know all its items beforehand and to built it
         * from an iterable.
         *
         * This implementation represents the interval tree as an augmented balanced
         * binary search tree. It works by sorting the intervals by startpoint first
         * then proceeds building the augmented balanced BST bottom-up from the
         * sorted list.
         *
         * Note that this implementation considers every given intervals as closed for
         * simplicity's sake.
         *
         * For more information: https://en.wikipedia.org/wiki/Interval_tree
         */
        var iterables = require('./utils/iterables.js'),
          typed = require('./utils/typed-arrays.js');
        var FixedStack = require('./fixed-stack.js');

        // TODO: pass index to getters
        // TODO: custom comparison
        // TODO: possibility to pass offset buffer

        // TODO: intervals() => Symbol.iterator
        // TODO: dfs()

        /**
         * Helpers.
         */

        /**
         * Recursive function building the BST from the sorted list of interval
         * indices.
         *
         * @param  {array}    intervals     - Array of intervals to index.
         * @param  {function} endGetter     - Getter function for end of intervals.
         * @param  {array}    sortedIndices - Sorted indices of the intervals.
         * @param  {array}    tree          - BST memory.
         * @param  {array}    augmentations - Array of node augmentations.
         * @param  {number}   i             - BST index of current node.
         * @param  {number}   low           - Dichotomy low index.
         * @param  {number}   high          - Dichotomy high index.
         * @return {number}                 - Created node augmentation value.
         */
        function buildBST(intervals, endGetter, sortedIndices, tree, augmentations, i, low, high) {
          var mid = low + (high - low) / 2 | 0,
            midMinusOne = ~-mid,
            midPlusOne = -~mid;
          var current = sortedIndices[mid];
          tree[i] = current + 1;
          var end = endGetter ? endGetter(intervals[current]) : intervals[current][1];
          var left = i * 2 + 1,
            right = i * 2 + 2;
          var leftEnd = -Infinity,
            rightEnd = -Infinity;
          if (low <= midMinusOne) {
            leftEnd = buildBST(intervals, endGetter, sortedIndices, tree, augmentations, left, low, midMinusOne);
          }
          if (midPlusOne <= high) {
            rightEnd = buildBST(intervals, endGetter, sortedIndices, tree, augmentations, right, midPlusOne, high);
          }
          var augmentation = Math.max(end, leftEnd, rightEnd);
          var augmentationPointer = current;
          if (augmentation === leftEnd) augmentationPointer = augmentations[tree[left] - 1];else if (augmentation === rightEnd) augmentationPointer = augmentations[tree[right] - 1];
          augmentations[current] = augmentationPointer;
          return augmentation;
        }

        /**
         * StaticIntervalTree.
         *
         * @constructor
         * @param {array}           intervals - Array of intervals to index.
         * @param {array<function>} getters   - Optional getters.
         */
        function StaticIntervalTree(intervals, getters) {
          // Properties
          this.size = intervals.length;
          this.intervals = intervals;
          var startGetter = null,
            endGetter = null;
          if (Array.isArray(getters)) {
            startGetter = getters[0];
            endGetter = getters[1];
          }

          // Building the indices array
          var length = intervals.length;
          var IndicesArray = typed.getPointerArray(length + 1);
          var indices = new IndicesArray(length);
          var i;
          for (i = 1; i < length; i++) indices[i] = i;

          // Sorting indices array
          // TODO: check if some version of radix sort can outperform this part
          indices.sort(function (a, b) {
            a = intervals[a];
            b = intervals[b];
            if (startGetter) {
              a = startGetter(a);
              b = startGetter(b);
            } else {
              a = a[0];
              b = b[0];
            }
            if (a < b) return -1;
            if (a > b) return 1;

            // TODO: use getters
            // TODO: this ordering has the following invariant: if query interval
            // contains [nodeStart, max], then whole right subtree can be collected
            // a = a[1];
            // b = b[1];

            // if (a < b)
            //   return 1;

            // if (a > b)
            //   return -1;

            return 0;
          });

          // Building the binary tree
          var height = Math.ceil(Math.log2(length + 1)),
            treeSize = Math.pow(2, height) - 1;
          var tree = new IndicesArray(treeSize);
          var augmentations = new IndicesArray(length);
          buildBST(intervals, endGetter, indices, tree, augmentations, 0, 0, length - 1);

          // Dropping indices
          indices = null;

          // Storing necessary information
          this.height = height;
          this.tree = tree;
          this.augmentations = augmentations;
          this.startGetter = startGetter;
          this.endGetter = endGetter;

          // Initializing DFS stack
          this.stack = new FixedStack(IndicesArray, this.height);
        }

        /**
         * Method returning a list of intervals containing the given point.
         *
         * @param  {any}   point - Target point.
         * @return {array}
         */
        StaticIntervalTree.prototype.intervalsContainingPoint = function (point) {
          var matches = [];
          var stack = this.stack;
          stack.clear();
          stack.push(0);
          var l = this.tree.length;
          var bstIndex, intervalIndex, interval, maxInterval, start, end, max, left, right;
          while (stack.size) {
            bstIndex = stack.pop();
            intervalIndex = this.tree[bstIndex] - 1;
            interval = this.intervals[intervalIndex];
            maxInterval = this.intervals[this.augmentations[intervalIndex]];
            max = this.endGetter ? this.endGetter(maxInterval) : maxInterval[1];

            // No possible match, point is farther right than the max end value
            if (point > max) continue;

            // Searching left
            left = bstIndex * 2 + 1;
            if (left < l && this.tree[left] !== 0) stack.push(left);
            start = this.startGetter ? this.startGetter(interval) : interval[0];
            end = this.endGetter ? this.endGetter(interval) : interval[1];

            // Checking current node
            if (point >= start && point <= end) matches.push(interval);

            // If the point is to the left of the start of the current interval,
            // then it cannot be in the right child
            if (point < start) continue;

            // Searching right
            right = bstIndex * 2 + 2;
            if (right < l && this.tree[right] !== 0) stack.push(right);
          }
          return matches;
        };

        /**
         * Method returning a list of intervals overlapping the given interval.
         *
         * @param  {any}   interval - Target interval.
         * @return {array}
         */
        StaticIntervalTree.prototype.intervalsOverlappingInterval = function (interval) {
          var intervalStart = this.startGetter ? this.startGetter(interval) : interval[0],
            intervalEnd = this.endGetter ? this.endGetter(interval) : interval[1];
          var matches = [];
          var stack = this.stack;
          stack.clear();
          stack.push(0);
          var l = this.tree.length;
          var bstIndex, intervalIndex, currentInterval, maxInterval, start, end, max, left, right;
          while (stack.size) {
            bstIndex = stack.pop();
            intervalIndex = this.tree[bstIndex] - 1;
            currentInterval = this.intervals[intervalIndex];
            maxInterval = this.intervals[this.augmentations[intervalIndex]];
            max = this.endGetter ? this.endGetter(maxInterval) : maxInterval[1];

            // No possible match, start is farther right than the max end value
            if (intervalStart > max) continue;

            // Searching left
            left = bstIndex * 2 + 1;
            if (left < l && this.tree[left] !== 0) stack.push(left);
            start = this.startGetter ? this.startGetter(currentInterval) : currentInterval[0];
            end = this.endGetter ? this.endGetter(currentInterval) : currentInterval[1];

            // Checking current node
            if (intervalEnd >= start && intervalStart <= end) matches.push(currentInterval);

            // If the end is to the left of the start of the current interval,
            // then it cannot be in the right child
            if (intervalEnd < start) continue;

            // Searching right
            right = bstIndex * 2 + 2;
            if (right < l && this.tree[right] !== 0) stack.push(right);
          }
          return matches;
        };

        /**
         * Convenience known methods.
         */
        StaticIntervalTree.prototype.inspect = function () {
          var proxy = this.intervals.slice();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: StaticIntervalTree,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') StaticIntervalTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = StaticIntervalTree.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @return {StaticIntervalTree}
         */
        StaticIntervalTree.from = function (iterable, getters) {
          if (iterables.isArrayLike(iterable)) return new StaticIntervalTree(iterable, getters);
          return new StaticIntervalTree(Array.from(iterable), getters);
        };

        /**
         * Exporting.
         */
        module.exports = StaticIntervalTree;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/iterables.js': __cjsMetaURL$6,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './fixed-stack.js': __cjsMetaURL$s
        };
      });

      // I am the facade module who provides access to the CommonJS module './static-interval-tree.js'~
      if (!__cjsMetaURL$t) {
        loader.throwInvalidWrapper('./static-interval-tree.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/static-interval-tree.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$t);
      var __cjsMetaURL$u = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/binary-search.js';
      loader.define(__cjsMetaURL$u, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Binary Search Helpers
         * ================================
         *
         * Typical binary search functions.
         */

        /**
         * Function returning the index of the search value in the array or `-1` if
         * not found.
         *
         * @param  {array} array - Haystack.
         * @param  {any}   value - Needle.
         * @return {number}
         */
        exports.search = function (array, value, lo, hi) {
          var mid = 0;
          lo = typeof lo !== 'undefined' ? lo : 0;
          hi = typeof hi !== 'undefined' ? hi : array.length;
          hi--;
          var current;
          while (lo <= hi) {
            mid = lo + hi >>> 1;
            current = array[mid];
            if (current > value) {
              hi = ~-mid;
            } else if (current < value) {
              lo = -~mid;
            } else {
              return mid;
            }
          }
          return -1;
        };

        /**
         * Same as above, but can use a custom comparator function.
         *
         * @param  {function} comparator - Custom comparator function.
         * @param  {array}    array      - Haystack.
         * @param  {any}      value      - Needle.
         * @return {number}
         */
        exports.searchWithComparator = function (comparator, array, value) {
          var mid = 0,
            lo = 0,
            hi = ~-array.length,
            comparison;
          while (lo <= hi) {
            mid = lo + hi >>> 1;
            comparison = comparator(array[mid], value);
            if (comparison > 0) {
              hi = ~-mid;
            } else if (comparison < 0) {
              lo = -~mid;
            } else {
              return mid;
            }
          }
          return -1;
        };

        /**
         * Function returning the lower bound of the given value in the array.
         *
         * @param  {array}  array - Haystack.
         * @param  {any}    value - Needle.
         * @param  {number} [lo] - Start index.
         * @param  {numner} [hi] - End index.
         * @return {number}
         */
        exports.lowerBound = function (array, value, lo, hi) {
          var mid = 0;
          lo = typeof lo !== 'undefined' ? lo : 0;
          hi = typeof hi !== 'undefined' ? hi : array.length;
          while (lo < hi) {
            mid = lo + hi >>> 1;
            if (value <= array[mid]) {
              hi = mid;
            } else {
              lo = -~mid;
            }
          }
          return lo;
        };

        /**
         * Same as above, but can use a custom comparator function.
         *
         * @param  {function} comparator - Custom comparator function.
         * @param  {array}    array      - Haystack.
         * @param  {any}      value      - Needle.
         * @return {number}
         */
        exports.lowerBoundWithComparator = function (comparator, array, value) {
          var mid = 0,
            lo = 0,
            hi = array.length;
          while (lo < hi) {
            mid = lo + hi >>> 1;
            if (comparator(value, array[mid]) <= 0) {
              hi = mid;
            } else {
              lo = -~mid;
            }
          }
          return lo;
        };

        /**
         * Same as above, but can work on sorted indices.
         *
         * @param  {array}    array - Haystack.
         * @param  {array}    array - Indices.
         * @param  {any}      value - Needle.
         * @return {number}
         */
        exports.lowerBoundIndices = function (array, indices, value, lo, hi) {
          var mid = 0;
          lo = typeof lo !== 'undefined' ? lo : 0;
          hi = typeof hi !== 'undefined' ? hi : array.length;
          while (lo < hi) {
            mid = lo + hi >>> 1;
            if (value <= array[indices[mid]]) {
              hi = mid;
            } else {
              lo = -~mid;
            }
          }
          return lo;
        };

        /**
         * Function returning the upper bound of the given value in the array.
         *
         * @param  {array}  array - Haystack.
         * @param  {any}    value - Needle.
         * @param  {number} [lo] - Start index.
         * @param  {numner} [hi] - End index.
         * @return {number}
         */
        exports.upperBound = function (array, value, lo, hi) {
          var mid = 0;
          lo = typeof lo !== 'undefined' ? lo : 0;
          hi = typeof hi !== 'undefined' ? hi : array.length;
          while (lo < hi) {
            mid = lo + hi >>> 1;
            if (value >= array[mid]) {
              lo = -~mid;
            } else {
              hi = mid;
            }
          }
          return lo;
        };

        /**
         * Same as above, but can use a custom comparator function.
         *
         * @param  {function} comparator - Custom comparator function.
         * @param  {array}    array      - Haystack.
         * @param  {any}      value      - Needle.
         * @return {number}
         */
        exports.upperBoundWithComparator = function (comparator, array, value) {
          var mid = 0,
            lo = 0,
            hi = array.length;
          while (lo < hi) {
            mid = lo + hi >>> 1;
            if (comparator(value, array[mid]) >= 0) {
              lo = -~mid;
            } else {
              hi = mid;
            }
          }
          return lo;
        };

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.search;
        module.exports.searchWithComparator;
        module.exports.lowerBound;
        module.exports.lowerBoundWithComparator;
        module.exports.lowerBoundIndices;
        module.exports.upperBound;
        module.exports.upperBoundWithComparator;
      }, {});
      var __cjsMetaURL$v = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/utils/merge.js';
      loader.define(__cjsMetaURL$v, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-constant-condition: 0 */
        /**
         * Mnemonist Merge Helpers
         * ========================
         *
         * Various merge algorithms used to handle sorted lists. Note that the given
         * functions are optimized and won't accept mixed arguments.
         *
         * Note: maybe this piece of code belong to sortilege, along with binary-search.
         */
        var typed = require('./typed-arrays.js'),
          isArrayLike = require('./iterables.js').isArrayLike,
          binarySearch = require('./binary-search.js'),
          FibonacciHeap = require('../fibonacci-heap.js');

        // TODO: update to use exponential search
        // TODO: when not knowing final length => should use plain arrays rather than
        // same type as input

        /**
         * Merge two sorted array-like structures into one.
         *
         * @param  {array} a - First array.
         * @param  {array} b - Second array.
         * @return {array}
         */
        function mergeArrays(a, b) {
          // One of the arrays is empty
          if (a.length === 0) return b.slice();
          if (b.length === 0) return a.slice();

          // Finding min array
          var tmp;
          if (a[0] > b[0]) {
            tmp = a;
            a = b;
            b = tmp;
          }

          // If array have non overlapping ranges, we can just concatenate them
          var aEnd = a[a.length - 1],
            bStart = b[0];
          if (aEnd <= bStart) {
            if (typed.isTypedArray(a)) return typed.concat(a, b);
            return a.concat(b);
          }

          // Initializing target
          var array = new a.constructor(a.length + b.length);

          // Iterating until we overlap
          var i, l, v;
          for (i = 0, l = a.length; i < l; i++) {
            v = a[i];
            if (v <= bStart) array[i] = v;else break;
          }

          // Handling overlap
          var aPointer = i,
            aLength = a.length,
            bPointer = 0,
            bLength = b.length,
            aHead,
            bHead;
          while (aPointer < aLength && bPointer < bLength) {
            aHead = a[aPointer];
            bHead = b[bPointer];
            if (aHead <= bHead) {
              array[i++] = aHead;
              aPointer++;
            } else {
              array[i++] = bHead;
              bPointer++;
            }
          }

          // Filling
          while (aPointer < aLength) array[i++] = a[aPointer++];
          while (bPointer < bLength) array[i++] = b[bPointer++];
          return array;
        }

        /**
         * Perform the union of two already unique sorted array-like structures into one.
         *
         * @param  {array} a - First array.
         * @param  {array} b - Second array.
         * @return {array}
         */
        function unionUniqueArrays(a, b) {
          // One of the arrays is empty
          if (a.length === 0) return b.slice();
          if (b.length === 0) return a.slice();

          // Finding min array
          var tmp;
          if (a[0] > b[0]) {
            tmp = a;
            a = b;
            b = tmp;
          }

          // If array have non overlapping ranges, we can just concatenate them
          var aEnd = a[a.length - 1],
            bStart = b[0];
          if (aEnd < bStart) {
            if (typed.isTypedArray(a)) return typed.concat(a, b);
            return a.concat(b);
          }

          // Initializing target
          var array = new a.constructor();

          // Iterating until we overlap
          var i, l, v;
          for (i = 0, l = a.length; i < l; i++) {
            v = a[i];
            if (v < bStart) array.push(v);else break;
          }

          // Handling overlap
          var aPointer = i,
            aLength = a.length,
            bPointer = 0,
            bLength = b.length,
            aHead,
            bHead;
          while (aPointer < aLength && bPointer < bLength) {
            aHead = a[aPointer];
            bHead = b[bPointer];
            if (aHead <= bHead) {
              if (array.length === 0 || array[array.length - 1] !== aHead) array.push(aHead);
              aPointer++;
            } else {
              if (array.length === 0 || array[array.length - 1] !== bHead) array.push(bHead);
              bPointer++;
            }
          }

          // Filling
          // TODO: it's possible to optimize a bit here, since the condition is only
          // relevant the first time
          while (aPointer < aLength) {
            aHead = a[aPointer++];
            if (array.length === 0 || array[array.length - 1] !== aHead) array.push(aHead);
          }
          while (bPointer < bLength) {
            bHead = b[bPointer++];
            if (array.length === 0 || array[array.length - 1] !== bHead) array.push(bHead);
          }
          return array;
        }

        /**
         * Perform the intersection of two already unique sorted array-like structures into one.
         *
         * @param  {array} a - First array.
         * @param  {array} b - Second array.
         * @return {array}
         */
        exports.intersectionUniqueArrays = function (a, b) {
          // One of the arrays is empty
          if (a.length === 0 || b.length === 0) return new a.constructor(0);

          // Finding min array
          var tmp;
          if (a[0] > b[0]) {
            tmp = a;
            a = b;
            b = tmp;
          }

          // If array have non overlapping ranges, there is no intersection
          var aEnd = a[a.length - 1],
            bStart = b[0];
          if (aEnd < bStart) return new a.constructor(0);

          // Initializing target
          var array = new a.constructor();

          // Handling overlap
          var aPointer = binarySearch.lowerBound(a, bStart),
            aLength = a.length,
            bPointer = 0,
            bLength = binarySearch.upperBound(b, aEnd),
            aHead,
            bHead;
          while (aPointer < aLength && bPointer < bLength) {
            aHead = a[aPointer];
            bHead = b[bPointer];
            if (aHead < bHead) {
              aPointer = binarySearch.lowerBound(a, bHead, aPointer + 1);
            } else if (aHead > bHead) {
              bPointer = binarySearch.lowerBound(b, aHead, bPointer + 1);
            } else {
              array.push(aHead);
              aPointer++;
              bPointer++;
            }
          }
          return array;
        };

        /**
         * Merge k sorted array-like structures into one.
         *
         * @param  {array<array>} arrays - Arrays to merge.
         * @return {array}
         */
        function kWayMergeArrays(arrays) {
          var length = 0,
            max = -Infinity,
            al,
            i,
            l;
          var filtered = [];
          for (i = 0, l = arrays.length; i < l; i++) {
            al = arrays[i].length;
            if (al === 0) continue;
            filtered.push(arrays[i]);
            length += al;
            if (al > max) max = al;
          }
          if (filtered.length === 0) return new arrays[0].constructor(0);
          if (filtered.length === 1) return filtered[0].slice();
          if (filtered.length === 2) return mergeArrays(filtered[0], filtered[1]);
          arrays = filtered;
          var array = new arrays[0].constructor(length);
          var PointerArray = typed.getPointerArray(max);
          var pointers = new PointerArray(arrays.length);

          // TODO: benchmark vs. a binomial heap
          var heap = new FibonacciHeap(function (a, b) {
            a = arrays[a][pointers[a]];
            b = arrays[b][pointers[b]];
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
          });
          for (i = 0; i < l; i++) heap.push(i);
          i = 0;
          var p, v;
          while (heap.size) {
            p = heap.pop();
            v = arrays[p][pointers[p]++];
            array[i++] = v;
            if (pointers[p] < arrays[p].length) heap.push(p);
          }
          return array;
        }

        /**
         * Perform the union of k sorted unique array-like structures into one.
         *
         * @param  {array<array>} arrays - Arrays to merge.
         * @return {array}
         */
        function kWayUnionUniqueArrays(arrays) {
          var max = -Infinity,
            al,
            i,
            l;
          var filtered = [];
          for (i = 0, l = arrays.length; i < l; i++) {
            al = arrays[i].length;
            if (al === 0) continue;
            filtered.push(arrays[i]);
            if (al > max) max = al;
          }
          if (filtered.length === 0) return new arrays[0].constructor(0);
          if (filtered.length === 1) return filtered[0].slice();
          if (filtered.length === 2) return unionUniqueArrays(filtered[0], filtered[1]);
          arrays = filtered;
          var array = new arrays[0].constructor();
          var PointerArray = typed.getPointerArray(max);
          var pointers = new PointerArray(arrays.length);

          // TODO: benchmark vs. a binomial heap
          var heap = new FibonacciHeap(function (a, b) {
            a = arrays[a][pointers[a]];
            b = arrays[b][pointers[b]];
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
          });
          for (i = 0; i < l; i++) heap.push(i);
          var p, v;
          while (heap.size) {
            p = heap.pop();
            v = arrays[p][pointers[p]++];
            if (array.length === 0 || array[array.length - 1] !== v) array.push(v);
            if (pointers[p] < arrays[p].length) heap.push(p);
          }
          return array;
        }

        /**
         * Perform the intersection of k sorted array-like structures into one.
         *
         * @param  {array<array>} arrays - Arrays to merge.
         * @return {array}
         */
        exports.kWayIntersectionUniqueArrays = function (arrays) {
          var maxStart = -Infinity,
            minEnd = Infinity,
            first,
            last,
            al,
            i,
            l;
          for (i = 0, l = arrays.length; i < l; i++) {
            al = arrays[i].length;

            // If one of the arrays is empty, so is the intersection
            if (al === 0) return [];
            first = arrays[i][0];
            last = arrays[i][al - 1];
            if (first > maxStart) maxStart = first;
            if (last < minEnd) minEnd = last;
          }

          // Full overlap is impossible
          if (maxStart > minEnd) return [];

          // Only one value
          if (maxStart === minEnd) return [maxStart];

          // NOTE: trying to outsmart I(D,I(C,I(A,B))) is pointless unfortunately...
          // NOTE: I tried to be very clever about bounds but it does not seem
          // to improve the performance of the algorithm.
          var a,
            b,
            array = arrays[0],
            aPointer,
            bPointer,
            aLimit,
            bLimit,
            aHead,
            bHead,
            start = maxStart;
          for (i = 1; i < l; i++) {
            a = array;
            b = arrays[i];

            // Change that to `[]` and observe some perf drops on V8...
            array = new Array();
            aPointer = 0;
            bPointer = binarySearch.lowerBound(b, start);
            aLimit = a.length;
            bLimit = b.length;
            while (aPointer < aLimit && bPointer < bLimit) {
              aHead = a[aPointer];
              bHead = b[bPointer];
              if (aHead < bHead) {
                aPointer = binarySearch.lowerBound(a, bHead, aPointer + 1);
              } else if (aHead > bHead) {
                bPointer = binarySearch.lowerBound(b, aHead, bPointer + 1);
              } else {
                array.push(aHead);
                aPointer++;
                bPointer++;
              }
            }
            if (array.length === 0) return array;
            start = array[0];
          }
          return array;
        };

        /**
         * Variadic merging all of the given arrays.
         *
         * @param  {...array}
         * @return {array}
         */
        exports.merge = function () {
          if (arguments.length === 2) {
            if (isArrayLike(arguments[0])) return mergeArrays(arguments[0], arguments[1]);
          } else {
            if (isArrayLike(arguments[0])) return kWayMergeArrays(arguments);
          }
          return null;
        };

        /**
         * Variadic function performing the union of all the given unique arrays.
         *
         * @param  {...array}
         * @return {array}
         */
        exports.unionUnique = function () {
          if (arguments.length === 2) {
            if (isArrayLike(arguments[0])) return unionUniqueArrays(arguments[0], arguments[1]);
          } else {
            if (isArrayLike(arguments[0])) return kWayUnionUniqueArrays(arguments);
          }
          return null;
        };

        /**
         * Variadic function performing the intersection of all the given unique arrays.
         *
         * @param  {...array}
         * @return {array}
         */
        exports.intersectionUnique = function () {
          if (arguments.length === 2) {
            if (isArrayLike(arguments[0])) return exports.intersectionUniqueArrays(arguments[0], arguments[1]);
          } else {
            if (isArrayLike(arguments[0])) return exports.kWayIntersectionUniqueArrays(arguments);
          }
          return null;
        };

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.intersectionUniqueArrays;
        module.exports.kWayIntersectionUniqueArrays;
        module.exports.merge;
        module.exports.unionUnique;
        module.exports.intersectionUnique;
      }, function () {
        return {
          './typed-arrays.js': __cjsMetaURL$5,
          './iterables.js': __cjsMetaURL$6,
          './binary-search.js': __cjsMetaURL$u,
          '../fibonacci-heap.js': __cjsMetaURL$4
        };
      });
      var __cjsMetaURL$w = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/inverted-index.js';
      loader.define(__cjsMetaURL$w, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Inverted Index
         * =========================
         *
         * JavaScript implementation of an inverted index.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach'),
          helpers = require('./utils/merge.js');
        function identity(x) {
          return x;
        }

        /**
         * InvertedIndex.
         *
         * @constructor
         * @param {function} tokenizer - Tokenizer function.
         */
        function InvertedIndex(descriptor) {
          this.clear();
          if (Array.isArray(descriptor)) {
            this.documentTokenizer = descriptor[0];
            this.queryTokenizer = descriptor[1];
          } else {
            this.documentTokenizer = descriptor;
            this.queryTokenizer = descriptor;
          }
          if (!this.documentTokenizer) this.documentTokenizer = identity;
          if (!this.queryTokenizer) this.queryTokenizer = identity;
          if (typeof this.documentTokenizer !== 'function') throw new Error('mnemonist/InvertedIndex.constructor: document tokenizer is not a function.');
          if (typeof this.queryTokenizer !== 'function') throw new Error('mnemonist/InvertedIndex.constructor: query tokenizer is not a function.');
        }

        /**
         * Method used to clear the InvertedIndex.
         *
         * @return {undefined}
         */
        InvertedIndex.prototype.clear = function () {
          // Properties
          this.items = [];
          this.mapping = new Map();
          this.size = 0;
          this.dimension = 0;
        };

        /**
         * Method used to add a document to the index.
         *
         * @param  {any} doc - Item to add.
         * @return {InvertedIndex}
         */
        InvertedIndex.prototype.add = function (doc) {
          // Increasing size
          this.size++;

          // Storing document
          var key = this.items.length;
          this.items.push(doc);

          // Tokenizing the document
          var tokens = this.documentTokenizer(doc);
          if (!Array.isArray(tokens)) throw new Error('mnemonist/InvertedIndex.add: tokenizer function should return an array of tokens.');

          // Indexing
          var done = new Set(),
            token,
            container;
          for (var i = 0, l = tokens.length; i < l; i++) {
            token = tokens[i];
            if (done.has(token)) continue;
            done.add(token);
            container = this.mapping.get(token);
            if (!container) {
              container = [];
              this.mapping.set(token, container);
            }
            container.push(key);
          }
          this.dimension = this.mapping.size;
          return this;
        };

        /**
         * Method used to query the index in a AND fashion.
         *
         * @param  {any} query - Query
         * @return {Set}       - Intersection of documents matching the query.
         */
        InvertedIndex.prototype.get = function (query) {
          // Early termination
          if (!this.size) return [];

          // First we need to tokenize the query
          var tokens = this.queryTokenizer(query);
          if (!Array.isArray(tokens)) throw new Error('mnemonist/InvertedIndex.query: tokenizer function should return an array of tokens.');
          if (!tokens.length) return [];
          var results = this.mapping.get(tokens[0]),
            c,
            i,
            l;
          if (typeof results === 'undefined' || results.length === 0) return [];
          if (tokens.length > 1) {
            for (i = 1, l = tokens.length; i < l; i++) {
              c = this.mapping.get(tokens[i]);
              if (typeof c === 'undefined' || c.length === 0) return [];
              results = helpers.intersectionUniqueArrays(results, c);
            }
          }
          var docs = new Array(results.length);
          for (i = 0, l = docs.length; i < l; i++) docs[i] = this.items[results[i]];
          return docs;
        };

        /**
         * Method used to iterate over each of the documents.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        InvertedIndex.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = 0, l = this.documents.length; i < l; i++) callback.call(scope, this.documents[i], i, this);
        };

        /**
         * Method returning an iterator over the index's documents.
         *
         * @return {Iterator}
         */
        InvertedIndex.prototype.documents = function () {
          var documents = this.items,
            l = documents.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = documents[i++];
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method returning an iterator over the index's tokens.
         *
         * @return {Iterator}
         */
        InvertedIndex.prototype.tokens = function () {
          return this.mapping.keys();
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') InvertedIndex.prototype[Symbol.iterator] = InvertedIndex.prototype.documents;

        /**
         * Convenience known methods.
         */
        InvertedIndex.prototype.inspect = function () {
          var array = this.items.slice();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: InvertedIndex,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') InvertedIndex.prototype[Symbol.for('nodejs.util.inspect.custom')] = InvertedIndex.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a InvertedIndex.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} tokenizer - Tokenizer function.
         * @return {InvertedIndex}
         */
        InvertedIndex.from = function (iterable, descriptor) {
          var index = new InvertedIndex(descriptor);
          forEach(iterable, function (doc) {
            index.add(doc);
          });
          return index;
        };

        /**
         * Exporting.
         */
        module.exports = InvertedIndex;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/merge.js': __cjsMetaURL$v
        };
      });

      // I am the facade module who provides access to the CommonJS module './inverted-index.js'~
      if (!__cjsMetaURL$w) {
        loader.throwInvalidWrapper('./inverted-index.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/inverted-index.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$w);
      var __cjsMetaURL$x = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sort/quick.js';
      loader.define(__cjsMetaURL$x, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Quick Sort
         * =====================
         *
         * Quick sort related functions.
         * Adapted from: https://alienryderflex.com/quicksort/
         */
        var LOS = new Float64Array(64),
          HIS = new Float64Array(64);
        function inplaceQuickSort(array, lo, hi) {
          var p, i, l, r, swap;
          LOS[0] = lo;
          HIS[0] = hi;
          i = 0;
          while (i >= 0) {
            l = LOS[i];
            r = HIS[i] - 1;
            if (l < r) {
              p = array[l];
              while (l < r) {
                while (array[r] >= p && l < r) r--;
                if (l < r) array[l++] = array[r];
                while (array[l] <= p && l < r) l++;
                if (l < r) array[r--] = array[l];
              }
              array[l] = p;
              LOS[i + 1] = l + 1;
              HIS[i + 1] = HIS[i];
              HIS[i++] = l;
              if (HIS[i] - LOS[i] > HIS[i - 1] - LOS[i - 1]) {
                swap = LOS[i];
                LOS[i] = LOS[i - 1];
                LOS[i - 1] = swap;
                swap = HIS[i];
                HIS[i] = HIS[i - 1];
                HIS[i - 1] = swap;
              }
            } else {
              i--;
            }
          }
          return array;
        }
        exports.inplaceQuickSort = inplaceQuickSort;
        function inplaceQuickSortIndices(array, indices, lo, hi) {
          var p, i, l, r, t, swap;
          LOS[0] = lo;
          HIS[0] = hi;
          i = 0;
          while (i >= 0) {
            l = LOS[i];
            r = HIS[i] - 1;
            if (l < r) {
              t = indices[l];
              p = array[t];
              while (l < r) {
                while (array[indices[r]] >= p && l < r) r--;
                if (l < r) indices[l++] = indices[r];
                while (array[indices[l]] <= p && l < r) l++;
                if (l < r) indices[r--] = indices[l];
              }
              indices[l] = t;
              LOS[i + 1] = l + 1;
              HIS[i + 1] = HIS[i];
              HIS[i++] = l;
              if (HIS[i] - LOS[i] > HIS[i - 1] - LOS[i - 1]) {
                swap = LOS[i];
                LOS[i] = LOS[i - 1];
                LOS[i - 1] = swap;
                swap = HIS[i];
                HIS[i] = HIS[i - 1];
                HIS[i - 1] = swap;
              }
            } else {
              i--;
            }
          }
          return indices;
        }
        exports.inplaceQuickSortIndices = inplaceQuickSortIndices;

        // #endregion ORIGINAL CODE

        module.exports;
        module.exports.inplaceQuickSort;
        module.exports.inplaceQuickSortIndices;
      }, {});
      var __cjsMetaURL$y = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/kd-tree.js';
      loader.define(__cjsMetaURL$y, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist KDTree
         * =================
         *
         * Low-level JavaScript implementation of a k-dimensional tree.
         */
        var iterables = require('./utils/iterables.js');
        var typed = require('./utils/typed-arrays.js');
        var createTupleComparator = require('./utils/comparators.js').createTupleComparator;
        var FixedReverseHeap = require('./fixed-reverse-heap.js');
        var inplaceQuickSortIndices = require('./sort/quick.js').inplaceQuickSortIndices;

        /**
         * Helper function used to compute the squared distance between a query point
         * and an indexed points whose values are stored in a tree's axes.
         *
         * Note that squared distance is used instead of euclidean to avoid
         * costly sqrt computations.
         *
         * @param  {number} dimensions - Number of dimensions.
         * @param  {array}  axes       - Axes data.
         * @param  {number} pivot      - Pivot.
         * @param  {array}  point      - Query point.
         * @return {number}
         */
        function squaredDistanceAxes(dimensions, axes, pivot, b) {
          var d;
          var dist = 0,
            step;
          for (d = 0; d < dimensions; d++) {
            step = axes[d][pivot] - b[d];
            dist += step * step;
          }
          return dist;
        }

        /**
         * Helper function used to reshape input data into low-level axes data.
         *
         * @param  {number} dimensions - Number of dimensions.
         * @param  {array}  data       - Data in the shape [label, [x, y, z...]]
         * @return {object}
         */
        function reshapeIntoAxes(dimensions, data) {
          var l = data.length;
          var axes = new Array(dimensions),
            labels = new Array(l),
            axis;
          var PointerArray = typed.getPointerArray(l);
          var ids = new PointerArray(l);
          var d, i, row;
          var f = true;
          for (d = 0; d < dimensions; d++) {
            axis = new Float64Array(l);
            for (i = 0; i < l; i++) {
              row = data[i];
              axis[i] = row[1][d];
              if (f) {
                labels[i] = row[0];
                ids[i] = i;
              }
            }
            f = false;
            axes[d] = axis;
          }
          return {
            axes: axes,
            ids: ids,
            labels: labels
          };
        }

        /**
         * Helper function used to build a kd-tree from axes data.
         *
         * @param  {number} dimensions - Number of dimensions.
         * @param  {array}  axes       - Axes.
         * @param  {array}  ids        - Indices to sort.
         * @param  {array}  labels     - Point labels.
         * @return {object}
         */
        function buildTree(dimensions, axes, ids, labels) {
          var l = labels.length;

          // NOTE: +1 because we need to keep 0 as null pointer
          var PointerArray = typed.getPointerArray(l + 1);

          // Building the tree
          var pivots = new PointerArray(l),
            lefts = new PointerArray(l),
            rights = new PointerArray(l);
          var stack = [[0, 0, ids.length, -1, 0]],
            step,
            parent,
            direction,
            median,
            pivot,
            lo,
            hi;
          var d,
            i = 0;
          while (stack.length !== 0) {
            step = stack.pop();
            d = step[0];
            lo = step[1];
            hi = step[2];
            parent = step[3];
            direction = step[4];
            inplaceQuickSortIndices(axes[d], ids, lo, hi);
            l = hi - lo;
            median = lo + (l >>> 1); // Fancy floor(l / 2)
            pivot = ids[median];
            pivots[i] = pivot;
            if (parent > -1) {
              if (direction === 0) lefts[parent] = i + 1;else rights[parent] = i + 1;
            }
            d = (d + 1) % dimensions;

            // Right
            if (median !== lo && median !== hi - 1) {
              stack.push([d, median + 1, hi, i, 1]);
            }

            // Left
            if (median !== lo) {
              stack.push([d, lo, median, i, 0]);
            }
            i++;
          }
          return {
            axes: axes,
            labels: labels,
            pivots: pivots,
            lefts: lefts,
            rights: rights
          };
        }

        /**
         * KDTree.
         *
         * @constructor
         */
        function KDTree(dimensions, build) {
          this.dimensions = dimensions;
          this.visited = 0;
          this.axes = build.axes;
          this.labels = build.labels;
          this.pivots = build.pivots;
          this.lefts = build.lefts;
          this.rights = build.rights;
          this.size = this.labels.length;
        }

        /**
         * Method returning the query's nearest neighbor.
         *
         * @param  {array}  query - Query point.
         * @return {any}
         */
        KDTree.prototype.nearestNeighbor = function (query) {
          var bestDistance = Infinity,
            best = null;
          var dimensions = this.dimensions,
            axes = this.axes,
            pivots = this.pivots,
            lefts = this.lefts,
            rights = this.rights;
          var visited = 0;
          function recurse(d, node) {
            visited++;
            var left = lefts[node],
              right = rights[node],
              pivot = pivots[node];
            var dist = squaredDistanceAxes(dimensions, axes, pivot, query);
            if (dist < bestDistance) {
              best = pivot;
              bestDistance = dist;
              if (dist === 0) return;
            }
            var dx = axes[d][pivot] - query[d];
            d = (d + 1) % dimensions;

            // Going the correct way?
            if (dx > 0) {
              if (left !== 0) recurse(d, left - 1);
            } else {
              if (right !== 0) recurse(d, right - 1);
            }

            // Going the other way?
            if (dx * dx < bestDistance) {
              if (dx > 0) {
                if (right !== 0) recurse(d, right - 1);
              } else {
                if (left !== 0) recurse(d, left - 1);
              }
            }
          }
          recurse(0, 0);
          this.visited = visited;
          return this.labels[best];
        };
        var KNN_HEAP_COMPARATOR_3 = createTupleComparator(3);
        var KNN_HEAP_COMPARATOR_2 = createTupleComparator(2);

        /**
         * Method returning the query's k nearest neighbors.
         *
         * @param  {number} k     - Number of nearest neighbor to retrieve.
         * @param  {array}  query - Query point.
         * @return {array}
         */

        // TODO: can do better by improving upon static-kdtree here
        KDTree.prototype.kNearestNeighbors = function (k, query) {
          if (k <= 0) throw new Error('mnemonist/kd-tree.kNearestNeighbors: k should be a positive number.');
          k = Math.min(k, this.size);
          if (k === 1) return [this.nearestNeighbor(query)];
          var heap = new FixedReverseHeap(Array, KNN_HEAP_COMPARATOR_3, k);
          var dimensions = this.dimensions,
            axes = this.axes,
            pivots = this.pivots,
            lefts = this.lefts,
            rights = this.rights;
          var visited = 0;
          function recurse(d, node) {
            var left = lefts[node],
              right = rights[node],
              pivot = pivots[node];
            var dist = squaredDistanceAxes(dimensions, axes, pivot, query);
            heap.push([dist, visited++, pivot]);
            var point = query[d],
              split = axes[d][pivot],
              dx = point - split;
            d = (d + 1) % dimensions;

            // Going the correct way?
            if (point < split) {
              if (left !== 0) {
                recurse(d, left - 1);
              }
            } else {
              if (right !== 0) {
                recurse(d, right - 1);
              }
            }

            // Going the other way?
            if (dx * dx < heap.peek()[0] || heap.size < k) {
              if (point < split) {
                if (right !== 0) {
                  recurse(d, right - 1);
                }
              } else {
                if (left !== 0) {
                  recurse(d, left - 1);
                }
              }
            }
          }
          recurse(0, 0);
          this.visited = visited;
          var best = heap.consume();
          for (var i = 0; i < best.length; i++) best[i] = this.labels[best[i][2]];
          return best;
        };

        /**
         * Method returning the query's k nearest neighbors by linear search.
         *
         * @param  {number} k     - Number of nearest neighbor to retrieve.
         * @param  {array}  query - Query point.
         * @return {array}
         */
        KDTree.prototype.linearKNearestNeighbors = function (k, query) {
          if (k <= 0) throw new Error('mnemonist/kd-tree.kNearestNeighbors: k should be a positive number.');
          k = Math.min(k, this.size);
          var heap = new FixedReverseHeap(Array, KNN_HEAP_COMPARATOR_2, k);
          var i, l, dist;
          for (i = 0, l = this.size; i < l; i++) {
            dist = squaredDistanceAxes(this.dimensions, this.axes, this.pivots[i], query);
            heap.push([dist, i]);
          }
          var best = heap.consume();
          for (i = 0; i < best.length; i++) best[i] = this.labels[this.pivots[best[i][1]]];
          return best;
        };

        /**
         * Convenience known methods.
         */
        KDTree.prototype.inspect = function () {
          var dummy = new Map();
          dummy.dimensions = this.dimensions;
          Object.defineProperty(dummy, 'constructor', {
            value: KDTree,
            enumerable: false
          });
          var i, j, point;
          for (i = 0; i < this.size; i++) {
            point = new Array(this.dimensions);
            for (j = 0; j < this.dimensions; j++) point[j] = this.axes[j][i];
            dummy.set(this.labels[i], point);
          }
          return dummy;
        };
        if (typeof Symbol !== 'undefined') KDTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = KDTree.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {number}   dimensions - Space dimensions.
         * @return {KDTree}
         */
        KDTree.from = function (iterable, dimensions) {
          var data = iterables.toArray(iterable);
          var reshaped = reshapeIntoAxes(dimensions, data);
          var result = buildTree(dimensions, reshaped.axes, reshaped.ids, reshaped.labels);
          return new KDTree(dimensions, result);
        };

        /**
         * Static @.from function building a KDTree from given axes.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @param  {number}   dimensions - Space dimensions.
         * @return {KDTree}
         */
        KDTree.fromAxes = function (axes, labels) {
          if (!labels) labels = typed.indices(axes[0].length);
          var dimensions = axes.length;
          var result = buildTree(axes.length, axes, typed.indices(labels.length), labels);
          return new KDTree(dimensions, result);
        };

        /**
         * Exporting.
         */
        module.exports = KDTree;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/iterables.js': __cjsMetaURL$6,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './utils/comparators.js': __cjsMetaURL$1,
          './fixed-reverse-heap.js': __cjsMetaURL$n,
          './sort/quick.js': __cjsMetaURL$x
        };
      });

      // I am the facade module who provides access to the CommonJS module './kd-tree.js'~
      if (!__cjsMetaURL$y) {
        loader.throwInvalidWrapper('./kd-tree.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/kd-tree.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$y);
      var __cjsMetaURL$z = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/linked-list.js';
      loader.define(__cjsMetaURL$z, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Linked List
         * ======================
         *
         * Singly linked list implementation. Uses raw JavaScript objects as nodes
         * as benchmarks proved it was the fastest thing to do.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach');

        /**
         * Linked List.
         *
         * @constructor
         */
        function LinkedList() {
          this.clear();
        }

        /**
         * Method used to clear the list.
         *
         * @return {undefined}
         */
        LinkedList.prototype.clear = function () {
          // Properties
          this.head = null;
          this.tail = null;
          this.size = 0;
        };

        /**
         * Method used to get the first item of the list.
         *
         * @return {any}
         */
        LinkedList.prototype.first = function () {
          return this.head ? this.head.item : undefined;
        };
        LinkedList.prototype.peek = LinkedList.prototype.first;

        /**
         * Method used to get the last item of the list.
         *
         * @return {any}
         */
        LinkedList.prototype.last = function () {
          return this.tail ? this.tail.item : undefined;
        };

        /**
         * Method used to add an item at the end of the list.
         *
         * @param  {any}    item - The item to add.
         * @return {number}
         */
        LinkedList.prototype.push = function (item) {
          var node = {
            item: item,
            next: null
          };
          if (!this.head) {
            this.head = node;
            this.tail = node;
          } else {
            this.tail.next = node;
            this.tail = node;
          }
          this.size++;
          return this.size;
        };

        /**
         * Method used to add an item at the beginning of the list.
         *
         * @param  {any}    item - The item to add.
         * @return {number}
         */
        LinkedList.prototype.unshift = function (item) {
          var node = {
            item: item,
            next: null
          };
          if (!this.head) {
            this.head = node;
            this.tail = node;
          } else {
            if (!this.head.next) this.tail = this.head;
            node.next = this.head;
            this.head = node;
          }
          this.size++;
          return this.size;
        };

        /**
         * Method used to retrieve & remove the first item of the list.
         *
         * @return {any}
         */
        LinkedList.prototype.shift = function () {
          if (!this.size) return undefined;
          var node = this.head;
          this.head = node.next;
          this.size--;
          return node.item;
        };

        /**
         * Method used to iterate over the list.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        LinkedList.prototype.forEach = function (callback, scope) {
          if (!this.size) return;
          scope = arguments.length > 1 ? scope : this;
          var n = this.head,
            i = 0;
          while (n) {
            callback.call(scope, n.item, i, this);
            n = n.next;
            i++;
          }
        };

        /**
         * Method used to convert the list into an array.
         *
         * @return {array}
         */
        LinkedList.prototype.toArray = function () {
          if (!this.size) return [];
          var array = new Array(this.size);
          for (var i = 0, l = this.size, n = this.head; i < l; i++) {
            array[i] = n.item;
            n = n.next;
          }
          return array;
        };

        /**
         * Method used to create an iterator over a list's values.
         *
         * @return {Iterator}
         */
        LinkedList.prototype.values = function () {
          var n = this.head;
          return new Iterator(function () {
            if (!n) return {
              done: true
            };
            var value = n.item;
            n = n.next;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over a list's entries.
         *
         * @return {Iterator}
         */
        LinkedList.prototype.entries = function () {
          var n = this.head,
            i = 0;
          return new Iterator(function () {
            if (!n) return {
              done: true
            };
            var value = n.item;
            n = n.next;
            i++;
            return {
              value: [i - 1, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') LinkedList.prototype[Symbol.iterator] = LinkedList.prototype.values;

        /**
         * Convenience known methods.
         */
        LinkedList.prototype.toString = function () {
          return this.toArray().join(',');
        };
        LinkedList.prototype.toJSON = function () {
          return this.toArray();
        };
        LinkedList.prototype.inspect = function () {
          var array = this.toArray();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: LinkedList,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') LinkedList.prototype[Symbol.for('nodejs.util.inspect.custom')] = LinkedList.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a list.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @return {LinkedList}
         */
        LinkedList.from = function (iterable) {
          var list = new LinkedList();
          forEach(iterable, function (value) {
            list.push(value);
          });
          return list;
        };

        /**
         * Exporting.
         */
        module.exports = LinkedList;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './linked-list.js'~
      if (!__cjsMetaURL$z) {
        loader.throwInvalidWrapper('./linked-list.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/linked-list.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$z);
      var __cjsMetaURL$A = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-cache.js';
      loader.define(__cjsMetaURL$A, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist LRUCache
         * ===================
         *
         * JavaScript implementation of the LRU Cache data structure. To save up
         * memory and allocations this implementation represents its underlying
         * doubly-linked list as static arrays and pointers. Thus, memory is allocated
         * only once at instantiation and JS objects are never created to serve as
         * pointers. This also means this implementation does not trigger too many
         * garbage collections.
         *
         * Note that to save up memory, a LRU Cache can be implemented using a singly
         * linked list by storing predecessors' pointers as hashmap values.
         * However, this means more hashmap lookups and would probably slow the whole
         * thing down. What's more, pointers are not the things taking most space in
         * memory.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach'),
          typed = require('./utils/typed-arrays.js'),
          iterables = require('./utils/iterables.js');

        /**
         * LRUCache.
         *
         * @constructor
         * @param {function} Keys     - Array class for storing keys.
         * @param {function} Values   - Array class for storing values.
         * @param {number}   capacity - Desired capacity.
         */
        function LRUCache(Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          this.capacity = capacity;
          if (typeof this.capacity !== 'number' || this.capacity <= 0) throw new Error('mnemonist/lru-cache: capacity should be positive number.');else if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity) throw new Error('mnemonist/lru-cache: capacity should be a finite positive integer.');
          var PointerArray = typed.getPointerArray(capacity);
          this.forward = new PointerArray(capacity);
          this.backward = new PointerArray(capacity);
          this.K = typeof Keys === 'function' ? new Keys(capacity) : new Array(capacity);
          this.V = typeof Values === 'function' ? new Values(capacity) : new Array(capacity);

          // Properties
          this.size = 0;
          this.head = 0;
          this.tail = 0;
          this.items = {};
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        LRUCache.prototype.clear = function () {
          this.size = 0;
          this.head = 0;
          this.tail = 0;
          this.items = {};
        };

        /**
         * Method used to splay a value on top.
         *
         * @param  {number}   pointer - Pointer of the value to splay on top.
         * @return {LRUCache}
         */
        LRUCache.prototype.splayOnTop = function (pointer) {
          var oldHead = this.head;
          if (this.head === pointer) return this;
          var previous = this.backward[pointer],
            next = this.forward[pointer];
          if (this.tail === pointer) {
            this.tail = previous;
          } else {
            this.backward[next] = previous;
          }
          this.forward[previous] = next;
          this.backward[oldHead] = pointer;
          this.head = pointer;
          this.forward[pointer] = oldHead;
          return this;
        };

        /**
         * Method used to set the value for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {undefined}
         */
        LRUCache.prototype.set = function (key, value) {
          var pointer = this.items[key];

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            this.V[pointer] = value;
            return;
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            pointer = this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            delete this.items[this.K[pointer]];
          }

          // Storing key & value
          this.items[key] = pointer;
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;
        };

        /**
         * Method used to set the value for the given key in the cache
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {{evicted: boolean, key: any, value: any}} An object containing the
         * key and value of an item that was overwritten or evicted in the set
         * operation, as well as a boolean indicating whether it was evicted due to
         * limited capacity. Return value is null if nothing was evicted or overwritten
         * during the set operation.
         */
        LRUCache.prototype.setpop = function (key, value) {
          var oldValue = null;
          var oldKey = null;
          var pointer = this.items[key];

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            oldValue = this.V[pointer];
            this.V[pointer] = value;
            return {
              evicted: false,
              key: key,
              value: oldValue
            };
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            pointer = this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            oldValue = this.V[pointer];
            oldKey = this.K[pointer];
            delete this.items[oldKey];
          }

          // Storing key & value
          this.items[key] = pointer;
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;

          // Return object if eviction took place, otherwise return null
          if (oldKey) {
            return {
              evicted: true,
              key: oldKey,
              value: oldValue
            };
          } else {
            return null;
          }
        };

        /**
         * Method used to check whether the key exists in the cache.
         *
         * @param  {any} key   - Key.
         * @return {boolean}
         */
        LRUCache.prototype.has = function (key) {
          return key in this.items;
        };

        /**
         * Method used to get the value attached to the given key. Will move the
         * related key to the front of the underlying linked list.
         *
         * @param  {any} key   - Key.
         * @return {any}
         */
        LRUCache.prototype.get = function (key) {
          var pointer = this.items[key];
          if (typeof pointer === 'undefined') return;
          this.splayOnTop(pointer);
          return this.V[pointer];
        };

        /**
         * Method used to get the value attached to the given key. Does not modify
         * the ordering of the underlying linked list.
         *
         * @param  {any} key   - Key.
         * @return {any}
         */
        LRUCache.prototype.peek = function (key) {
          var pointer = this.items[key];
          if (typeof pointer === 'undefined') return;
          return this.V[pointer];
        };

        /**
         * Method used to iterate over the cache's entries using a callback.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        LRUCache.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var i = 0,
            l = this.size;
          var pointer = this.head,
            keys = this.K,
            values = this.V,
            forward = this.forward;
          while (i < l) {
            callback.call(scope, values[pointer], keys[pointer], this);
            pointer = forward[pointer];
            i++;
          }
        };

        /**
         * Method used to create an iterator over the cache's keys from most
         * recently used to least recently used.
         *
         * @return {Iterator}
         */
        LRUCache.prototype.keys = function () {
          var i = 0,
            l = this.size;
          var pointer = this.head,
            keys = this.K,
            forward = this.forward;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var key = keys[pointer];
            i++;
            if (i < l) pointer = forward[pointer];
            return {
              done: false,
              value: key
            };
          });
        };

        /**
         * Method used to create an iterator over the cache's values from most
         * recently used to least recently used.
         *
         * @return {Iterator}
         */
        LRUCache.prototype.values = function () {
          var i = 0,
            l = this.size;
          var pointer = this.head,
            values = this.V,
            forward = this.forward;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = values[pointer];
            i++;
            if (i < l) pointer = forward[pointer];
            return {
              done: false,
              value: value
            };
          });
        };

        /**
         * Method used to create an iterator over the cache's entries from most
         * recently used to least recently used.
         *
         * @return {Iterator}
         */
        LRUCache.prototype.entries = function () {
          var i = 0,
            l = this.size;
          var pointer = this.head,
            keys = this.K,
            values = this.V,
            forward = this.forward;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var key = keys[pointer],
              value = values[pointer];
            i++;
            if (i < l) pointer = forward[pointer];
            return {
              done: false,
              value: [key, value]
            };
          });
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') LRUCache.prototype[Symbol.iterator] = LRUCache.prototype.entries;

        /**
         * Convenience known methods.
         */
        LRUCache.prototype.inspect = function () {
          var proxy = new Map();
          var iterator = this.entries(),
            step;
          while (step = iterator.next(), !step.done) proxy.set(step.value[0], step.value[1]);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: LRUCache,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') LRUCache.prototype[Symbol.for('nodejs.util.inspect.custom')] = LRUCache.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} Keys     - Array class for storing keys.
         * @param  {function} Values   - Array class for storing values.
         * @param  {number}   capacity - Cache's capacity.
         * @return {LRUCache}
         */
        LRUCache.from = function (iterable, Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.');
          } else if (arguments.length === 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          var cache = new LRUCache(Keys, Values, capacity);
          forEach(iterable, function (value, key) {
            cache.set(key, value);
          });
          return cache;
        };

        /**
         * Exporting.
         */
        module.exports = LRUCache;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });

      // I am the facade module who provides access to the CommonJS module './lru-cache.js'~
      if (!__cjsMetaURL$A) {
        loader.throwInvalidWrapper('./lru-cache.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-cache.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$A);
      var __cjsMetaURL$B = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-cache-with-delete.js';
      loader.define(__cjsMetaURL$B, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist LRUCacheWithDelete
         * =============================
         *
         * An extension of LRUCache with delete functionality.
         */

        var LRUCache = require('./lru-cache.js'),
          forEach = require('obliterator/foreach'),
          typed = require('./utils/typed-arrays.js'),
          iterables = require('./utils/iterables.js');

        // The only complication with deleting items is that the LRU's
        // performance depends on having a fixed-size list of pointers; the
        // doubly-linked-list is happy to expand and contract.
        //
        // On delete, we record the position of the former item's pointer in a
        // list of "holes" in the pointer array. On insert, if there is a hole
        // the new pointer slots in to fill the hole; otherwise, it is
        // appended as usual. (Note: we are only talking here about the
        // internal pointer list. setting or getting an item promotes it
        // to the top of the LRU ranking no matter what came before)

        function LRUCacheWithDelete(Keys, Values, capacity) {
          if (arguments.length < 2) {
            LRUCache.call(this, Keys);
          } else {
            LRUCache.call(this, Keys, Values, capacity);
          }
          var PointerArray = typed.getPointerArray(this.capacity);
          this.deleted = new PointerArray(this.capacity);
          this.deletedSize = 0;
        }
        for (var k in LRUCache.prototype) LRUCacheWithDelete.prototype[k] = LRUCache.prototype[k];
        if (typeof Symbol !== 'undefined') LRUCacheWithDelete.prototype[Symbol.iterator] = LRUCache.prototype[Symbol.iterator];

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        LRUCacheWithDelete.prototype.clear = function () {
          LRUCache.prototype.clear.call(this);
          this.deletedSize = 0;
        };

        /**
         * Method used to set the value for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {undefined}
         */
        LRUCacheWithDelete.prototype.set = function (key, value) {
          var pointer = this.items[key];

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            this.V[pointer] = value;
            return;
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            if (this.deletedSize > 0) {
              // If there is a "hole" in the pointer list, reuse it
              pointer = this.deleted[--this.deletedSize];
            } else {
              // otherwise append to the pointer list
              pointer = this.size;
            }
            this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            delete this.items[this.K[pointer]];
          }

          // Storing key & value
          this.items[key] = pointer;
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;
        };

        /**
         * Method used to set the value for the given key in the cache
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {{evicted: boolean, key: any, value: any}} An object containing the
         * key and value of an item that was overwritten or evicted in the set
         * operation, as well as a boolean indicating whether it was evicted due to
         * limited capacity. Return value is null if nothing was evicted or overwritten
         * during the set operation.
         */
        LRUCacheWithDelete.prototype.setpop = function (key, value) {
          var oldValue = null;
          var oldKey = null;
          var pointer = this.items[key];

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            oldValue = this.V[pointer];
            this.V[pointer] = value;
            return {
              evicted: false,
              key: key,
              value: oldValue
            };
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            if (this.deletedSize > 0) {
              // If there is a "hole" in the pointer list, reuse it
              pointer = this.deleted[--this.deletedSize];
            } else {
              // otherwise append to the pointer list
              pointer = this.size;
            }
            this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            oldValue = this.V[pointer];
            oldKey = this.K[pointer];
            delete this.items[oldKey];
          }

          // Storing key & value
          this.items[key] = pointer;
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;

          // Return object if eviction took place, otherwise return null
          if (oldKey) {
            return {
              evicted: true,
              key: oldKey,
              value: oldValue
            };
          } else {
            return null;
          }
        };

        /**
         * Method used to delete the entry for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @return {boolean}   - true if the item was present
         */
        LRUCacheWithDelete.prototype.delete = function (key) {
          var pointer = this.items[key];
          if (typeof pointer === 'undefined') {
            return false;
          }
          delete this.items[key];
          if (this.size === 1) {
            this.size = 0;
            this.head = 0;
            this.tail = 0;
            this.deletedSize = 0;
            return true;
          }
          var previous = this.backward[pointer],
            next = this.forward[pointer];
          if (this.head === pointer) {
            this.head = next;
          }
          if (this.tail === pointer) {
            this.tail = previous;
          }
          this.forward[previous] = next;
          this.backward[next] = previous;
          this.size--;
          this.deleted[this.deletedSize++] = pointer;
          return true;
        };

        /**
         * Method used to remove and return the value for the given key in the cache.
         *
         * @param  {any} key                 - Key.
         * @param  {any} [missing=undefined] - Value to return if item is absent
         * @return {any} The value, if present; the missing indicator if absent
         */
        LRUCacheWithDelete.prototype.remove = function (key, missing) {
          if (missing === void 0) {
            missing = undefined;
          }
          var pointer = this.items[key];
          if (typeof pointer === 'undefined') {
            return missing;
          }
          var dead = this.V[pointer];
          delete this.items[key];
          if (this.size === 1) {
            this.size = 0;
            this.head = 0;
            this.tail = 0;
            this.deletedSize = 0;
            return dead;
          }
          var previous = this.backward[pointer],
            next = this.forward[pointer];
          if (this.head === pointer) {
            this.head = next;
          }
          if (this.tail === pointer) {
            this.tail = previous;
          }
          this.forward[previous] = next;
          this.backward[next] = previous;
          this.size--;
          this.deleted[this.deletedSize++] = pointer;
          return dead;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} Keys     - Array class for storing keys.
         * @param  {function} Values   - Array class for storing values.
         * @param  {number}   capacity - Cache's capacity.
         * @return {LRUCacheWithDelete}
         */
        LRUCacheWithDelete.from = function (iterable, Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.');
          } else if (arguments.length === 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          var cache = new LRUCacheWithDelete(Keys, Values, capacity);
          forEach(iterable, function (value, key) {
            cache.set(key, value);
          });
          return cache;
        };
        module.exports = LRUCacheWithDelete;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './lru-cache.js': __cjsMetaURL$A,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });

      // I am the facade module who provides access to the CommonJS module './lru-cache-with-delete.js'~
      if (!__cjsMetaURL$B) {
        loader.throwInvalidWrapper('./lru-cache-with-delete.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-cache-with-delete.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$B);
      var __cjsMetaURL$C = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-map.js';
      loader.define(__cjsMetaURL$C, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist LRUMap
         * =================
         *
         * Variant of the LRUCache class that leverages an ES6 Map instead of an object.
         * It might be faster for some use case but it is still hard to understand
         * when a Map can outperform an object in v8.
         */
        var LRUCache = require('./lru-cache.js'),
          forEach = require('obliterator/foreach'),
          typed = require('./utils/typed-arrays.js'),
          iterables = require('./utils/iterables.js');

        /**
         * LRUMap.
         *
         * @constructor
         * @param {function} Keys     - Array class for storing keys.
         * @param {function} Values   - Array class for storing values.
         * @param {number}   capacity - Desired capacity.
         */
        function LRUMap(Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          this.capacity = capacity;
          if (typeof this.capacity !== 'number' || this.capacity <= 0) throw new Error('mnemonist/lru-map: capacity should be positive number.');else if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity) throw new Error('mnemonist/lru-map: capacity should be a finite positive integer.');
          var PointerArray = typed.getPointerArray(capacity);
          this.forward = new PointerArray(capacity);
          this.backward = new PointerArray(capacity);
          this.K = typeof Keys === 'function' ? new Keys(capacity) : new Array(capacity);
          this.V = typeof Values === 'function' ? new Values(capacity) : new Array(capacity);

          // Properties
          this.size = 0;
          this.head = 0;
          this.tail = 0;
          this.items = new Map();
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        LRUMap.prototype.clear = function () {
          this.size = 0;
          this.head = 0;
          this.tail = 0;
          this.items.clear();
        };

        /**
         * Method used to set the value for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {undefined}
         */
        LRUMap.prototype.set = function (key, value) {
          var pointer = this.items.get(key);

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            this.V[pointer] = value;
            return;
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            pointer = this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            this.items.delete(this.K[pointer]);
          }

          // Storing key & value
          this.items.set(key, pointer);
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;
        };

        /**
         * Method used to set the value for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {{evicted: boolean, key: any, value: any}} An object containing the
         * key and value of an item that was overwritten or evicted in the set
         * operation, as well as a boolean indicating whether it was evicted due to
         * limited capacity. Return value is null if nothing was evicted or overwritten
         * during the set operation.
         */
        LRUMap.prototype.setpop = function (key, value) {
          var oldValue = null;
          var oldKey = null;
          var pointer = this.items.get(key);

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            oldValue = this.V[pointer];
            this.V[pointer] = value;
            return {
              evicted: false,
              key: key,
              value: oldValue
            };
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            pointer = this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            oldValue = this.V[pointer];
            oldKey = this.K[pointer];
            this.items.delete(oldKey);
          }

          // Storing key & value
          this.items.set(key, pointer);
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;

          // Return object if eviction took place, otherwise return null
          if (oldKey) {
            return {
              evicted: true,
              key: oldKey,
              value: oldValue
            };
          } else {
            return null;
          }
        };

        /**
         * Method used to check whether the key exists in the cache.
         *
         * @param  {any} key   - Key.
         * @return {boolean}
         */
        LRUMap.prototype.has = function (key) {
          return this.items.has(key);
        };

        /**
         * Method used to get the value attached to the given key. Will move the
         * related key to the front of the underlying linked list.
         *
         * @param  {any} key   - Key.
         * @return {any}
         */
        LRUMap.prototype.get = function (key) {
          var pointer = this.items.get(key);
          if (typeof pointer === 'undefined') return;
          this.splayOnTop(pointer);
          return this.V[pointer];
        };

        /**
         * Method used to get the value attached to the given key. Does not modify
         * the ordering of the underlying linked list.
         *
         * @param  {any} key   - Key.
         * @return {any}
         */
        LRUMap.prototype.peek = function (key) {
          var pointer = this.items.get(key);
          if (typeof pointer === 'undefined') return;
          return this.V[pointer];
        };

        /**
         * Methods that can be reused as-is from LRUCache.
         */
        LRUMap.prototype.splayOnTop = LRUCache.prototype.splayOnTop;
        LRUMap.prototype.forEach = LRUCache.prototype.forEach;
        LRUMap.prototype.keys = LRUCache.prototype.keys;
        LRUMap.prototype.values = LRUCache.prototype.values;
        LRUMap.prototype.entries = LRUCache.prototype.entries;

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') LRUMap.prototype[Symbol.iterator] = LRUMap.prototype.entries;

        /**
         * Convenience known methods.
         */
        LRUMap.prototype.inspect = LRUCache.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} Keys     - Array class for storing keys.
         * @param  {function} Values   - Array class for storing values.
         * @param  {number}   capacity - Cache's capacity.
         * @return {LRUMap}
         */
        LRUMap.from = function (iterable, Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.');
          } else if (arguments.length === 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          var cache = new LRUMap(Keys, Values, capacity);
          forEach(iterable, function (value, key) {
            cache.set(key, value);
          });
          return cache;
        };

        /**
         * Exporting.
         */
        module.exports = LRUMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './lru-cache.js': __cjsMetaURL$A,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });

      // I am the facade module who provides access to the CommonJS module './lru-map.js'~
      if (!__cjsMetaURL$C) {
        loader.throwInvalidWrapper('./lru-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$C);
      var __cjsMetaURL$D = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-map-with-delete.js';
      loader.define(__cjsMetaURL$D, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist LRUMapWithDelete
         * ===========================
         *
         * An extension of LRUMap with delete functionality.
         */

        var LRUMap = require('./lru-map.js'),
          forEach = require('obliterator/foreach'),
          typed = require('./utils/typed-arrays.js'),
          iterables = require('./utils/iterables.js');

        // The only complication with deleting items is that the LRU's
        // performance depends on having a fixed-size list of pointers; the
        // doubly-linked-list is happy to expand and contract.
        //
        // On delete, we record the position of the former item's pointer in a
        // list of "holes" in the pointer array. On insert, if there is a hole
        // the new pointer slots in to fill the hole; otherwise, it is
        // appended as usual. (Note: we are only talking here about the
        // internal pointer list. setting or getting an item promotes it
        // to the top of the LRU ranking no matter what came before)

        function LRUMapWithDelete(Keys, Values, capacity) {
          if (arguments.length < 2) {
            LRUMap.call(this, Keys);
          } else {
            LRUMap.call(this, Keys, Values, capacity);
          }
          var PointerArray = typed.getPointerArray(this.capacity);
          this.deleted = new PointerArray(this.capacity);
          this.deletedSize = 0;
        }
        for (var k in LRUMap.prototype) LRUMapWithDelete.prototype[k] = LRUMap.prototype[k];
        if (typeof Symbol !== 'undefined') LRUMapWithDelete.prototype[Symbol.iterator] = LRUMap.prototype[Symbol.iterator];

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        LRUMapWithDelete.prototype.clear = function () {
          LRUMap.prototype.clear.call(this);
          this.deletedSize = 0;
        };

        /**
         * Method used to set the value for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {undefined}
         */
        LRUMapWithDelete.prototype.set = function (key, value) {
          var pointer = this.items.get(key);

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            this.V[pointer] = value;
            return;
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            if (this.deletedSize > 0) {
              // If there is a "hole" in the pointer list, reuse it
              pointer = this.deleted[--this.deletedSize];
            } else {
              // otherwise append to the pointer list
              pointer = this.size;
            }
            this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            this.items.delete(this.K[pointer]);
          }

          // Storing key & value
          this.items.set(key, pointer);
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;
        };

        /**
         * Method used to set the value for the given key in the cache
         *
         * @param  {any} key   - Key.
         * @param  {any} value - Value.
         * @return {{evicted: boolean, key: any, value: any}} An object containing the
         * key and value of an item that was overwritten or evicted in the set
         * operation, as well as a boolean indicating whether it was evicted due to
         * limited capacity. Return value is null if nothing was evicted or overwritten
         * during the set operation.
         */
        LRUMapWithDelete.prototype.setpop = function (key, value) {
          var oldValue = null;
          var oldKey = null;
          var pointer = this.items.get(key);

          // The key already exists, we just need to update the value and splay on top
          if (typeof pointer !== 'undefined') {
            this.splayOnTop(pointer);
            oldValue = this.V[pointer];
            this.V[pointer] = value;
            return {
              evicted: false,
              key: key,
              value: oldValue
            };
          }

          // The cache is not yet full
          if (this.size < this.capacity) {
            if (this.deletedSize > 0) {
              // If there is a "hole" in the pointer list, reuse it
              pointer = this.deleted[--this.deletedSize];
            } else {
              // otherwise append to the pointer list
              pointer = this.size;
            }
            this.size++;
          }

          // Cache is full, we need to drop the last value
          else {
            pointer = this.tail;
            this.tail = this.backward[pointer];
            oldValue = this.V[pointer];
            oldKey = this.K[pointer];
            this.items.delete(oldKey);
          }

          // Storing key & value
          this.items.set(key, pointer);
          this.K[pointer] = key;
          this.V[pointer] = value;

          // Moving the item at the front of the list
          this.forward[pointer] = this.head;
          this.backward[this.head] = pointer;
          this.head = pointer;

          // Return object if eviction took place, otherwise return null
          if (oldKey) {
            return {
              evicted: true,
              key: oldKey,
              value: oldValue
            };
          } else {
            return null;
          }
        };

        /**
         * Method used to delete the entry for the given key in the cache.
         *
         * @param  {any} key   - Key.
         * @return {boolean}   - true if the item was present
         */
        LRUMapWithDelete.prototype.delete = function (key) {
          var pointer = this.items.get(key);
          if (typeof pointer === 'undefined') {
            return false;
          }
          this.items.delete(key);
          if (this.size === 1) {
            this.size = 0;
            this.head = 0;
            this.tail = 0;
            this.deletedSize = 0;
            return true;
          }
          var previous = this.backward[pointer],
            next = this.forward[pointer];
          if (this.head === pointer) {
            this.head = next;
          }
          if (this.tail === pointer) {
            this.tail = previous;
          }
          this.forward[previous] = next;
          this.backward[next] = previous;
          this.size--;
          this.deleted[this.deletedSize++] = pointer;
          return true;
        };

        /**
         * Method used to remove and return the value for the given key in the cache.
         *
         * @param  {any} key                 - Key.
         * @param  {any} [missing=undefined] - Value to return if item is absent
         * @return {any} The value, if present; the missing indicator if absent
         */
        LRUMapWithDelete.prototype.remove = function (key, missing) {
          if (missing === void 0) {
            missing = undefined;
          }
          var pointer = this.items.get(key);
          if (typeof pointer === 'undefined') {
            return missing;
          }
          var dead = this.V[pointer];
          this.items.delete(key);
          if (this.size === 1) {
            this.size = 0;
            this.head = 0;
            this.tail = 0;
            this.deletedSize = 0;
            return dead;
          }
          var previous = this.backward[pointer],
            next = this.forward[pointer];
          if (this.head === pointer) {
            this.head = next;
          }
          if (this.tail === pointer) {
            this.tail = previous;
          }
          this.forward[previous] = next;
          this.backward[next] = previous;
          this.size--;
          this.deleted[this.deletedSize++] = pointer;
          return dead;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} Keys     - Array class for storing keys.
         * @param  {function} Values   - Array class for storing values.
         * @param  {number}   capacity - Cache's capacity.
         * @return {LRUMapWithDelete}
         */
        LRUMapWithDelete.from = function (iterable, Keys, Values, capacity) {
          if (arguments.length < 2) {
            capacity = iterables.guessLength(iterable);
            if (typeof capacity !== 'number') throw new Error('mnemonist/lru-map.from: could not guess iterable length. Please provide desired capacity as last argument.');
          } else if (arguments.length === 2) {
            capacity = Keys;
            Keys = null;
            Values = null;
          }
          var cache = new LRUMapWithDelete(Keys, Values, capacity);
          forEach(iterable, function (value, key) {
            cache.set(key, value);
          });
          return cache;
        };
        module.exports = LRUMapWithDelete;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './lru-map.js': __cjsMetaURL$C,
          'obliterator/foreach': __cjsMetaURL$3,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './utils/iterables.js': __cjsMetaURL$6
        };
      });

      // I am the facade module who provides access to the CommonJS module './lru-map-with-delete.js'~
      if (!__cjsMetaURL$D) {
        loader.throwInvalidWrapper('./lru-map-with-delete.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/lru-map-with-delete.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$D);

      // I am the facade module who provides access to the CommonJS module './multi-map.js'~
      if (!__cjsMetaURL$p) {
        loader.throwInvalidWrapper('./multi-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/multi-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$p);
      var __cjsMetaURL$E = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/multi-set.js';
      loader.define(__cjsMetaURL$E, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist MultiSet
         * ====================
         *
         * JavaScript implementation of a MultiSet.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach'),
          FixedReverseHeap = require('./fixed-reverse-heap.js');

        /**
         * Helpers.
         */
        var MULTISET_ITEM_COMPARATOR = function MULTISET_ITEM_COMPARATOR(a, b) {
          if (a[1] > b[1]) return -1;
          if (a[1] < b[1]) return 1;
          return 0;
        };

        // TODO: helper functions: union, intersection, sum, difference, subtract

        /**
         * MultiSet.
         *
         * @constructor
         */
        function MultiSet() {
          this.items = new Map();
          Object.defineProperty(this.items, 'constructor', {
            value: MultiSet,
            enumerable: false
          });
          this.clear();
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        MultiSet.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.dimension = 0;
          this.items.clear();
        };

        /**
         * Method used to add an item to the set.
         *
         * @param  {any}    item  - Item to add.
         * @param  {number} count - Optional count.
         * @return {MultiSet}
         */
        MultiSet.prototype.add = function (item, count) {
          if (count === 0) return this;
          if (count < 0) return this.remove(item, -count);
          count = count || 1;
          if (typeof count !== 'number') throw new Error('mnemonist/multi-set.add: given count should be a number.');
          this.size += count;
          var currentCount = this.items.get(item);
          if (currentCount === undefined) this.dimension++;else count += currentCount;
          this.items.set(item, count);
          return this;
        };

        /**
         * Method used to set the multiplicity of an item in the set.
         *
         * @param  {any}    item  - Target item.
         * @param  {number} count - Desired multiplicity.
         * @return {MultiSet}
         */
        MultiSet.prototype.set = function (item, count) {
          var currentCount;
          if (typeof count !== 'number') throw new Error('mnemonist/multi-set.set: given count should be a number.');

          // Setting an item to 0 or to a negative number means deleting it from the set
          if (count <= 0) {
            currentCount = this.items.get(item);
            if (typeof currentCount !== 'undefined') {
              this.size -= currentCount;
              this.dimension--;
            }
            this.items.delete(item);
            return this;
          }
          count = count || 1;
          currentCount = this.items.get(item);
          if (typeof currentCount === 'number') {
            this.items.set(item, currentCount + count);
          } else {
            this.dimension++;
            this.items.set(item, count);
          }
          this.size += count;
          return this;
        };

        /**
         * Method used to return whether the item exists in the set.
         *
         * @param  {any} item  - Item to check.
         * @return {boolan}
         */
        MultiSet.prototype.has = function (item) {
          return this.items.has(item);
        };

        /**
         * Method used to delete an item from the set.
         *
         * @param  {any} item  - Item to delete.
         * @return {boolan}
         */
        MultiSet.prototype.delete = function (item) {
          var count = this.items.get(item);
          if (count === 0) return false;
          this.size -= count;
          this.dimension--;
          this.items.delete(item);
          return true;
        };

        /**
         * Method used to remove an item from the set.
         *
         * @param  {any} item  - Item to delete.
         * @param  {number} count - Optional count.
         * @return {undefined}
         */
        MultiSet.prototype.remove = function (item, count) {
          if (count === 0) return;
          if (count < 0) return this.add(item, -count);
          count = count || 1;
          if (typeof count !== 'number') throw new Error('mnemonist/multi-set.remove: given count should be a number.');
          var currentCount = this.items.get(item);
          if (typeof currentCount === 'undefined') return;
          var newCount = Math.max(0, currentCount - count);
          if (newCount === 0) {
            this.items.delete(item);
            this.size -= currentCount;
            this.dimension--;
          } else {
            this.items.set(item, newCount);
            this.size -= count;
          }
          return;
        };

        /**
         * Method used to change a key into another one, merging counts if the target
         * key already exists.
         *
         * @param  {any} a - From key.
         * @param  {any} b - To key.
         * @return {MultiSet}
         */
        MultiSet.prototype.edit = function (a, b) {
          var am = this.multiplicity(a);

          // If a does not exist in the set, we can stop right there
          if (am === 0) return;
          var bm = this.multiplicity(b);
          this.items.set(b, am + bm);
          this.items.delete(a);
          return this;
        };

        /**
         * Method used to return the multiplicity of the given item.
         *
         * @param  {any} item  - Item to get.
         * @return {number}
         */
        MultiSet.prototype.multiplicity = function (item) {
          var count = this.items.get(item);
          if (typeof count === 'undefined') return 0;
          return count;
        };
        MultiSet.prototype.get = MultiSet.prototype.multiplicity;
        MultiSet.prototype.count = MultiSet.prototype.multiplicity;

        /**
         * Method used to return the frequency of the given item in the set.
         *
         * @param  {any} item - Item to get.
         * @return {number}
         */
        MultiSet.prototype.frequency = function (item) {
          if (this.size === 0) return 0;
          var count = this.multiplicity(item);
          return count / this.size;
        };

        /**
         * Method used to return the n most common items from the set.
         *
         * @param  {number} n - Number of items to retrieve.
         * @return {array}
         */
        MultiSet.prototype.top = function (n) {
          if (typeof n !== 'number' || n <= 0) throw new Error('mnemonist/multi-set.top: n must be a number > 0.');
          var heap = new FixedReverseHeap(Array, MULTISET_ITEM_COMPARATOR, n);
          var iterator = this.items.entries(),
            step;
          while (step = iterator.next(), !step.done) heap.push(step.value);
          return heap.consume();
        };

        /**
         * Method used to iterate over the set's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        MultiSet.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var i;
          this.items.forEach(function (multiplicity, value) {
            for (i = 0; i < multiplicity; i++) callback.call(scope, value, value);
          });
        };

        /**
         * Method used to iterate over the set's multiplicities.
         *
         * @param  {function}  callback - Function to call for each multiplicity.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        MultiSet.prototype.forEachMultiplicity = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          this.items.forEach(callback, scope);
        };

        /**
         * Method returning an iterator over the set's keys. I.e. its unique values,
         * in a sense.
         *
         * @return {Iterator}
         */
        MultiSet.prototype.keys = function () {
          return this.items.keys();
        };

        /**
         * Method returning an iterator over the set's values.
         *
         * @return {Iterator}
         */
        MultiSet.prototype.values = function () {
          var iterator = this.items.entries(),
            inContainer = false,
            step,
            value,
            multiplicity,
            i;
          return new Iterator(function next() {
            if (!inContainer) {
              step = iterator.next();
              if (step.done) return {
                done: true
              };
              inContainer = true;
              value = step.value[0];
              multiplicity = step.value[1];
              i = 0;
            }
            if (i >= multiplicity) {
              inContainer = false;
              return next();
            }
            i++;
            return {
              done: false,
              value: value
            };
          });
        };

        /**
         * Method returning an iterator over the set's multiplicities.
         *
         * @return {Iterator}
         */
        MultiSet.prototype.multiplicities = function () {
          return this.items.entries();
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') MultiSet.prototype[Symbol.iterator] = MultiSet.prototype.values;

        /**
         * Convenience known methods.
         */
        MultiSet.prototype.inspect = function () {
          return this.items;
        };
        if (typeof Symbol !== 'undefined') MultiSet.prototype[Symbol.for('nodejs.util.inspect.custom')] = MultiSet.prototype.inspect;
        MultiSet.prototype.toJSON = function () {
          return this.items;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @return {MultiSet}
         */
        MultiSet.from = function (iterable) {
          var set = new MultiSet();
          forEach(iterable, function (value) {
            set.add(value);
          });
          return set;
        };

        /**
         * Function returning whether the multiset A is a subset of the multiset B.
         *
         * @param  {MultiSet} A - First set.
         * @param  {MultiSet} B - Second set.
         * @return {boolean}
         */
        MultiSet.isSubset = function (A, B) {
          var iterator = A.multiplicities(),
            step,
            key,
            mA;

          // Shortcuts
          if (A === B) return true;
          if (A.dimension > B.dimension) return false;
          while (step = iterator.next(), !step.done) {
            key = step.value[0];
            mA = step.value[1];
            if (B.multiplicity(key) < mA) return false;
          }
          return true;
        };

        /**
         * Function returning whether the multiset A is a superset of the multiset B.
         *
         * @param  {MultiSet} A - First set.
         * @param  {MultiSet} B - Second set.
         * @return {boolean}
         */
        MultiSet.isSuperset = function (A, B) {
          return MultiSet.isSubset(B, A);
        };

        /**
         * Exporting.
         */
        module.exports = MultiSet;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3,
          './fixed-reverse-heap.js': __cjsMetaURL$n
        };
      });

      // I am the facade module who provides access to the CommonJS module './multi-set.js'~
      if (!__cjsMetaURL$E) {
        loader.throwInvalidWrapper('./multi-set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/multi-set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$E);
      var __cjsMetaURL$F = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/passjoin-index.js';
      loader.define(__cjsMetaURL$F, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist PassjoinIndex
         * ========================
         *
         * The PassjoinIndex is an index leveraging the "passjoin" algorithm as a mean
         * to index strings for Levenshtein distance queries. It features a complexity
         * related to the Levenshtein query threshold k rather than the number of
         * strings to test (roughly O(k^3)).
         *
         * [References]:
         * Jiang, Yu, Dong Deng, Jiannan Wang, Guoliang Li, et Jianhua Feng.
         * « Efficient Parallel Partition-Based Algorithms for Similarity Search and Join
         * with Edit Distance Constraints ». In Proceedings of the Joint EDBT/ICDT 2013
         * Workshops on - EDBT ’13, 341. Genoa, Italy: ACM Press, 2013.
         * https://doi.org/10.1145/2457317.2457382.
         *
         * Li, Guoliang, Dong Deng, et Jianhua Feng. « A Partition-Based Method for
         * String Similarity Joins with Edit-Distance Constraints ». ACM Transactions on
         * Database Systems 38, no 2 (1 juin 2013): 1‑33.
         * https://doi.org/10.1145/2487259.2487261.
         *
         * [Urls]:
         * http://people.csail.mit.edu/dongdeng/projects/passjoin/index.html
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach');

        // TODO: leveraging BagDistance as an upper bound of Levenshtein
        // TODO: leverage n-grams recursive indexing
        // TODO: try the MultiArray as a memory backend
        // TODO: what about damerau levenshtein

        /**
         * Helpers.
         */

        /**
         * Function returning the number of substrings that will be selected by the
         * multi-match-aware selection scheme for theshold `k`, for a string of length
         * `s` to match strings of length `l`.
         *
         * @param   {number} k - Levenshtein distance threshold.
         * @param   {number} s - Length of target strings.
         * @param   {number} l - Length of strings to match.
         * @returns {number}   - The number of selected substrings.
         */
        function countSubstringsL(k, s, l) {
          return ((Math.pow(k, 2) - Math.pow(Math.abs(s - l), 2)) / 2 | 0) + k + 1;
        }

        /**
         * Function returning the minimum number of substrings that will be selected by
         * the multi-match-aware selection scheme for theshold `k`, for a string of
         * length `s` to match any string of relevant length.
         *
         * @param   {number} k - Levenshtein distance threshold.
         * @param   {number} s - Length of target strings.
         * @returns {number}   - The number of selected substrings.
         */
        function countKeys(k, s) {
          var c = 0;
          for (var l = 0, m = s + 1; l < m; l++) c += countSubstringsL(k, s, l);
          return c;
        }

        /**
         * Function used to compare two keys in order to sort them first by decreasing
         * length and then alphabetically as per the "4.2 Effective Indexing Strategy"
         * point of the paper.
         *
         * @param   {number} k - Levenshtein distance threshold.
         * @param   {number} s - Length of target strings.
         * @returns {number}   - The number of selected substrings.
         */
        function comparator(a, b) {
          if (a.length > b.length) return -1;
          if (a.length < b.length) return 1;
          if (a < b) return -1;
          if (a > b) return 1;
          return 0;
        }

        /**
         * Function partitioning a string into k + 1 uneven segments, the shorter
         * ones, then the longer ones.
         *
         * @param   {number} k - Levenshtein distance threshold.
         * @param   {number} l - Length of the string.
         * @returns {Array}    - The partition tuples (start, length).
         */
        function partition(k, l) {
          var m = k + 1,
            a = l / m | 0,
            b = a + 1,
            i,
            j;
          var largeSegments = l - a * m,
            smallSegments = m - largeSegments;
          var tuples = new Array(k + 1);
          for (i = 0; i < smallSegments; i++) tuples[i] = [i * a, a];
          var offset = (i - 1) * a + a;
          for (j = 0; j < largeSegments; j++) tuples[i + j] = [offset + j * b, b];
          return tuples;
        }

        /**
         * Function yielding a string's k + 1 passjoin segments to index.
         *
         * @param   {number} k      - Levenshtein distance threshold.
         * @param   {string} string - Target string.
         * @returns {Array}         - The string's segments.
         */
        function segments(k, string) {
          var l = string.length,
            m = k + 1,
            a = l / m | 0,
            b = a + 1,
            o,
            i,
            j;
          var largeSegments = l - a * m,
            smallSegments = m - largeSegments;
          var S = new Array(k + 1);
          for (i = 0; i < smallSegments; i++) {
            o = i * a;
            S[i] = string.slice(o, o + a);
          }
          var offset = (i - 1) * a + a;
          for (j = 0; j < largeSegments; j++) {
            o = offset + j * b;
            S[i + j] = string.slice(o, o + b);
          }
          return S;
        }

        // TODO: jsdocs
        function segmentPos(k, i, string) {
          if (i === 0) return 0;
          var l = string.length;
          var m = k + 1,
            a = l / m | 0,
            b = a + 1;
          var largeSegments = l - a * m,
            smallSegments = m - largeSegments;
          if (i <= smallSegments - 1) return i * a;
          var offset = i - smallSegments;
          return smallSegments * a + offset * b;
        }

        /**
         * Function returning the interval of relevant substrings to lookup using the
         * multi-match-aware substring selection scheme described in the paper.
         *
         * @param   {number} k      - Levenshtein distance threshold.
         * @param   {number} delta  - Signed length difference between both considered strings.
         * @param   {number} i      - k + 1 segment index.
         * @param   {number} s      - String's length.
         * @param   {number} pi     - k + 1 segment position in target string.
         * @param   {number} li     - k + 1 segment length.
         * @returns {Array}         - The interval (start, stop).
         */
        function multiMatchAwareInterval(k, delta, i, s, pi, li) {
          var start1 = pi - i,
            end1 = pi + i;
          var o = k - i;
          var start2 = pi + delta - o,
            end2 = pi + delta + o;
          var end3 = s - li;
          return [Math.max(0, start1, start2), Math.min(end1, end2, end3)];
        }

        /**
         * Function yielding relevant substrings to lookup using the multi-match-aware
         * substring selection scheme described in the paper.
         *
         * @param   {number} k      - Levenshtein distance threshold.
         * @param   {string} string  - Target string.
         * @param   {number} l      - Length of strings to match.
         * @param   {number} i      - k + 1 segment index.
         * @param   {number} pi     - k + 1 segment position in target string.
         * @param   {number} li     - k + 1 segment length.
         * @returns {Array}         - The contiguous substrings.
         */
        function multiMatchAwareSubstrings(k, string, l, i, pi, li) {
          var s = string.length;

          // Note that we need to keep the non-absolute delta for this function
          // to work in both directions, up & down
          var delta = s - l;
          var interval = multiMatchAwareInterval(k, delta, i, s, pi, li);
          var start = interval[0],
            stop = interval[1];
          var currentSubstring = '';
          var substrings = [];
          var substring, j, m;
          for (j = start, m = stop + 1; j < m; j++) {
            substring = string.slice(j, j + li);

            // We skip identical consecutive substrings (to avoid repetition in case
            // of contiguous letter duplication)
            if (substring === currentSubstring) continue;
            substrings.push(substring);
            currentSubstring = substring;
          }
          return substrings;
        }

        /**
         * PassjoinIndex.
         *
         * @note I tried to apply the paper's optimizations regarding Levenshtein
         * distance computations but it did not provide a performance boost, quite
         * the contrary. This is because since we are mostly using the index for small k
         * here, most of the strings we work on are quite small and the bookkeeping
         * induced by Ukkonen's method and the paper's one are slowing us down more than
         * they actually help us go faster.
         *
         * @note This implementation does not try to ensure that you add the same string
         * more than once.
         *
         * @constructor
         * @param {function} levenshtein - Levenshtein distance function.
         * @param {number}   k           - Levenshtein distance threshold.
         */
        function PassjoinIndex(levenshtein, k) {
          if (typeof levenshtein !== 'function') throw new Error('mnemonist/passjoin-index: `levenshtein` should be a function returning edit distance between two strings.');
          if (typeof k !== 'number' || k < 1) throw new Error('mnemonist/passjoin-index: `k` should be a number > 0');
          this.levenshtein = levenshtein;
          this.k = k;
          this.clear();
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        PassjoinIndex.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.strings = [];
          this.invertedIndices = {};
        };

        /**
         * Method used to add a new value to the index.
         *
         * @param  {string|Array} value - Value to add.
         * @return {PassjoinIndex}
         */
        PassjoinIndex.prototype.add = function (value) {
          var l = value.length;
          var stringIndex = this.size;
          this.strings.push(value);
          this.size++;
          var S = segments(this.k, value);
          var Ll = this.invertedIndices[l];
          if (typeof Ll === 'undefined') {
            Ll = {};
            this.invertedIndices[l] = Ll;
          }
          var segment, matches, key, i, m;
          for (i = 0, m = S.length; i < m; i++) {
            segment = S[i];
            key = segment + i;
            matches = Ll[key];
            if (typeof matches === 'undefined') {
              matches = [stringIndex];
              Ll[key] = matches;
            } else {
              matches.push(stringIndex);
            }
          }
          return this;
        };

        /**
         * Method used to search for string matching the given query.
         *
         * @param  {string|Array} query - Query string.
         * @return {Array}
         */
        PassjoinIndex.prototype.search = function (query) {
          var s = query.length,
            k = this.k;
          var M = new Set();
          var candidates, candidate, queryPos, querySegmentLength, key, S, P, l, m, i, n1, j, n2, y, n3;
          for (l = Math.max(0, s - k), m = s + k + 1; l < m; l++) {
            var Ll = this.invertedIndices[l];
            if (typeof Ll === 'undefined') continue;
            P = partition(k, l);
            for (i = 0, n1 = P.length; i < n1; i++) {
              queryPos = P[i][0];
              querySegmentLength = P[i][1];
              S = multiMatchAwareSubstrings(k, query, l, i, queryPos, querySegmentLength);

              // Empty string edge case
              if (!S.length) S = [''];
              for (j = 0, n2 = S.length; j < n2; j++) {
                key = S[j] + i;
                candidates = Ll[key];
                if (typeof candidates === 'undefined') continue;
                for (y = 0, n3 = candidates.length; y < n3; y++) {
                  candidate = this.strings[candidates[y]];

                  // NOTE: first condition is here not to compute Levenshtein
                  // distance for tiny strings

                  // NOTE: maintaining a Set of rejected candidate is not really useful
                  // because it consumes more memory and because non-matches are
                  // less likely to be candidates agains
                  if (s <= k && l <= k || !M.has(candidate) && this.levenshtein(query, candidate) <= k) M.add(candidate);
                }
              }
            }
          }
          return M;
        };

        /**
         * Method used to iterate over the index.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        PassjoinIndex.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = 0, l = this.strings.length; i < l; i++) callback.call(scope, this.strings[i], i, this);
        };

        /**
         * Method used to create an iterator over a index's values.
         *
         * @return {Iterator}
         */
        PassjoinIndex.prototype.values = function () {
          var strings = this.strings,
            l = strings.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = strings[i];
            i++;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') PassjoinIndex.prototype[Symbol.iterator] = PassjoinIndex.prototype.values;

        /**
         * Convenience known methods.
         */
        PassjoinIndex.prototype.inspect = function () {
          var array = this.strings.slice();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: PassjoinIndex,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') PassjoinIndex.prototype[Symbol.for('nodejs.util.inspect.custom')] = PassjoinIndex.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @return {PassjoinIndex}
         */
        PassjoinIndex.from = function (iterable, levenshtein, k) {
          var index = new PassjoinIndex(levenshtein, k);
          forEach(iterable, function (string) {
            index.add(string);
          });
          return index;
        };

        /**
         * Exporting.
         */
        PassjoinIndex.countKeys = countKeys;
        PassjoinIndex.comparator = comparator;
        PassjoinIndex.partition = partition;
        PassjoinIndex.segments = segments;
        PassjoinIndex.segmentPos = segmentPos;
        PassjoinIndex.multiMatchAwareInterval = multiMatchAwareInterval;
        PassjoinIndex.multiMatchAwareSubstrings = multiMatchAwareSubstrings;
        module.exports = PassjoinIndex;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './passjoin-index.js'~
      if (!__cjsMetaURL$F) {
        loader.throwInvalidWrapper('./passjoin-index.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/passjoin-index.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$F);
      var __cjsMetaURL$G = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/queue.js';
      loader.define(__cjsMetaURL$G, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Queue
         * ================
         *
         * Queue implementation based on the ideas of Queue.js that seems to beat
         * a LinkedList one in performance.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach');

        /**
         * Queue
         *
         * @constructor
         */
        function Queue() {
          this.clear();
        }

        /**
         * Method used to clear the queue.
         *
         * @return {undefined}
         */
        Queue.prototype.clear = function () {
          // Properties
          this.items = [];
          this.offset = 0;
          this.size = 0;
        };

        /**
         * Method used to add an item to the queue.
         *
         * @param  {any}    item - Item to enqueue.
         * @return {number}
         */
        Queue.prototype.enqueue = function (item) {
          this.items.push(item);
          return ++this.size;
        };

        /**
         * Method used to retrieve & remove the first item of the queue.
         *
         * @return {any}
         */
        Queue.prototype.dequeue = function () {
          if (!this.size) return;
          var item = this.items[this.offset];
          if (++this.offset * 2 >= this.items.length) {
            this.items = this.items.slice(this.offset);
            this.offset = 0;
          }
          this.size--;
          return item;
        };

        /**
         * Method used to retrieve the first item of the queue.
         *
         * @return {any}
         */
        Queue.prototype.peek = function () {
          if (!this.size) return;
          return this.items[this.offset];
        };

        /**
         * Method used to iterate over the queue.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        Queue.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = this.offset, j = 0, l = this.items.length; i < l; i++, j++) callback.call(scope, this.items[i], j, this);
        };

        /*
         * Method used to convert the queue to a JavaScript array.
         *
         * @return {array}
         */
        Queue.prototype.toArray = function () {
          return this.items.slice(this.offset);
        };

        /**
         * Method used to create an iterator over a queue's values.
         *
         * @return {Iterator}
         */
        Queue.prototype.values = function () {
          var items = this.items,
            i = this.offset;
          return new Iterator(function () {
            if (i >= items.length) return {
              done: true
            };
            var value = items[i];
            i++;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over a queue's entries.
         *
         * @return {Iterator}
         */
        Queue.prototype.entries = function () {
          var items = this.items,
            i = this.offset,
            j = 0;
          return new Iterator(function () {
            if (i >= items.length) return {
              done: true
            };
            var value = items[i];
            i++;
            return {
              value: [j++, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') Queue.prototype[Symbol.iterator] = Queue.prototype.values;

        /**
         * Convenience known methods.
         */
        Queue.prototype.toString = function () {
          return this.toArray().join(',');
        };
        Queue.prototype.toJSON = function () {
          return this.toArray();
        };
        Queue.prototype.inspect = function () {
          var array = this.toArray();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: Queue,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') Queue.prototype[Symbol.for('nodejs.util.inspect.custom')] = Queue.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a queue.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @return {Queue}
         */
        Queue.from = function (iterable) {
          var queue = new Queue();
          forEach(iterable, function (value) {
            queue.enqueue(value);
          });
          return queue;
        };

        /**
         * Static @.of function taking an arbitrary number of arguments & converting it
         * into a queue.
         *
         * @param  {...any} args
         * @return {Queue}
         */
        Queue.of = function () {
          return Queue.from(arguments);
        };

        /**
         * Exporting.
         */
        module.exports = Queue;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './queue.js'~
      if (!__cjsMetaURL$G) {
        loader.throwInvalidWrapper('./queue.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/queue.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$G);

      // I am the facade module who provides access to the CommonJS module './fixed-stack.js'~
      if (!__cjsMetaURL$s) {
        loader.throwInvalidWrapper('./fixed-stack.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/fixed-stack.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$s);
      var __cjsMetaURL$H = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/stack.js';
      loader.define(__cjsMetaURL$H, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Stack
         * ================
         *
         * Stack implementation relying on JavaScript arrays, which are fast enough &
         * correctly optimized for this kind of work.
         */
        var Iterator = require('obliterator/iterator'),
          forEach = require('obliterator/foreach');

        /**
         * Stack
         *
         * @constructor
         */
        function Stack() {
          this.clear();
        }

        /**
         * Method used to clear the stack.
         *
         * @return {undefined}
         */
        Stack.prototype.clear = function () {
          // Properties
          this.items = [];
          this.size = 0;
        };

        /**
         * Method used to add an item to the stack.
         *
         * @param  {any}    item - Item to add.
         * @return {number}
         */
        Stack.prototype.push = function (item) {
          this.items.push(item);
          return ++this.size;
        };

        /**
         * Method used to retrieve & remove the last item of the stack.
         *
         * @return {any}
         */
        Stack.prototype.pop = function () {
          if (this.size === 0) return;
          this.size--;
          return this.items.pop();
        };

        /**
         * Method used to get the last item of the stack.
         *
         * @return {any}
         */
        Stack.prototype.peek = function () {
          return this.items[this.size - 1];
        };

        /**
         * Method used to iterate over the stack.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        Stack.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = 0, l = this.items.length; i < l; i++) callback.call(scope, this.items[l - i - 1], i, this);
        };

        /**
         * Method used to convert the stack to a JavaScript array.
         *
         * @return {array}
         */
        Stack.prototype.toArray = function () {
          var array = new Array(this.size),
            l = this.size - 1,
            i = this.size;
          while (i--) array[i] = this.items[l - i];
          return array;
        };

        /**
         * Method used to create an iterator over a stack's values.
         *
         * @return {Iterator}
         */
        Stack.prototype.values = function () {
          var items = this.items,
            l = items.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[l - i - 1];
            i++;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Method used to create an iterator over a stack's entries.
         *
         * @return {Iterator}
         */
        Stack.prototype.entries = function () {
          var items = this.items,
            l = items.length,
            i = 0;
          return new Iterator(function () {
            if (i >= l) return {
              done: true
            };
            var value = items[l - i - 1];
            return {
              value: [i++, value],
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') Stack.prototype[Symbol.iterator] = Stack.prototype.values;

        /**
         * Convenience known methods.
         */
        Stack.prototype.toString = function () {
          return this.toArray().join(',');
        };
        Stack.prototype.toJSON = function () {
          return this.toArray();
        };
        Stack.prototype.inspect = function () {
          var array = this.toArray();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: Stack,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') Stack.prototype[Symbol.for('nodejs.util.inspect.custom')] = Stack.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a stack.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @return {Stack}
         */
        Stack.from = function (iterable) {
          var stack = new Stack();
          forEach(iterable, function (value) {
            stack.push(value);
          });
          return stack;
        };

        /**
         * Static @.of function taking an arbitrary number of arguments & converting it
         * into a stack.
         *
         * @param  {...any} args
         * @return {Stack}
         */
        Stack.of = function () {
          return Stack.from(arguments);
        };

        /**
         * Exporting.
         */
        module.exports = Stack;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './stack.js'~
      if (!__cjsMetaURL$H) {
        loader.throwInvalidWrapper('./stack.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/stack.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$H);
      var __cjsMetaURL$I = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-queue-set.js';
      loader.define(__cjsMetaURL$I, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist SparseQueueSet
         * =========================
         *
         * JavaScript sparse queue set implemented on top of byte arrays.
         *
         * [Reference]: https://research.swtch.com/sparse
         */
        var Iterator = require('obliterator/iterator'),
          getPointerArray = require('./utils/typed-arrays.js').getPointerArray;

        /**
         * SparseQueueSet.
         *
         * @constructor
         */
        function SparseQueueSet(capacity) {
          var ByteArray = getPointerArray(capacity);

          // Properties
          this.start = 0;
          this.size = 0;
          this.capacity = capacity;
          this.dense = new ByteArray(capacity);
          this.sparse = new ByteArray(capacity);
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        SparseQueueSet.prototype.clear = function () {
          this.start = 0;
          this.size = 0;
        };

        /**
         * Method used to check the existence of a member in the queue.
         *
         * @param  {number} member - Member to test.
         * @return {SparseQueueSet}
         */
        SparseQueueSet.prototype.has = function (member) {
          if (this.size === 0) return false;
          var index = this.sparse[member];
          var inBounds = index < this.capacity && index >= this.start && index < this.start + this.size || index < (this.start + this.size) % this.capacity;
          return inBounds && this.dense[index] === member;
        };

        /**
         * Method used to add a member to the queue.
         *
         * @param  {number} member - Member to add.
         * @return {SparseQueueSet}
         */
        SparseQueueSet.prototype.enqueue = function (member) {
          var index = this.sparse[member];
          if (this.size !== 0) {
            var inBounds = index < this.capacity && index >= this.start && index < this.start + this.size || index < (this.start + this.size) % this.capacity;
            if (inBounds && this.dense[index] === member) return this;
          }
          index = (this.start + this.size) % this.capacity;
          this.dense[index] = member;
          this.sparse[member] = index;
          this.size++;
          return this;
        };

        /**
         * Method used to remove the next member from the queue.
         *
         * @param  {number} member - Member to delete.
         * @return {boolean}
         */
        SparseQueueSet.prototype.dequeue = function () {
          if (this.size === 0) return;
          var index = this.start;
          this.size--;
          this.start++;
          if (this.start === this.capacity) this.start = 0;
          var member = this.dense[index];
          this.sparse[member] = this.capacity;
          return member;
        };

        /**
         * Method used to iterate over the queue's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        SparseQueueSet.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          while (j < l) {
            callback.call(scope, this.dense[i], j, this);
            i++;
            j++;
            if (i === c) i = 0;
          }
        };

        /**
         * Method used to create an iterator over a set's values.
         *
         * @return {Iterator}
         */
        SparseQueueSet.prototype.values = function () {
          var dense = this.dense,
            c = this.capacity,
            l = this.size,
            i = this.start,
            j = 0;
          return new Iterator(function () {
            if (j >= l) return {
              done: true
            };
            var value = dense[i];
            i++;
            j++;
            if (i === c) i = 0;
            return {
              value: value,
              done: false
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') SparseQueueSet.prototype[Symbol.iterator] = SparseQueueSet.prototype.values;

        /**
         * Convenience known methods.
         */
        SparseQueueSet.prototype.inspect = function () {
          var proxy = [];
          this.forEach(function (member) {
            proxy.push(member);
          });

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: SparseQueueSet,
            enumerable: false
          });
          proxy.capacity = this.capacity;
          return proxy;
        };
        if (typeof Symbol !== 'undefined') SparseQueueSet.prototype[Symbol.for('nodejs.util.inspect.custom')] = SparseQueueSet.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = SparseQueueSet;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/typed-arrays.js': __cjsMetaURL$5
        };
      });

      // I am the facade module who provides access to the CommonJS module './sparse-queue-set.js'~
      if (!__cjsMetaURL$I) {
        loader.throwInvalidWrapper('./sparse-queue-set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-queue-set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$I);
      var __cjsMetaURL$J = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-map.js';
      loader.define(__cjsMetaURL$J, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist SparseMap
         * ====================
         *
         * JavaScript sparse map implemented on top of byte arrays.
         *
         * [Reference]: https://research.swtch.com/sparse
         */
        var Iterator = require('obliterator/iterator'),
          getPointerArray = require('./utils/typed-arrays.js').getPointerArray;

        /**
         * SparseMap.
         *
         * @constructor
         */
        function SparseMap(Values, length) {
          if (arguments.length < 2) {
            length = Values;
            Values = Array;
          }
          var ByteArray = getPointerArray(length);

          // Properties
          this.size = 0;
          this.length = length;
          this.dense = new ByteArray(length);
          this.sparse = new ByteArray(length);
          this.vals = new Values(length);
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        SparseMap.prototype.clear = function () {
          this.size = 0;
        };

        /**
         * Method used to check the existence of a member in the set.
         *
         * @param  {number} member - Member to test.
         * @return {SparseMap}
         */
        SparseMap.prototype.has = function (member) {
          var index = this.sparse[member];
          return index < this.size && this.dense[index] === member;
        };

        /**
         * Method used to get the value associated to a member in the set.
         *
         * @param  {number} member - Member to test.
         * @return {any}
         */
        SparseMap.prototype.get = function (member) {
          var index = this.sparse[member];
          if (index < this.size && this.dense[index] === member) return this.vals[index];
          return;
        };

        /**
         * Method used to set a value into the map.
         *
         * @param  {number} member - Member to set.
         * @param  {any}    value  - Associated value.
         * @return {SparseMap}
         */
        SparseMap.prototype.set = function (member, value) {
          var index = this.sparse[member];
          if (index < this.size && this.dense[index] === member) {
            this.vals[index] = value;
            return this;
          }
          this.dense[this.size] = member;
          this.sparse[member] = this.size;
          this.vals[this.size] = value;
          this.size++;
          return this;
        };

        /**
         * Method used to remove a member from the set.
         *
         * @param  {number} member - Member to delete.
         * @return {boolean}
         */
        SparseMap.prototype.delete = function (member) {
          var index = this.sparse[member];
          if (index >= this.size || this.dense[index] !== member) return false;
          index = this.dense[this.size - 1];
          this.dense[this.sparse[member]] = index;
          this.sparse[index] = this.sparse[member];
          this.size--;
          return true;
        };

        /**
         * Method used to iterate over the set's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        SparseMap.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          for (var i = 0; i < this.size; i++) callback.call(scope, this.vals[i], this.dense[i]);
        };

        /**
         * Method used to create an iterator over a set's members.
         *
         * @return {Iterator}
         */
        SparseMap.prototype.keys = function () {
          var size = this.size,
            dense = this.dense,
            i = 0;
          return new Iterator(function () {
            if (i < size) {
              var item = dense[i];
              i++;
              return {
                value: item
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Method used to create an iterator over a set's values.
         *
         * @return {Iterator}
         */
        SparseMap.prototype.values = function () {
          var size = this.size,
            values = this.vals,
            i = 0;
          return new Iterator(function () {
            if (i < size) {
              var item = values[i];
              i++;
              return {
                value: item
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Method used to create an iterator over a set's entries.
         *
         * @return {Iterator}
         */
        SparseMap.prototype.entries = function () {
          var size = this.size,
            dense = this.dense,
            values = this.vals,
            i = 0;
          return new Iterator(function () {
            if (i < size) {
              var item = [dense[i], values[i]];
              i++;
              return {
                value: item
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') SparseMap.prototype[Symbol.iterator] = SparseMap.prototype.entries;

        /**
         * Convenience known methods.
         */
        SparseMap.prototype.inspect = function () {
          var proxy = new Map();
          for (var i = 0; i < this.size; i++) proxy.set(this.dense[i], this.vals[i]);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: SparseMap,
            enumerable: false
          });
          proxy.length = this.length;
          if (this.vals.constructor !== Array) proxy.type = this.vals.constructor.name;
          return proxy;
        };
        if (typeof Symbol !== 'undefined') SparseMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = SparseMap.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = SparseMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/typed-arrays.js': __cjsMetaURL$5
        };
      });

      // I am the facade module who provides access to the CommonJS module './sparse-map.js'~
      if (!__cjsMetaURL$J) {
        loader.throwInvalidWrapper('./sparse-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$J);
      var __cjsMetaURL$K = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-set.js';
      loader.define(__cjsMetaURL$K, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist SparseSet
         * ====================
         *
         * JavaScript sparse set implemented on top of byte arrays.
         *
         * [Reference]: https://research.swtch.com/sparse
         */
        var Iterator = require('obliterator/iterator'),
          getPointerArray = require('./utils/typed-arrays.js').getPointerArray;

        /**
         * SparseSet.
         *
         * @constructor
         */
        function SparseSet(length) {
          var ByteArray = getPointerArray(length);

          // Properties
          this.size = 0;
          this.length = length;
          this.dense = new ByteArray(length);
          this.sparse = new ByteArray(length);
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        SparseSet.prototype.clear = function () {
          this.size = 0;
        };

        /**
         * Method used to check the existence of a member in the set.
         *
         * @param  {number} member - Member to test.
         * @return {SparseSet}
         */
        SparseSet.prototype.has = function (member) {
          var index = this.sparse[member];
          return index < this.size && this.dense[index] === member;
        };

        /**
         * Method used to add a member to the set.
         *
         * @param  {number} member - Member to add.
         * @return {SparseSet}
         */
        SparseSet.prototype.add = function (member) {
          var index = this.sparse[member];
          if (index < this.size && this.dense[index] === member) return this;
          this.dense[this.size] = member;
          this.sparse[member] = this.size;
          this.size++;
          return this;
        };

        /**
         * Method used to remove a member from the set.
         *
         * @param  {number} member - Member to delete.
         * @return {boolean}
         */
        SparseSet.prototype.delete = function (member) {
          var index = this.sparse[member];
          if (index >= this.size || this.dense[index] !== member) return false;
          index = this.dense[this.size - 1];
          this.dense[this.sparse[member]] = index;
          this.sparse[index] = this.sparse[member];
          this.size--;
          return true;
        };

        /**
         * Method used to iterate over the set's values.
         *
         * @param  {function}  callback - Function to call for each item.
         * @param  {object}    scope    - Optional scope.
         * @return {undefined}
         */
        SparseSet.prototype.forEach = function (callback, scope) {
          scope = arguments.length > 1 ? scope : this;
          var item;
          for (var i = 0; i < this.size; i++) {
            item = this.dense[i];
            callback.call(scope, item, item);
          }
        };

        /**
         * Method used to create an iterator over a set's values.
         *
         * @return {Iterator}
         */
        SparseSet.prototype.values = function () {
          var size = this.size,
            dense = this.dense,
            i = 0;
          return new Iterator(function () {
            if (i < size) {
              var item = dense[i];
              i++;
              return {
                value: item
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Attaching the #.values method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') SparseSet.prototype[Symbol.iterator] = SparseSet.prototype.values;

        /**
         * Convenience known methods.
         */
        SparseSet.prototype.inspect = function () {
          var proxy = new Set();
          for (var i = 0; i < this.size; i++) proxy.add(this.dense[i]);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: SparseSet,
            enumerable: false
          });
          proxy.length = this.length;
          return proxy;
        };
        if (typeof Symbol !== 'undefined') SparseSet.prototype[Symbol.for('nodejs.util.inspect.custom')] = SparseSet.prototype.inspect;

        /**
         * Exporting.
         */
        module.exports = SparseSet;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/iterator': __cjsMetaURL$9,
          './utils/typed-arrays.js': __cjsMetaURL$5
        };
      });

      // I am the facade module who provides access to the CommonJS module './sparse-set.js'~
      if (!__cjsMetaURL$K) {
        loader.throwInvalidWrapper('./sparse-set.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/sparse-set.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$K);
      var __cjsMetaURL$L = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/symspell.js';
      loader.define(__cjsMetaURL$L, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /* eslint no-loop-func: 0 */
        /**
         * Mnemonist SymSpell
         * ===================
         *
         * JavaScript implementation of the Symmetric Delete Spelling dictionary to
         * efficiently index & query expression based on edit distance.
         * Note that the current implementation target the v3.0 of the algorithm.
         *
         * [Reference]:
         * http://blog.faroo.com/2012/06/07/improved-edit-distance-based-spelling-correction/
         * https://github.com/wolfgarbe/symspell
         *
         * [Author]:
         * Wolf Garbe
         */
        var forEach = require('obliterator/foreach');

        /**
         * Constants.
         */
        var DEFAULT_MAX_DISTANCE = 2,
          DEFAULT_VERBOSITY = 2;
        var VERBOSITY = new Set([
        // Returns only the top suggestion
        0,
        // Returns suggestions with the smallest edit distance
        1,
        // Returns every suggestion (no early termination)
        2]);
        var VERBOSITY_EXPLANATIONS = {
          0: 'Returns only the top suggestion',
          1: 'Returns suggestions with the smallest edit distance',
          2: 'Returns every suggestion (no early termination)'
        };

        /**
         * Functions.
         */

        /**
         * Function creating a dictionary item.
         *
         * @param  {number} [value] - An optional suggestion.
         * @return {object}         - The created item.
         */
        function createDictionaryItem(value) {
          var suggestions = new Set();
          if (typeof value === 'number') suggestions.add(value);
          return {
            suggestions: suggestions,
            count: 0
          };
        }

        /**
         * Function creating a suggestion item.
         *
         * @return {object} - The created item.
         */
        function createSuggestionItem(term, distance, count) {
          return {
            term: term || '',
            distance: distance || 0,
            count: count || 0
          };
        }

        /**
         * Simplified edit function.
         *
         * @param {string} word      - Target word.
         * @param {number} distance  - Distance.
         * @param {number} max       - Max distance.
         * @param {Set}    [deletes] - Set mutated to store deletes.
         */
        function edits(word, distance, max, deletes) {
          deletes = deletes || new Set();
          distance++;
          var deletedItem,
            l = word.length,
            i;
          if (l > 1) {
            for (i = 0; i < l; i++) {
              deletedItem = word.substring(0, i) + word.substring(i + 1);
              if (!deletes.has(deletedItem)) {
                deletes.add(deletedItem);
                if (distance < max) edits(deletedItem, distance, max, deletes);
              }
            }
          }
          return deletes;
        }

        /**
         * Function used to conditionally add suggestions.
         *
         * @param {array}  words       - Words list.
         * @param {number} verbosity   - Verbosity level.
         * @param {object} item        - The target item.
         * @param {string} suggestion  - The target suggestion.
         * @param {number} int         - Integer key of the word.
         * @param {object} deletedItem - Considered deleted item.
         * @param {SymSpell}
         */
        function addLowestDistance(words, verbosity, item, suggestion, int, deletedItem) {
          var first = item.suggestions.values().next().value;
          if (verbosity < 2 && item.suggestions.size > 0 && words[first].length - deletedItem.length > suggestion.length - deletedItem.length) {
            item.suggestions = new Set();
            item.count = 0;
          }
          if (verbosity === 2 || !item.suggestions.size || words[first].length - deletedItem.length >= suggestion.length - deletedItem.length) {
            item.suggestions.add(int);
          }
        }

        /**
         * Custom Damerau-Levenshtein used by the algorithm.
         *
         * @param  {string} source - First string.
         * @param  {string} target - Second string.
         * @return {number}        - The distance.
         */
        function damerauLevenshtein(source, target) {
          var m = source.length,
            n = target.length,
            H = [[]],
            INF = m + n,
            sd = new Map(),
            i,
            l,
            j;
          H[0][0] = INF;
          for (i = 0; i <= m; i++) {
            if (!H[i + 1]) H[i + 1] = [];
            H[i + 1][1] = i;
            H[i + 1][0] = INF;
          }
          for (j = 0; j <= n; j++) {
            H[1][j + 1] = j;
            H[0][j + 1] = INF;
          }
          var st = source + target,
            letter;
          for (i = 0, l = st.length; i < l; i++) {
            letter = st[i];
            if (!sd.has(letter)) sd.set(letter, 0);
          }

          // Iterating
          for (i = 1; i <= m; i++) {
            var DB = 0;
            for (j = 1; j <= n; j++) {
              var i1 = sd.get(target[j - 1]),
                j1 = DB;
              if (source[i - 1] === target[j - 1]) {
                H[i + 1][j + 1] = H[i][j];
                DB = j;
              } else {
                H[i + 1][j + 1] = Math.min(H[i][j], H[i + 1][j], H[i][j + 1]) + 1;
              }
              H[i + 1][j + 1] = Math.min(H[i + 1][j + 1], H[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1));
            }
            sd.set(source[i - 1], i);
          }
          return H[m + 1][n + 1];
        }

        /**
         * Lookup function.
         *
         * @param  {object} dictionary  - A SymSpell dictionary.
         * @param  {array}  words       - Unique words list.
         * @param  {number} verbosity   - Verbosity level.
         * @param  {number} maxDistance - Maximum distance.
         * @param  {number} maxLength   - Maximum word length in the dictionary.
         * @param  {string} input       - Input string.
         * @return {array}              - The list of suggestions.
         */
        function lookup(dictionary, words, verbosity, maxDistance, maxLength, input) {
          var length = input.length;
          if (length - maxDistance > maxLength) return [];
          var candidates = [input],
            candidateSet = new Set(),
            suggestionSet = new Set();
          var suggestions = [],
            candidate,
            item;

          // Exhausting every candidates
          while (candidates.length > 0) {
            candidate = candidates.shift();

            // Early termination
            if (verbosity < 2 && suggestions.length > 0 && length - candidate.length > suggestions[0].distance) break;
            item = dictionary[candidate];
            if (item !== undefined) {
              if (typeof item === 'number') item = createDictionaryItem(item);
              if (item.count > 0 && !suggestionSet.has(candidate)) {
                suggestionSet.add(candidate);
                var suggestItem = createSuggestionItem(candidate, length - candidate.length, item.count);
                suggestions.push(suggestItem);

                // Another early termination
                if (verbosity < 2 && length - candidate.length === 0) break;
              }

              // Iterating over the item's suggestions
              item.suggestions.forEach(function (index) {
                var suggestion = words[index];

                // Do we already have this suggestion?
                if (suggestionSet.has(suggestion)) return;
                suggestionSet.add(suggestion);

                // Computing distance between candidate & suggestion
                var distance = 0;
                if (input !== suggestion) {
                  if (suggestion.length === candidate.length) {
                    distance = length - candidate.length;
                  } else if (length === candidate.length) {
                    distance = suggestion.length - candidate.length;
                  } else {
                    var ii = 0,
                      jj = 0;
                    var l = suggestion.length;
                    while (ii < l && ii < length && suggestion[ii] === input[ii]) {
                      ii++;
                    }
                    while (jj < l - ii && jj < length && suggestion[l - jj - 1] === input[length - jj - 1]) {
                      jj++;
                    }
                    if (ii > 0 || jj > 0) {
                      distance = damerauLevenshtein(suggestion.substr(ii, l - ii - jj), input.substr(ii, length - ii - jj));
                    } else {
                      distance = damerauLevenshtein(suggestion, input);
                    }
                  }
                }

                // Removing suggestions of higher distance
                if (verbosity < 2 && suggestions.length > 0 && suggestions[0].distance > distance) {
                  suggestions = [];
                }
                if (verbosity < 2 && suggestions.length > 0 && distance > suggestions[0].distance) {
                  return;
                }
                if (distance <= maxDistance) {
                  var target = dictionary[suggestion];
                  if (target !== undefined) {
                    suggestions.push(createSuggestionItem(suggestion, distance, target.count));
                  }
                }
              });
            }

            // Adding edits
            if (length - candidate.length < maxDistance) {
              if (verbosity < 2 && suggestions.length > 0 && length - candidate.length >= suggestions[0].distance) continue;
              for (var i = 0, l = candidate.length; i < l; i++) {
                var deletedItem = candidate.substring(0, i) + candidate.substring(i + 1);
                if (!candidateSet.has(deletedItem)) {
                  candidateSet.add(deletedItem);
                  candidates.push(deletedItem);
                }
              }
            }
          }
          if (verbosity === 0) return suggestions.slice(0, 1);
          return suggestions;
        }

        /**
         * SymSpell.
         *
         * @constructor
         */
        function SymSpell(options) {
          options = options || {};
          this.clear();

          // Properties
          this.maxDistance = typeof options.maxDistance === 'number' ? options.maxDistance : DEFAULT_MAX_DISTANCE;
          this.verbosity = typeof options.verbosity === 'number' ? options.verbosity : DEFAULT_VERBOSITY;

          // Sanity checks
          if (typeof this.maxDistance !== 'number' || this.maxDistance <= 0) throw Error('mnemonist/SymSpell.constructor: invalid `maxDistance` option. Should be a integer greater than 0.');
          if (!VERBOSITY.has(this.verbosity)) throw Error('mnemonist/SymSpell.constructor: invalid `verbosity` option. Should be either 0, 1 or 2.');
        }

        /**
         * Method used to clear the structure.
         *
         * @return {undefined}
         */
        SymSpell.prototype.clear = function () {
          // Properties
          this.size = 0;
          this.dictionary = Object.create(null);
          this.maxLength = 0;
          this.words = [];
        };

        /**
         * Method used to add a word to the index.
         *
         * @param {string} word - Word to add.
         * @param {SymSpell}
         */
        SymSpell.prototype.add = function (word) {
          var _this = this;
          var item = this.dictionary[word];
          if (item !== undefined) {
            if (typeof item === 'number') {
              item = createDictionaryItem(item);
              this.dictionary[word] = item;
            }
            item.count++;
          } else {
            item = createDictionaryItem();
            item.count++;
            this.dictionary[word] = item;
            if (word.length > this.maxLength) this.maxLength = word.length;
          }
          if (item.count === 1) {
            var number = this.words.length;
            this.words.push(word);
            var deletes = edits(word, 0, this.maxDistance);
            deletes.forEach(function (deletedItem) {
              var target = _this.dictionary[deletedItem];
              if (target !== undefined) {
                if (typeof target === 'number') {
                  target = createDictionaryItem(target);
                  _this.dictionary[deletedItem] = target;
                }
                if (!target.suggestions.has(number)) {
                  addLowestDistance(_this.words, _this.verbosity, target, word, number, deletedItem);
                }
              } else {
                _this.dictionary[deletedItem] = number;
              }
            });
          }
          this.size++;
          return this;
        };

        /**
         * Method used to search the index.
         *
         * @param  {string} input - Input query.
         * @return {array}        - The found suggestions.
         */
        SymSpell.prototype.search = function (input) {
          return lookup(this.dictionary, this.words, this.verbosity, this.maxDistance, this.maxLength, input);
        };

        /**
         * Convenience known methods.
         */
        SymSpell.prototype.inspect = function () {
          var array = [];
          array.size = this.size;
          array.maxDistance = this.maxDistance;
          array.verbosity = this.verbosity;
          array.behavior = VERBOSITY_EXPLANATIONS[this.verbosity];
          for (var k in this.dictionary) {
            if (typeof this.dictionary[k] === 'object' && this.dictionary[k].count) array.push([k, this.dictionary[k].count]);
          }

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: SymSpell,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') SymSpell.prototype[Symbol.for('nodejs.util.inspect.custom')] = SymSpell.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a structure.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @return {SymSpell}
         */
        SymSpell.from = function (iterable, options) {
          var index = new SymSpell(options);
          forEach(iterable, function (value) {
            index.add(value);
          });
          return index;
        };

        /**
         * Exporting.
         */
        module.exports = SymSpell;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3
        };
      });

      // I am the facade module who provides access to the CommonJS module './symspell.js'~
      if (!__cjsMetaURL$L) {
        loader.throwInvalidWrapper('./symspell.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/symspell.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$L);
      var __cjsMetaURL$M = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/trie-map.js';
      loader.define(__cjsMetaURL$M, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist TrieMap
         * ==================
         *
         * JavaScript TrieMap implementation based upon plain objects. As such this
         * structure is more a convenience building upon the trie's advantages than
         * a real performant alternative to already existing structures.
         *
         * Note that the Trie is based upon the TrieMap since the underlying machine
         * is the very same. The Trie just does not let you set values and only
         * considers the existence of the given prefixes.
         */
        var forEach = require('obliterator/foreach'),
          Iterator = require('obliterator/iterator');

        /**
         * Constants.
         */
        var SENTINEL = String.fromCharCode(0);

        /**
         * TrieMap.
         *
         * @constructor
         */
        function TrieMap(Token) {
          this.mode = Token === Array ? 'array' : 'string';
          this.clear();
        }

        /**
         * Method used to clear the trie.
         *
         * @return {undefined}
         */
        TrieMap.prototype.clear = function () {
          // Properties
          this.root = {};
          this.size = 0;
        };

        /**
         * Method used to set the value of the given prefix in the trie.
         *
         * @param  {string|array} prefix - Prefix to follow.
         * @param  {any}          value  - Value for the prefix.
         * @return {TrieMap}
         */
        TrieMap.prototype.set = function (prefix, value) {
          var node = this.root,
            token;
          for (var i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token] || (node[token] = {});
          }

          // Do we need to increase size?
          if (!(SENTINEL in node)) this.size++;
          node[SENTINEL] = value;
          return this;
        };

        /**
         * Method used to update the value of the given prefix in the trie.
         *
         * @param  {string|array} prefix - Prefix to follow.
         * @param  {(oldValue: any | undefined) => any} updateFunction - Update value visitor callback.
         * @return {TrieMap}
         */
        TrieMap.prototype.update = function (prefix, updateFunction) {
          var node = this.root,
            token;
          for (var i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token] || (node[token] = {});
          }

          // Do we need to increase size?
          if (!(SENTINEL in node)) this.size++;
          node[SENTINEL] = updateFunction(node[SENTINEL]);
          return this;
        };

        /**
         * Method used to return the value sitting at the end of the given prefix or
         * undefined if none exist.
         *
         * @param  {string|array} prefix - Prefix to follow.
         * @return {any|undefined}
         */
        TrieMap.prototype.get = function (prefix) {
          var node = this.root,
            token,
            i,
            l;
          for (i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token];

            // Prefix does not exist
            if (typeof node === 'undefined') return;
          }
          if (!(SENTINEL in node)) return;
          return node[SENTINEL];
        };

        /**
         * Method used to delete a prefix from the trie.
         *
         * @param  {string|array} prefix - Prefix to delete.
         * @return {boolean}
         */
        TrieMap.prototype.delete = function (prefix) {
          var node = this.root,
            toPrune = null,
            tokenToPrune = null,
            parent,
            token,
            i,
            l;
          for (i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            parent = node;
            node = node[token];

            // Prefix does not exist
            if (typeof node === 'undefined') return false;

            // Keeping track of a potential branch to prune
            if (toPrune !== null) {
              if (Object.keys(node).length > 1) {
                toPrune = null;
                tokenToPrune = null;
              }
            } else {
              if (Object.keys(node).length < 2) {
                toPrune = parent;
                tokenToPrune = token;
              }
            }
          }
          if (!(SENTINEL in node)) return false;
          this.size--;
          if (toPrune) delete toPrune[tokenToPrune];else delete node[SENTINEL];
          return true;
        };

        // TODO: add #.prune?

        /**
         * Method used to assert whether the given prefix exists in the TrieMap.
         *
         * @param  {string|array} prefix - Prefix to check.
         * @return {boolean}
         */
        TrieMap.prototype.has = function (prefix) {
          var node = this.root,
            token;
          for (var i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token];
            if (typeof node === 'undefined') return false;
          }
          return SENTINEL in node;
        };

        /**
         * Method used to retrieve every item in the trie with the given prefix.
         *
         * @param  {string|array} prefix - Prefix to query.
         * @return {array}
         */
        TrieMap.prototype.find = function (prefix) {
          var isString = typeof prefix === 'string';
          var node = this.root,
            matches = [],
            token,
            i,
            l;
          for (i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token];
            if (typeof node === 'undefined') return matches;
          }

          // Performing DFS from prefix
          var nodeStack = [node],
            prefixStack = [prefix],
            k;
          while (nodeStack.length) {
            prefix = prefixStack.pop();
            node = nodeStack.pop();
            for (k in node) {
              if (k === SENTINEL) {
                matches.push([prefix, node[SENTINEL]]);
                continue;
              }
              nodeStack.push(node[k]);
              prefixStack.push(isString ? prefix + k : prefix.concat(k));
            }
          }
          return matches;
        };

        /**
         * Method returning an iterator over the trie's values.
         *
         * @param  {string|array} [prefix] - Optional starting prefix.
         * @return {Iterator}
         */
        TrieMap.prototype.values = function (prefix) {
          var node = this.root,
            nodeStack = [],
            token,
            i,
            l;

          // Resolving initial prefix
          if (prefix) {
            for (i = 0, l = prefix.length; i < l; i++) {
              token = prefix[i];
              node = node[token];

              // If the prefix does not exist, we return an empty iterator
              if (typeof node === 'undefined') return Iterator.empty();
            }
          }
          nodeStack.push(node);
          return new Iterator(function () {
            var currentNode,
              hasValue = false,
              k;
            while (nodeStack.length) {
              currentNode = nodeStack.pop();
              for (k in currentNode) {
                if (k === SENTINEL) {
                  hasValue = true;
                  continue;
                }
                nodeStack.push(currentNode[k]);
              }
              if (hasValue) return {
                done: false,
                value: currentNode[SENTINEL]
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Method returning an iterator over the trie's prefixes.
         *
         * @param  {string|array} [prefix] - Optional starting prefix.
         * @return {Iterator}
         */
        TrieMap.prototype.prefixes = function (prefix) {
          var node = this.root,
            nodeStack = [],
            prefixStack = [],
            token,
            i,
            l;
          var isString = this.mode === 'string';

          // Resolving initial prefix
          if (prefix) {
            for (i = 0, l = prefix.length; i < l; i++) {
              token = prefix[i];
              node = node[token];

              // If the prefix does not exist, we return an empty iterator
              if (typeof node === 'undefined') return Iterator.empty();
            }
          } else {
            prefix = isString ? '' : [];
          }
          nodeStack.push(node);
          prefixStack.push(prefix);
          return new Iterator(function () {
            var currentNode,
              currentPrefix,
              hasValue = false,
              k;
            while (nodeStack.length) {
              currentNode = nodeStack.pop();
              currentPrefix = prefixStack.pop();
              for (k in currentNode) {
                if (k === SENTINEL) {
                  hasValue = true;
                  continue;
                }
                nodeStack.push(currentNode[k]);
                prefixStack.push(isString ? currentPrefix + k : currentPrefix.concat(k));
              }
              if (hasValue) return {
                done: false,
                value: currentPrefix
              };
            }
            return {
              done: true
            };
          });
        };
        TrieMap.prototype.keys = TrieMap.prototype.prefixes;

        /**
         * Method returning an iterator over the trie's entries.
         *
         * @param  {string|array} [prefix] - Optional starting prefix.
         * @return {Iterator}
         */
        TrieMap.prototype.entries = function (prefix) {
          var node = this.root,
            nodeStack = [],
            prefixStack = [],
            token,
            i,
            l;
          var isString = this.mode === 'string';

          // Resolving initial prefix
          if (prefix) {
            for (i = 0, l = prefix.length; i < l; i++) {
              token = prefix[i];
              node = node[token];

              // If the prefix does not exist, we return an empty iterator
              if (typeof node === 'undefined') return Iterator.empty();
            }
          } else {
            prefix = isString ? '' : [];
          }
          nodeStack.push(node);
          prefixStack.push(prefix);
          return new Iterator(function () {
            var currentNode,
              currentPrefix,
              hasValue = false,
              k;
            while (nodeStack.length) {
              currentNode = nodeStack.pop();
              currentPrefix = prefixStack.pop();
              for (k in currentNode) {
                if (k === SENTINEL) {
                  hasValue = true;
                  continue;
                }
                nodeStack.push(currentNode[k]);
                prefixStack.push(isString ? currentPrefix + k : currentPrefix.concat(k));
              }
              if (hasValue) return {
                done: false,
                value: [currentPrefix, currentNode[SENTINEL]]
              };
            }
            return {
              done: true
            };
          });
        };

        /**
         * Attaching the #.entries method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') TrieMap.prototype[Symbol.iterator] = TrieMap.prototype.entries;

        /**
         * Convenience known methods.
         */
        TrieMap.prototype.inspect = function () {
          var proxy = new Array(this.size);
          var iterator = this.entries(),
            step,
            i = 0;
          while (step = iterator.next(), !step.done) proxy[i++] = step.value;

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: TrieMap,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') TrieMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = TrieMap.prototype.inspect;
        TrieMap.prototype.toJSON = function () {
          return this.root;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a trie.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @return {TrieMap}
         */
        TrieMap.from = function (iterable) {
          var trie = new TrieMap();
          forEach(iterable, function (value, key) {
            trie.set(key, value);
          });
          return trie;
        };

        /**
         * Exporting.
         */
        TrieMap.SENTINEL = SENTINEL;
        module.exports = TrieMap;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3,
          'obliterator/iterator': __cjsMetaURL$9
        };
      });
      var __cjsMetaURL$N = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/trie.js';
      loader.define(__cjsMetaURL$N, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Trie
         * ===============
         *
         * JavaScript Trie implementation based upon plain objects. As such this
         * structure is more a convenience building upon the trie's advantages than
         * a real performant alternative to already existing structures.
         *
         * Note that the Trie is based upon the TrieMap since the underlying machine
         * is the very same. The Trie just does not let you set values and only
         * considers the existence of the given prefixes.
         */
        var forEach = require('obliterator/foreach'),
          TrieMap = require('./trie-map.js');

        /**
         * Constants.
         */
        var SENTINEL = String.fromCharCode(0);

        /**
         * Trie.
         *
         * @constructor
         */
        function Trie(Token) {
          this.mode = Token === Array ? 'array' : 'string';
          this.clear();
        }

        // Re-using TrieMap's prototype
        for (var methodName in TrieMap.prototype) Trie.prototype[methodName] = TrieMap.prototype[methodName];

        // Dropping irrelevant methods
        delete Trie.prototype.set;
        delete Trie.prototype.get;
        delete Trie.prototype.values;
        delete Trie.prototype.entries;

        /**
         * Method used to add the given prefix to the trie.
         *
         * @param  {string|array} prefix - Prefix to follow.
         * @return {TrieMap}
         */
        Trie.prototype.add = function (prefix) {
          var node = this.root,
            token;
          for (var i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token] || (node[token] = {});
          }

          // Do we need to increase size?
          if (!(SENTINEL in node)) this.size++;
          node[SENTINEL] = true;
          return this;
        };

        /**
         * Method used to retrieve every item in the trie with the given prefix.
         *
         * @param  {string|array} prefix - Prefix to query.
         * @return {array}
         */
        Trie.prototype.find = function (prefix) {
          var isString = typeof prefix === 'string';
          var node = this.root,
            matches = [],
            token,
            i,
            l;
          for (i = 0, l = prefix.length; i < l; i++) {
            token = prefix[i];
            node = node[token];
            if (typeof node === 'undefined') return matches;
          }

          // Performing DFS from prefix
          var nodeStack = [node],
            prefixStack = [prefix],
            k;
          while (nodeStack.length) {
            prefix = prefixStack.pop();
            node = nodeStack.pop();
            for (k in node) {
              if (k === SENTINEL) {
                matches.push(prefix);
                continue;
              }
              nodeStack.push(node[k]);
              prefixStack.push(isString ? prefix + k : prefix.concat(k));
            }
          }
          return matches;
        };

        /**
         * Attaching the #.keys method to Symbol.iterator if possible.
         */
        if (typeof Symbol !== 'undefined') Trie.prototype[Symbol.iterator] = Trie.prototype.keys;

        /**
         * Convenience known methods.
         */
        Trie.prototype.inspect = function () {
          var proxy = new Set();
          var iterator = this.keys(),
            step;
          while (step = iterator.next(), !step.done) proxy.add(step.value);

          // Trick so that node displays the name of the constructor
          Object.defineProperty(proxy, 'constructor', {
            value: Trie,
            enumerable: false
          });
          return proxy;
        };
        if (typeof Symbol !== 'undefined') Trie.prototype[Symbol.for('nodejs.util.inspect.custom')] = Trie.prototype.inspect;
        Trie.prototype.toJSON = function () {
          return this.root;
        };

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a trie.
         *
         * @param  {Iterable} iterable   - Target iterable.
         * @return {Trie}
         */
        Trie.from = function (iterable) {
          var trie = new Trie();
          forEach(iterable, function (value) {
            trie.add(value);
          });
          return trie;
        };

        /**
         * Exporting.
         */
        Trie.SENTINEL = SENTINEL;
        module.exports = Trie;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          'obliterator/foreach': __cjsMetaURL$3,
          './trie-map.js': __cjsMetaURL$M
        };
      });

      // I am the facade module who provides access to the CommonJS module './trie.js'~
      if (!__cjsMetaURL$N) {
        loader.throwInvalidWrapper('./trie.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/trie.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$N);

      // I am the facade module who provides access to the CommonJS module './trie-map.js'~
      if (!__cjsMetaURL$M) {
        loader.throwInvalidWrapper('./trie-map.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/trie-map.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$M);
      var __cjsMetaURL$O = 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/vp-tree.js';
      loader.define(__cjsMetaURL$O, function (exports, require, module, __filename, __dirname) {
        // #region ORIGINAL CODE

        /**
         * Mnemonist Vantage Point Tree
         * =============================
         *
         * JavaScript implementation of the Vantage Point Tree storing the binary
         * tree as a flat byte array.
         *
         * Note that a VPTree has worst cases and is likely not to be perfectly
         * balanced because of median ambiguity. It is therefore not suitable
         * for hairballs and tiny datasets.
         *
         * [Reference]:
         * https://en.wikipedia.org/wiki/Vantage-point_tree
         */
        var iterables = require('./utils/iterables.js'),
          typed = require('./utils/typed-arrays.js'),
          inplaceQuickSortIndices = require('./sort/quick.js').inplaceQuickSortIndices,
          lowerBoundIndices = require('./utils/binary-search.js').lowerBoundIndices,
          Heap = require('./heap.js');
        var getPointerArray = typed.getPointerArray;

        // TODO: implement vantage point selection techniques (by swapping with last)
        // TODO: is this required to implement early termination for k <= size?

        /**
         * Heap comparator used by the #.nearestNeighbors method.
         */
        function comparator(a, b) {
          if (a.distance < b.distance) return 1;
          if (a.distance > b.distance) return -1;
          return 0;
        }

        /**
         * Function used to create the binary tree.
         *
         * @param  {function}     distance - Distance function to use.
         * @param  {array}        items    - Items to index (will be mutated).
         * @param  {array}        indices  - Indexes of the items.
         * @return {Float64Array}          - The flat binary tree.
         */
        function createBinaryTree(distance, items, indices) {
          var N = indices.length;
          var PointerArray = getPointerArray(N);
          var C = 0,
            nodes = new PointerArray(N),
            lefts = new PointerArray(N),
            rights = new PointerArray(N),
            mus = new Float64Array(N),
            stack = [0, 0, N],
            distances = new Float64Array(N),
            nodeIndex,
            vantagePoint,
            medianIndex,
            lo,
            hi,
            mid,
            mu,
            i,
            l;
          while (stack.length) {
            hi = stack.pop();
            lo = stack.pop();
            nodeIndex = stack.pop();

            // Getting our vantage point
            vantagePoint = indices[hi - 1];
            hi--;
            l = hi - lo;

            // Storing vantage point
            nodes[nodeIndex] = vantagePoint;

            // We are in a leaf
            if (l === 0) continue;

            // We only have two elements, the second one has to go right
            if (l === 1) {
              // We put remaining item to the right
              mu = distance(items[vantagePoint], items[indices[lo]]);
              mus[nodeIndex] = mu;

              // Right
              C++;
              rights[nodeIndex] = C;
              nodes[C] = indices[lo];
              continue;
            }

            // Computing distance from vantage point to other points
            for (i = lo; i < hi; i++) distances[indices[i]] = distance(items[vantagePoint], items[indices[i]]);
            inplaceQuickSortIndices(distances, indices, lo, hi);

            // Finding median of distances
            medianIndex = lo + l / 2 - 1;

            // Need to interpolate?
            if (medianIndex === (medianIndex | 0)) {
              mu = (distances[indices[medianIndex]] + distances[indices[medianIndex + 1]]) / 2;
            } else {
              mu = distances[indices[Math.ceil(medianIndex)]];
            }

            // Storing mu
            mus[nodeIndex] = mu;
            mid = lowerBoundIndices(distances, indices, mu, lo, hi);

            // console.log('Vantage point', items[vantagePoint], vantagePoint);
            // console.log('mu =', mu);
            // console.log('lo =', lo);
            // console.log('hi =', hi);
            // console.log('mid =', mid);

            // console.log('need to split', Array.from(indices).slice(lo, hi).map(i => {
            //   return [distances[i], distance(items[vantagePoint], items[i]), items[i]];
            // }));

            // Right
            if (hi - mid > 0) {
              C++;
              rights[nodeIndex] = C;
              stack.push(C, mid, hi);
              // console.log('Went right with ', Array.from(indices).slice(mid, hi).map(i => {
              //   return [distances[i], distance(items[vantagePoint], items[i]), items[i]];
              // }));
            }

            // Left
            if (mid - lo > 0) {
              C++;
              lefts[nodeIndex] = C;
              stack.push(C, lo, mid);
              // console.log('Went left with', Array.from(indices).slice(lo, mid).map(i => {
              //   return [distances[i], distance(items[vantagePoint], items[i]), items[i]];
              // }));
            }

            // console.log();
          }

          return {
            nodes: nodes,
            lefts: lefts,
            rights: rights,
            mus: mus
          };
        }

        /**
         * VPTree.
         *
         * @constructor
         * @param {function} distance - Distance function to use.
         * @param {Iterable} items    - Items to store.
         */
        function VPTree(distance, items) {
          if (typeof distance !== 'function') throw new Error('mnemonist/VPTree.constructor: given `distance` must be a function.');
          if (!items) throw new Error('mnemonist/VPTree.constructor: you must provide items to the tree. A VPTree cannot be updated after its creation.');

          // Properties
          this.distance = distance;
          this.heap = new Heap(comparator);
          this.D = 0;
          var arrays = iterables.toArrayWithIndices(items);
          this.items = arrays[0];
          var indices = arrays[1];

          // Creating the binary tree
          this.size = indices.length;
          var result = createBinaryTree(distance, this.items, indices);
          this.nodes = result.nodes;
          this.lefts = result.lefts;
          this.rights = result.rights;
          this.mus = result.mus;
        }

        /**
         * Function used to retrieve the k nearest neighbors of the query.
         *
         * @param  {number} k     - Number of neighbors to retrieve.
         * @param  {any}    query - The query.
         * @return {array}
         */
        VPTree.prototype.nearestNeighbors = function (k, query) {
          var neighbors = this.heap,
            stack = [0],
            tau = Infinity,
            nodeIndex,
            itemIndex,
            vantagePoint,
            leftIndex,
            rightIndex,
            mu,
            d;
          this.D = 0;
          while (stack.length) {
            nodeIndex = stack.pop();
            itemIndex = this.nodes[nodeIndex];
            vantagePoint = this.items[itemIndex];

            // Distance between query & the current vantage point
            d = this.distance(vantagePoint, query);
            this.D++;
            if (d < tau) {
              neighbors.push({
                distance: d,
                item: vantagePoint
              });

              // Trimming
              if (neighbors.size > k) neighbors.pop();

              // Adjusting tau (only if we already have k items, else it stays Infinity)
              if (neighbors.size >= k) tau = neighbors.peek().distance;
            }
            leftIndex = this.lefts[nodeIndex];
            rightIndex = this.rights[nodeIndex];

            // We are a leaf
            if (!leftIndex && !rightIndex) continue;
            mu = this.mus[nodeIndex];
            if (d < mu) {
              if (leftIndex && d < mu + tau) stack.push(leftIndex);
              if (rightIndex && d >= mu - tau)
                // Might not be necessary to test d
                stack.push(rightIndex);
            } else {
              if (rightIndex && d >= mu - tau) stack.push(rightIndex);
              if (leftIndex && d < mu + tau)
                // Might not be necessary to test d
                stack.push(leftIndex);
            }
          }
          var array = new Array(neighbors.size);
          for (var i = neighbors.size - 1; i >= 0; i--) array[i] = neighbors.pop();
          return array;
        };

        /**
         * Function used to retrieve every neighbors of query in the given radius.
         *
         * @param  {number} radius - Radius.
         * @param  {any}    query  - The query.
         * @return {array}
         */
        VPTree.prototype.neighbors = function (radius, query) {
          var neighbors = [],
            stack = [0],
            nodeIndex,
            itemIndex,
            vantagePoint,
            leftIndex,
            rightIndex,
            mu,
            d;
          this.D = 0;
          while (stack.length) {
            nodeIndex = stack.pop();
            itemIndex = this.nodes[nodeIndex];
            vantagePoint = this.items[itemIndex];

            // Distance between query & the current vantage point
            d = this.distance(vantagePoint, query);
            this.D++;
            if (d <= radius) neighbors.push({
              distance: d,
              item: vantagePoint
            });
            leftIndex = this.lefts[nodeIndex];
            rightIndex = this.rights[nodeIndex];

            // We are a leaf
            if (!leftIndex && !rightIndex) continue;
            mu = this.mus[nodeIndex];
            if (d < mu) {
              if (leftIndex && d < mu + radius) stack.push(leftIndex);
              if (rightIndex && d >= mu - radius)
                // Might not be necessary to test d
                stack.push(rightIndex);
            } else {
              if (rightIndex && d >= mu - radius) stack.push(rightIndex);
              if (leftIndex && d < mu + radius)
                // Might not be necessary to test d
                stack.push(leftIndex);
            }
          }
          return neighbors;
        };

        /**
         * Convenience known methods.
         */
        VPTree.prototype.inspect = function () {
          var array = this.items.slice();

          // Trick so that node displays the name of the constructor
          Object.defineProperty(array, 'constructor', {
            value: VPTree,
            enumerable: false
          });
          return array;
        };
        if (typeof Symbol !== 'undefined') VPTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = VPTree.prototype.inspect;

        /**
         * Static @.from function taking an arbitrary iterable & converting it into
         * a tree.
         *
         * @param  {Iterable} iterable - Target iterable.
         * @param  {function} distance - Distance function to use.
         * @return {VPTree}
         */
        VPTree.from = function (iterable, distance) {
          return new VPTree(distance, iterable);
        };

        /**
         * Exporting.
         */
        module.exports = VPTree;

        // #endregion ORIGINAL CODE

        module.exports;
      }, function () {
        return {
          './utils/iterables.js': __cjsMetaURL$6,
          './utils/typed-arrays.js': __cjsMetaURL$5,
          './sort/quick.js': __cjsMetaURL$x,
          './utils/binary-search.js': __cjsMetaURL$u,
          './heap.js': __cjsMetaURL$7
        };
      });

      // I am the facade module who provides access to the CommonJS module './vp-tree.js'~
      if (!__cjsMetaURL$O) {
        loader.throwInvalidWrapper('./vp-tree.js', 'file:///C:/Users/dell/Desktop/com_file/code_project/line-rotating/node_modules/.pnpm/mnemonist@0.40.3/node_modules/mnemonist/vp-tree.mjs?cjs=&original=.js');
      }
      loader.require(__cjsMetaURL$O);

      /**
       * Mnemonist Library Endpoint (ESM)
       * =================================
       *
       * Exporting every data structure through a unified endpoint.
       */
      var MinFibonacciHeap = _cjsExports.MinFibonacciHeap;
      var MaxFibonacciHeap = _cjsExports.MaxFibonacciHeap;
      var MinHeap = _cjsExports$1.MinHeap;
      var MaxHeap = _cjsExports$1.MaxHeap;
      var GeneralizedSuffixArray = _cjsExports$2.GeneralizedSuffixArray;
      var Uint8Vector = _cjsExports$3.Uint8Vector;
      var Uint8ClampedVector = _cjsExports$3.Uint8ClampedVector;
      var Int8Vector = _cjsExports$3.Int8Vector;
      var Uint16Vector = _cjsExports$3.Uint16Vector;
      var Int16Vector = _cjsExports$3.Int16Vector;
      var Uint32Vector = _cjsExports$3.Uint32Vector;
      var Int32Vector = _cjsExports$3.Int32Vector;
      var Float32Vector = _cjsExports$3.Float32Vector;
      var Float64Vector = _cjsExports$3.Float64Vector;
      var PointerVector = _cjsExports$3.PointerVector;
      cclegacy._RF.push({}, "5f2b8bZy79DM4K/hjiOfDBJ", "Logger", undefined);

      // 定义日志上下文字典参数接口

      var LogLevels = {
        debug: 0,
        log: 1,
        info: 2,
        warn: 3,
        error: 4
      };
      var LoggerImpl = /*#__PURE__*/function () {
        function LoggerImpl(minLevel, joinSpace) {
          if (minLevel === void 0) {
            minLevel = LogLevels.debug;
          }
          if (joinSpace === void 0) {
            joinSpace = '';
          }
          this.minLevel = LogLevels.debug;
          this._parts = void 0;
          this._formatter = null;
          this.joinSpace = '';
          this.minLevel = minLevel;
          this.joinSpace = joinSpace;
          this._parts = new MinHeap(function (a, b) {
            return a.order - b.order;
          });
          this.refreshFormatter();
        }
        var _proto = LoggerImpl.prototype;
        _proto._log = function _log(level, message, context) {
          var _console;
          // 判断日志级别是否低于最小级别
          var currentLevel = LogLevels[level];
          if (currentLevel < this.minLevel) {
            return;
          }
          // 格式化日志
          var formatted = this._formatter(message, level, context);
          // 输出日志
          for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
            args[_key - 3] = arguments[_key];
          }
          (_console = console)[level].apply(_console, [formatted].concat(args));
        };
        _proto.debug = function debug(message, context) {
          for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
            args[_key2 - 2] = arguments[_key2];
          }
          this._log.apply(this, ['debug', message, context].concat(args));
        };
        _proto.log = function log(message, context) {
          for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
            args[_key3 - 2] = arguments[_key3];
          }
          this._log.apply(this, ['log', message, context].concat(args));
        };
        _proto.info = function info(message, context) {
          for (var _len4 = arguments.length, args = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
            args[_key4 - 2] = arguments[_key4];
          }
          this._log.apply(this, ['info', message, context].concat(args));
        };
        _proto.warn = function warn(message, context) {
          for (var _len5 = arguments.length, args = new Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) {
            args[_key5 - 2] = arguments[_key5];
          }
          this._log.apply(this, ['warn', message, context].concat(args));
        };
        _proto.error = function error(message, context) {
          for (var _len6 = arguments.length, args = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
            args[_key6 - 2] = arguments[_key6];
          }
          this._log.apply(this, ['error', message, context].concat(args));
        }
        /**
         * 注册日志部件
         * @param part 日志部件
         * @param part.order 排序值，越小越靠前，默认为Infinity（放在最后）
         */;
        _proto.registerPart = function registerPart(part) {
          var _part$order;
          part.order = (_part$order = part.order) != null ? _part$order : Infinity;
          this._parts.push(part);
        }

        /**
         * 重新生成格式化函数
         */;
        _proto.refreshFormatter = function refreshFormatter() {
          var _this = this;
          // 提取所有日志部件
          var parts = this._parts.consume();
          // 刷新格式化函数
          this._formatter = function (message, level, context) {
            return (
              // 遍历所有部件，生成日志
              parts.map(function (part) {
                return part.format(message, level, context);
              }).join(_this.joinSpace)
            );
          };
          // 重新注册堆
          for (var _iterator = _createForOfIteratorHelperLoose(parts), _step; !(_step = _iterator()).done;) {
            var _part = _step.value;
            this.registerPart(_part);
          }
        };
        return LoggerImpl;
      }(); // 默认logger实例
      var logger = new LoggerImpl();
      // 逻辑帧
      logger.registerPart({
        format: function format(_message, _level, _context) {
          return "[" + director.getTotalFrames() + "] ";
        },
        order: 1
      });
      // 日志级别
      logger.registerPart({
        format: function format(_message, level, _context) {
          return "[" + level + "] ";
        },
        order: 2
      });
      // 函数名称
      logger.registerPart({
        format: function format(_message, _level, context) {
          var _context$funcName;
          return "[" + ((_context$funcName = context == null ? void 0 : context.funcName) != null ? _context$funcName : '') + "] ";
        },
        order: 3
      });
      // 节点uuid
      logger.registerPart({
        format: function format(_message, _level, context) {
          var _context$nodeUuid;
          return "[" + ((_context$nodeUuid = context == null ? void 0 : context.nodeUuid) != null ? _context$nodeUuid : '') + "] ";
        },
        order: 4
      });
      // 日志信息
      logger.registerPart({
        format: function format(message, _level, _context) {
          return message;
        }
      });
      logger.refreshFormatter();
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "b97535QH79CY5paQ181v9ZC", "TypedEvent", undefined);
      /**
       * 类型安全的事件系统
       * 基于TypeScript类型系统实现编译时检查
       */
      // 事件模式类型树
      /**
       * 创建路径对象的类型
       * 生成一个可用于访问事件路径的对象，提供编译时类型检查和IDE自动补全
       */
      // 底层事件工具
      // 树状事件系统接口
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "4dd08RSD5xKJ6jpMF8nvmoh", "Types", undefined);
      /**
       * 辅助类型：让部分属性变为可选
       */
      /**
       * 辅助类型：排除某些属性
       */
      /**
       * 辅助类型：挑选某些属性
       */
      /**
       * 辅助类型：自由组合属性，先排除，再挑选，最后可选
       * @template T 原始类型
       * @template TnotNeed 必须排除的属性键
       * @template Tneed 必须包含的属性键
       * @template Tdefault 可选属性键
       */
      // 可选属性（仅明确标记可选）
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "4045dNM/w5GV75SY3Hj+h0H", "nanostores", undefined);
      var listenerQueue = [];
      var lqIndex = 0;
      var QUEUE_ITEMS_PER_LISTENER = 4;
      var epoch = 0;

      /* @__NO_SIDE_EFFECTS__ */
      var atom = function atom(initialValue) {
        var listeners = [];
        var $atom = {
          get: function get() {
            if (!$atom.lc) {
              $atom.listen(function () {})();
            }
            return $atom.value;
          },
          lc: 0,
          listen: function listen(listener) {
            $atom.lc = listeners.push(listener);
            return function () {
              for (var i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) {
                if (listenerQueue[i] === listener) {
                  listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
                } else {
                  i += QUEUE_ITEMS_PER_LISTENER;
                }
              }
              var index = listeners.indexOf(listener);
              if (~index) {
                listeners.splice(index, 1);
                if (! --$atom.lc) $atom.off();
              }
            };
          },
          notify: function notify(oldValue, changedKey) {
            epoch++;
            var runListenerQueue = !listenerQueue.length;
            for (var _i = 0, _listeners = listeners; _i < _listeners.length; _i++) {
              var listener = _listeners[_i];
              listenerQueue.push(listener, $atom.value, oldValue, changedKey);
            }
            if (runListenerQueue) {
              for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) {
                listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
              }
              listenerQueue.length = 0;
            }
          },
          /* It will be called on last listener unsubscribing.
          We will redefine it in onMount and onStop. */
          off: function off() {},
          set: function set(newValue) {
            var oldValue = $atom.value;
            if (oldValue !== newValue) {
              $atom.value = newValue;
              $atom.notify(oldValue);
            }
          },
          subscribe: function subscribe(listener) {
            var unbind = $atom.listen(listener);
            listener($atom.value);
            return unbind;
          },
          value: initialValue
        };
        return $atom;
      };
      var MOUNT = 5;
      var UNMOUNT = 6;
      var REVERT_MUTATION = 10;
      var on = function on(object, listener, eventKey, mutateStore) {
        object.events = object.events || {};
        if (!object.events[eventKey + REVERT_MUTATION]) {
          object.events[eventKey + REVERT_MUTATION] = mutateStore(function (eventProps) {
            // eslint-disable-next-line no-sequences
            object.events[eventKey].reduceRight(function (event, l) {
              return l(event), event;
            }, _extends({
              shared: {}
            }, eventProps));
          });
        }
        object.events[eventKey] = object.events[eventKey] || [];
        object.events[eventKey].push(listener);
        return function () {
          var currentListeners = object.events[eventKey];
          var index = currentListeners.indexOf(listener);
          currentListeners.splice(index, 1);
          if (!currentListeners.length) {
            delete object.events[eventKey];
            object.events[eventKey + REVERT_MUTATION]();
            delete object.events[eventKey + REVERT_MUTATION];
          }
        };
      };
      var STORE_UNMOUNT_DELAY = 1000;
      var onMount = function onMount($store, initialize) {
        var listener = function listener(payload) {
          var destroy = initialize(payload);
          if (destroy) $store.events[UNMOUNT].push(destroy);
        };
        return on($store, listener, MOUNT, function (runListeners) {
          var originListen = $store.listen;
          $store.listen = function () {
            if (!$store.lc && !$store.active) {
              $store.active = true;
              runListeners();
            }
            return originListen.apply(void 0, arguments);
          };
          var originOff = $store.off;
          $store.events[UNMOUNT] = [];
          $store.off = function () {
            originOff();
            setTimeout(function () {
              if ($store.active && !$store.lc) {
                $store.active = false;
                for (var _iterator2 = _createForOfIteratorHelperLoose($store.events[UNMOUNT]), _step2; !(_step2 = _iterator2()).done;) {
                  var destroy = _step2.value;
                  destroy();
                }
                $store.events[UNMOUNT] = [];
              }
            }, STORE_UNMOUNT_DELAY);
          };
          return function () {
            $store.listen = originListen;
            $store.off = originOff;
          };
        });
      };
      var computedStore = function computedStore(stores, cb, batched) {
        if (!Array.isArray(stores)) stores = [stores];
        var previousArgs;
        var currentEpoch;
        var set = function set() {
          if (currentEpoch === epoch) return;
          currentEpoch = epoch;
          var args = stores.map(function ($store) {
            return $store.get();
          });
          if (!previousArgs || args.some(function (arg, i) {
            return arg !== previousArgs[i];
          })) {
            previousArgs = args;
            var value = cb.apply(void 0, args);
            if (value && value.then && value.t) {
              value.then(function (asyncValue) {
                if (previousArgs === args) {
                  // Prevent a stale set
                  $computed.set(asyncValue);
                }
              });
            } else {
              $computed.set(value);
              currentEpoch = epoch;
            }
          }
        };
        var $computed = atom(undefined);
        var get = $computed.get;
        $computed.get = function () {
          set();
          return get();
        };
        var timer;
        var run = batched ? function () {
          clearTimeout(timer);
          timer = setTimeout(set);
        } : set;
        onMount($computed, function () {
          var unbinds = stores.map(function ($store) {
            return $store.listen(run);
          });
          set();
          return function () {
            for (var _iterator3 = _createForOfIteratorHelperLoose(unbinds), _step3; !(_step3 = _iterator3()).done;) {
              var unbind = _step3.value;
              unbind();
            }
          };
        });
        return $computed;
      };

      /* @__NO_SIDE_EFFECTS__ */
      var computed = function computed(stores, fn) {
        return computedStore(stores, fn);
      };
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "c001amTC69EbLksC4Fmb39C", "neverthrow", undefined);
      var defaultErrorConfig = {
        withStackTrace: false
      };
      // Custom error object
      // Context / discussion: https://github.com/supermacro/neverthrow/pull/215
      var createNeverThrowError = function createNeverThrowError(message, result, config) {
        if (config === void 0) {
          config = defaultErrorConfig;
        }
        var data = result.isOk() ? {
          type: 'Ok',
          value: result.value
        } : {
          type: 'Err',
          value: result.error
        };
        var maybeStack = config.withStackTrace ? new Error().stack : undefined;
        return {
          data: data,
          message: message,
          stack: maybeStack
        };
      };

      /******************************************************************************
      Copyright (c) Microsoft Corporation.
        Permission to use, copy, modify, and/or distribute this software for any
      purpose with or without fee is hereby granted.
        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
      AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
      LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
      OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
      PERFORMANCE OF THIS SOFTWARE.
      ***************************************************************************** */
      /* global Reflect, Promise, SuppressedError, Symbol, Iterator */

      function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) {
          return value instanceof P ? value : new P(function (resolve) {
            resolve(value);
          });
        }
        return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) {
            try {
              step(generator.next(value));
            } catch (e) {
              reject(e);
            }
          }
          function rejected(value) {
            try {
              step(generator['throw'](value));
            } catch (e) {
              reject(e);
            }
          }
          function step(result) {
            result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
          }
          step((generator = generator.apply(thisArg, [])).next());
        });
      }
      function __values(o) {
        var s = typeof Symbol === 'function' && Symbol.iterator,
          m = s && o[s],
          i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === 'number') return {
          next: function next() {
            if (o && i >= o.length) o = void 0;
            return {
              value: o && o[i++],
              done: !o
            };
          }
        };
        throw new TypeError(s ? 'Object is not iterable.' : 'Symbol.iterator is not defined.');
      }
      function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
      }
      function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator) throw new TypeError('Symbol.asyncIterator is not defined.');
        var g = generator.apply(thisArg, _arguments || []),
          i,
          q = [];
        return i = Object.create((typeof AsyncIterator === 'function' ? AsyncIterator : Object).prototype), verb('next'), verb('throw'), verb('return', awaitReturn), i[Symbol.asyncIterator] = function () {
          return this;
        }, i;
        function awaitReturn(f) {
          return function (v) {
            return Promise.resolve(v).then(f, reject);
          };
        }
        function verb(n, f) {
          if (g[n]) {
            i[n] = function (v) {
              return new Promise(function (a, b) {
                q.push([n, v, a, b]) > 1 || resume(n, v);
              });
            };
            if (f) i[n] = f(i[n]);
          }
        }
        function resume(n, v) {
          try {
            step(g[n](v));
          } catch (e) {
            settle(q[0][3], e);
          }
        }
        function step(r) {
          r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
        }
        function fulfill(value) {
          resume('next', value);
        }
        function reject(value) {
          resume('throw', value);
        }
        function settle(f, v) {
          if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
        }
      }
      function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb('next'), verb('throw', function (e) {
          throw e;
        }), verb('return'), i[Symbol.iterator] = function () {
          return this;
        }, i;
        function verb(n, f) {
          i[n] = o[n] ? function (v) {
            return (p = !p) ? {
              value: __await(o[n](v)),
              done: false
            } : f ? f(v) : v;
          } : f;
        }
      }
      function __asyncValues(o) {
        if (!Symbol.asyncIterator) throw new TypeError('Symbol.asyncIterator is not defined.');
        var m = o[Symbol.asyncIterator],
          i;
        return m ? m.call(o) : (o = typeof __values === 'function' ? __values(o) : o[Symbol.iterator](), i = {}, verb('next'), verb('throw'), verb('return'), i[Symbol.asyncIterator] = function () {
          return this;
        }, i);
        function verb(n) {
          i[n] = o[n] && function (v) {
            return new Promise(function (resolve, reject) {
              v = o[n](v), settle(resolve, reject, v.done, v.value);
            });
          };
        }
        function settle(resolve, reject, d, v) {
          Promise.resolve(v).then(function (v) {
            resolve({
              value: v,
              done: d
            });
          }, reject);
        }
      }
      typeof SuppressedError === 'function' ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = 'SuppressedError', e.error = error, e.suppressed = suppressed, e;
      };
      var ResultAsync = /*#__PURE__*/function (_Symbol$asyncIterator) {
        function ResultAsync(res) {
          this._promise = res;
        }
        ResultAsync.fromSafePromise = function fromSafePromise(promise) {
          var newPromise = promise.then(function (value) {
            return new Ok(value);
          });
          return new ResultAsync(newPromise);
        };
        ResultAsync.fromPromise = function fromPromise(promise, errorFn) {
          var newPromise = promise.then(function (value) {
            return new Ok(value);
          }).catch(function (e) {
            return new Err(errorFn(e));
          });
          return new ResultAsync(newPromise);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ;

        ResultAsync.fromThrowable = function fromThrowable(fn, errorFn) {
          var _this = this;
          return function () {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            return new ResultAsync(function () {
              return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
                return _regeneratorRuntime().wrap(function _callee$(_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      _context.prev = 0;
                      _context.t0 = Ok;
                      _context.next = 4;
                      return fn.apply(void 0, args);
                    case 4:
                      _context.t1 = _context.sent;
                      return _context.abrupt("return", new _context.t0(_context.t1));
                    case 8:
                      _context.prev = 8;
                      _context.t2 = _context["catch"](0);
                      return _context.abrupt("return", new Err(errorFn ? errorFn(_context.t2) : _context.t2));
                    case 11:
                    case "end":
                      return _context.stop();
                  }
                }, _callee, null, [[0, 8]]);
              }));
            }());
          };
        };
        ResultAsync.combine = function combine(asyncResultList) {
          return combineResultAsyncList(asyncResultList);
        };
        ResultAsync.combineWithAllErrors = function combineWithAllErrors(asyncResultList) {
          return combineResultAsyncListWithAllErrors(asyncResultList);
        };
        var _proto = ResultAsync.prototype;
        _proto.map = function map(f) {
          var _this2 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this2, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
              return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) switch (_context2.prev = _context2.next) {
                  case 0:
                    if (!res.isErr()) {
                      _context2.next = 2;
                      break;
                    }
                    return _context2.abrupt("return", new Err(res.error));
                  case 2:
                    _context2.t0 = Ok;
                    _context2.next = 5;
                    return f(res.value);
                  case 5:
                    _context2.t1 = _context2.sent;
                    return _context2.abrupt("return", new _context2.t0(_context2.t1));
                  case 7:
                  case "end":
                    return _context2.stop();
                }
              }, _callee2);
            }));
          }));
        };
        _proto.andThrough = function andThrough(f) {
          var _this3 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
              var newRes;
              return _regeneratorRuntime().wrap(function _callee3$(_context3) {
                while (1) switch (_context3.prev = _context3.next) {
                  case 0:
                    if (!res.isErr()) {
                      _context3.next = 2;
                      break;
                    }
                    return _context3.abrupt("return", new Err(res.error));
                  case 2:
                    _context3.next = 4;
                    return f(res.value);
                  case 4:
                    newRes = _context3.sent;
                    if (!newRes.isErr()) {
                      _context3.next = 7;
                      break;
                    }
                    return _context3.abrupt("return", new Err(newRes.error));
                  case 7:
                    return _context3.abrupt("return", new Ok(res.value));
                  case 8:
                  case "end":
                    return _context3.stop();
                }
              }, _callee3);
            }));
          }));
        };
        _proto.andTee = function andTee(f) {
          var _this4 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this4, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
              return _regeneratorRuntime().wrap(function _callee4$(_context4) {
                while (1) switch (_context4.prev = _context4.next) {
                  case 0:
                    if (!res.isErr()) {
                      _context4.next = 2;
                      break;
                    }
                    return _context4.abrupt("return", new Err(res.error));
                  case 2:
                    _context4.prev = 2;
                    _context4.next = 5;
                    return f(res.value);
                  case 5:
                    _context4.next = 9;
                    break;
                  case 7:
                    _context4.prev = 7;
                    _context4.t0 = _context4["catch"](2);
                  case 9:
                    return _context4.abrupt("return", new Ok(res.value));
                  case 10:
                  case "end":
                    return _context4.stop();
                }
              }, _callee4, null, [[2, 7]]);
            }));
          }));
        };
        _proto.orTee = function orTee(f) {
          var _this5 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this5, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
              return _regeneratorRuntime().wrap(function _callee5$(_context5) {
                while (1) switch (_context5.prev = _context5.next) {
                  case 0:
                    if (!res.isOk()) {
                      _context5.next = 2;
                      break;
                    }
                    return _context5.abrupt("return", new Ok(res.value));
                  case 2:
                    _context5.prev = 2;
                    _context5.next = 5;
                    return f(res.error);
                  case 5:
                    _context5.next = 9;
                    break;
                  case 7:
                    _context5.prev = 7;
                    _context5.t0 = _context5["catch"](2);
                  case 9:
                    return _context5.abrupt("return", new Err(res.error));
                  case 10:
                  case "end":
                    return _context5.stop();
                }
              }, _callee5, null, [[2, 7]]);
            }));
          }));
        };
        _proto.mapErr = function mapErr(f) {
          var _this6 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
              return _regeneratorRuntime().wrap(function _callee6$(_context6) {
                while (1) switch (_context6.prev = _context6.next) {
                  case 0:
                    if (!res.isOk()) {
                      _context6.next = 2;
                      break;
                    }
                    return _context6.abrupt("return", new Ok(res.value));
                  case 2:
                    _context6.t0 = Err;
                    _context6.next = 5;
                    return f(res.error);
                  case 5:
                    _context6.t1 = _context6.sent;
                    return _context6.abrupt("return", new _context6.t0(_context6.t1));
                  case 7:
                  case "end":
                    return _context6.stop();
                }
              }, _callee6);
            }));
          }));
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto.andThen = function andThen(f) {
          return new ResultAsync(this._promise.then(function (res) {
            if (res.isErr()) {
              return new Err(res.error);
            }
            var newValue = f(res.value);
            return newValue instanceof ResultAsync ? newValue._promise : newValue;
          }));
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto.orElse = function orElse(f) {
          var _this7 = this;
          return new ResultAsync(this._promise.then(function (res) {
            return __awaiter(_this7, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
              return _regeneratorRuntime().wrap(function _callee7$(_context7) {
                while (1) switch (_context7.prev = _context7.next) {
                  case 0:
                    if (!res.isErr()) {
                      _context7.next = 2;
                      break;
                    }
                    return _context7.abrupt("return", f(res.error));
                  case 2:
                    return _context7.abrupt("return", new Ok(res.value));
                  case 3:
                  case "end":
                    return _context7.stop();
                }
              }, _callee7);
            }));
          }));
        };
        _proto.match = function match(ok, _err) {
          return this._promise.then(function (res) {
            return res.match(ok, _err);
          });
        };
        _proto.unwrapOr = function unwrapOr(t) {
          return this._promise.then(function (res) {
            return res.unwrapOr(t);
          });
        }
        /**
         * @deprecated will be removed in 9.0.0.
         *
         * You can use `safeTry` without this method.
         * @example
         * ```typescript
         * safeTry(async function* () {
         *   const okValue = yield* yourResult
         * })
         * ```
         * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
         */;
        _proto.safeUnwrap = function safeUnwrap() {
          return __asyncGenerator(this, arguments, /*#__PURE__*/_regeneratorRuntime().mark(function safeUnwrap_1() {
            return _regeneratorRuntime().wrap(function safeUnwrap_1$(_context8) {
              while (1) switch (_context8.prev = _context8.next) {
                case 0:
                  _context8.t0 = __await;
                  _context8.t1 = __await;
                  _context8.t2 = __asyncDelegator;
                  _context8.t3 = __asyncValues;
                  _context8.next = 6;
                  return __await(this._promise.then(function (res) {
                    return res.safeUnwrap();
                  }));
                case 6:
                  _context8.t4 = _context8.sent;
                  _context8.t5 = (0, _context8.t3)(_context8.t4);
                  return _context8.delegateYield((0, _context8.t2)(_context8.t5), "t6", 9);
                case 9:
                  _context8.t7 = _context8.t6;
                  _context8.next = 12;
                  return (0, _context8.t1)(_context8.t7);
                case 12:
                  _context8.t8 = _context8.sent;
                  _context8.next = 15;
                  return (0, _context8.t0)(_context8.t8);
                case 15:
                  return _context8.abrupt("return", _context8.sent);
                case 16:
                case "end":
                  return _context8.stop();
              }
            }, safeUnwrap_1, this);
          }));
        }
        // Makes ResultAsync implement PromiseLike<Result>
        ;

        _proto.then = function then(successCallback, failureCallback) {
          return this._promise.then(successCallback, failureCallback);
        };
        _proto[_Symbol$asyncIterator] = function () {
          return __asyncGenerator(this, arguments, /*#__PURE__*/_regeneratorRuntime().mark(function _a() {
            var result;
            return _regeneratorRuntime().wrap(function _a$(_context9) {
              while (1) switch (_context9.prev = _context9.next) {
                case 0:
                  _context9.next = 2;
                  return __await(this._promise);
                case 2:
                  result = _context9.sent;
                  if (!result.isErr()) {
                    _context9.next = 8;
                    break;
                  }
                  _context9.next = 6;
                  return __await(errAsync(result.error));
                case 6:
                  _context9.next = 8;
                  return _context9.sent;
                case 8:
                  _context9.next = 10;
                  return __await(result.value);
                case 10:
                  return _context9.abrupt("return", _context9.sent);
                case 11:
                case "end":
                  return _context9.stop();
              }
            }, _a, this);
          }));
        };
        return ResultAsync;
      }(Symbol.asyncIterator);
      function errAsync(err) {
        return new ResultAsync(Promise.resolve(new Err(err)));
      }

      /**
       * Short circuits on the FIRST Err value that we find
       */
      var combineResultList = function combineResultList(resultList) {
        var acc = ok([]);
        var _loop = function _loop() {
          var result = _step.value;
          if (result.isErr()) {
            acc = err(result.error);
            return 1; // break
          } else {
            acc.map(function (list) {
              return list.push(result.value);
            });
          }
        };
        for (var _iterator = _createForOfIteratorHelperLoose(resultList), _step; !(_step = _iterator()).done;) {
          if (_loop()) break;
        }
        return acc;
      };
      /* This is the typesafe version of Promise.all
       *
       * Takes a list of ResultAsync<T, E> and success if all inner results are Ok values
       * or fails if one (or more) of the inner results are Err values
       */
      var combineResultAsyncList = function combineResultAsyncList(asyncResultList) {
        return ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
      };
      /**
       * Give a list of all the errors we find
       */
      var combineResultListWithAllErrors = function combineResultListWithAllErrors(resultList) {
        var acc = ok([]);
        for (var _iterator2 = _createForOfIteratorHelperLoose(resultList), _step2; !(_step2 = _iterator2()).done;) {
          var result = _step2.value;
          if (result.isErr() && acc.isErr()) {
            acc.error.push(result.error);
          } else if (result.isErr() && acc.isOk()) {
            acc = err([result.error]);
          } else if (result.isOk() && acc.isOk()) {
            acc.value.push(result.value);
          }
          // do nothing when result.isOk() && acc.isErr()
        }

        return acc;
      };
      var combineResultAsyncListWithAllErrors = function combineResultAsyncListWithAllErrors(asyncResultList) {
        return ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
      };

      // eslint-disable-next-line @typescript-eslint/no-namespace
      var Result;
      (function (Result) {
        /**
         * Wraps a function with a try catch, creating a new function with the same
         * arguments but returning `Ok` if successful, `Err` if the function throws
         *
         * @param fn function to wrap with ok on success or err on failure
         * @param errorFn when an error is thrown, this will wrap the error result if provided
         */
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        function fromThrowable(fn, errorFn) {
          return function () {
            try {
              var result = fn.apply(void 0, arguments);
              return ok(result);
            } catch (e) {
              return err(errorFn ? errorFn(e) : e);
            }
          };
        }
        Result.fromThrowable = fromThrowable;
        function combine(resultList) {
          return combineResultList(resultList);
        }
        Result.combine = combine;
        function combineWithAllErrors(resultList) {
          return combineResultListWithAllErrors(resultList);
        }
        Result.combineWithAllErrors = combineWithAllErrors;
      })(Result || (Result = {}));
      function ok(value) {
        return new Ok(value);
      }
      function err(err) {
        return new Err(err);
      }
      var Ok = /*#__PURE__*/function (_Symbol$iterator) {
        function Ok(value) {
          this.value = value;
        }
        var _proto2 = Ok.prototype;
        _proto2.isOk = function isOk() {
          return true;
        };
        _proto2.isErr = function isErr() {
          return !this.isOk();
        };
        _proto2.map = function map(f) {
          return ok(f(this.value));
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto2.mapErr = function mapErr(_f) {
          return ok(this.value);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto2.andThen = function andThen(f) {
          return f(this.value);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto2.andThrough = function andThrough(f) {
          var _this8 = this;
          return f(this.value).map(function (_value) {
            return _this8.value;
          });
        };
        _proto2.andTee = function andTee(f) {
          try {
            f(this.value);
          } catch (e) {
            // Tee doesn't care about the error
          }
          return ok(this.value);
        };
        _proto2.orTee = function orTee(_f) {
          return ok(this.value);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto2.orElse = function orElse(_f) {
          return ok(this.value);
        };
        _proto2.asyncAndThen = function asyncAndThen(f) {
          return f(this.value);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto2.asyncAndThrough = function asyncAndThrough(f) {
          var _this9 = this;
          return f(this.value).map(function () {
            return _this9.value;
          });
        };
        _proto2.asyncMap = function asyncMap(f) {
          return ResultAsync.fromSafePromise(f(this.value));
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto2.unwrapOr = function unwrapOr(_v) {
          return this.value;
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto2.match = function match(ok, _err) {
          return ok(this.value);
        };
        _proto2.safeUnwrap = function safeUnwrap() {
          var value = this.value;
          /* eslint-disable-next-line require-yield */
          return /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
            return _regeneratorRuntime().wrap(function _callee8$(_context10) {
              while (1) switch (_context10.prev = _context10.next) {
                case 0:
                  return _context10.abrupt("return", value);
                case 1:
                case "end":
                  return _context10.stop();
              }
            }, _callee8);
          })();
        };
        _proto2._unsafeUnwrap = function _unsafeUnwrap(_) {
          return this.value;
        };
        _proto2._unsafeUnwrapErr = function _unsafeUnwrapErr(config) {
          throw createNeverThrowError('Called `_unsafeUnwrapErr` on an Ok', this, config);
        }
        // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
        ;

        _proto2[_Symbol$iterator] = /*#__PURE__*/
        _regeneratorRuntime().mark(function _callee9() {
          return _regeneratorRuntime().wrap(function _callee9$(_context11) {
            while (1) switch (_context11.prev = _context11.next) {
              case 0:
                return _context11.abrupt("return", this.value);
              case 1:
              case "end":
                return _context11.stop();
            }
          }, _callee9, this);
        });
        return Ok;
      }(Symbol.iterator);
      var Err = /*#__PURE__*/function (_Symbol$iterator2) {
        function Err(error) {
          this.error = error;
        }
        var _proto3 = Err.prototype;
        _proto3.isOk = function isOk() {
          return false;
        };
        _proto3.isErr = function isErr() {
          return !this.isOk();
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto3.map = function map(_f) {
          return err(this.error);
        };
        _proto3.mapErr = function mapErr(f) {
          return err(f(this.error));
        };
        _proto3.andThrough = function andThrough(_f) {
          return err(this.error);
        };
        _proto3.andTee = function andTee(_f) {
          return err(this.error);
        };
        _proto3.orTee = function orTee(f) {
          try {
            f(this.error);
          } catch (e) {
            // Tee doesn't care about the error
          }
          return err(this.error);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto3.andThen = function andThen(_f) {
          return err(this.error);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
        ;

        _proto3.orElse = function orElse(f) {
          return f(this.error);
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto3.asyncAndThen = function asyncAndThen(_f) {
          return errAsync(this.error);
        };
        _proto3.asyncAndThrough = function asyncAndThrough(_f) {
          return errAsync(this.error);
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;

        _proto3.asyncMap = function asyncMap(_f) {
          return errAsync(this.error);
        };
        _proto3.unwrapOr = function unwrapOr(v) {
          return v;
        };
        _proto3.match = function match(_ok, err) {
          return err(this.error);
        };
        _proto3.safeUnwrap = function safeUnwrap() {
          var error = this.error;
          return /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
            return _regeneratorRuntime().wrap(function _callee10$(_context12) {
              while (1) switch (_context12.prev = _context12.next) {
                case 0:
                  _context12.next = 2;
                  return err(error);
                case 2:
                  throw new Error('Do not use this generator out of `safeTry`');
                case 3:
                case "end":
                  return _context12.stop();
              }
            }, _callee10);
          })();
        };
        _proto3._unsafeUnwrap = function _unsafeUnwrap(config) {
          throw createNeverThrowError('Called `_unsafeUnwrap` on an Err', this, config);
        };
        _proto3._unsafeUnwrapErr = function _unsafeUnwrapErr(_) {
          return this.error;
        };
        _proto3[_Symbol$iterator2] = /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
          var self;
          return _regeneratorRuntime().wrap(function _callee11$(_context13) {
            while (1) switch (_context13.prev = _context13.next) {
              case 0:
                // eslint-disable-next-line @typescript-eslint/no-this-alias
                self = this; // @ts-expect-error -- This is structurally equivalent and safe
                _context13.next = 3;
                return self;
              case 3:
                return _context13.abrupt("return", self);
              case 4:
              case "end":
                return _context13.stop();
            }
          }, _callee11, this);
        });
        return Err;
      }(Symbol.iterator);
      var fromThrowable = Result.fromThrowable;
      cclegacy._RF.pop();
      var _excluded = ["_nodes", "tags", "machine", "getMeta", "toJSON", "can", "hasTag", "matches"],
        _excluded2 = ["_nodes", "tags", "machine", "children", "context", "can", "hasTag", "matches", "getMeta", "toJSON"],
        _excluded5 = ["onDone", "onError"];
      cclegacy._RF.push({}, "76694fUc31OhpTYh6kQuX6/", "xstate", undefined);
      // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
      function getGlobal() {
        if (typeof globalThis !== 'undefined') {
          return globalThis;
        }
        if (typeof self !== 'undefined') {
          return self;
        }
        if (typeof window !== 'undefined') {
          return window;
        }
        if (typeof global !== 'undefined') {
          return global;
        }
      }
      function getDevTools() {
        var w = getGlobal();
        if (w.__xstate__) {
          return w.__xstate__;
        }
        return undefined;
      }
      var devToolsAdapter = function devToolsAdapter(service) {
        if (typeof window === 'undefined') {
          return;
        }
        var devTools = getDevTools();
        if (devTools) {
          devTools.register(service);
        }
      };
      var Mailbox = /*#__PURE__*/function () {
        function Mailbox(_process) {
          this._process = _process;
          this._active = false;
          this._current = null;
          this._last = null;
        }
        var _proto = Mailbox.prototype;
        _proto.start = function start() {
          this._active = true;
          this.flush();
        };
        _proto.clear = function clear() {
          // we can't set _current to null because we might be currently processing
          // and enqueue following clear shouldn't start processing the enqueued item immediately
          if (this._current) {
            this._current.next = null;
            this._last = this._current;
          }
        };
        _proto.enqueue = function enqueue(event) {
          var enqueued = {
            value: event,
            next: null
          };
          if (this._current) {
            this._last.next = enqueued;
            this._last = enqueued;
            return;
          }
          this._current = enqueued;
          this._last = enqueued;
          if (this._active) {
            this.flush();
          }
        };
        _proto.flush = function flush() {
          while (this._current) {
            // atm the given _process is responsible for implementing proper try/catch handling
            // we assume here that this won't throw in a way that can affect this mailbox
            var consumed = this._current;
            this._process(consumed.value);
            this._current = consumed.next;
          }
          this._last = null;
        };
        return Mailbox;
      }();
      var STATE_DELIMITER = '.';
      var TARGETLESS_KEY = '';
      var NULL_EVENT = '';
      var STATE_IDENTIFIER$1 = '#';
      var WILDCARD = '*';
      var XSTATE_INIT = 'xstate.init';
      var XSTATE_ERROR = 'xstate.error';
      var XSTATE_STOP = 'xstate.stop';

      /**
       * Returns an event that represents an implicit event that is sent after the
       * specified `delay`.
       *
       * @param delayRef The delay in milliseconds
       * @param id The state node ID where this event is handled
       */
      function createAfterEvent(delayRef, id) {
        return {
          type: "xstate.after." + delayRef + "." + id
        };
      }

      /**
       * Returns an event that represents that a final state node has been reached in
       * the parent state node.
       *
       * @param id The final state node's parent state node `id`
       * @param output The data to pass into the event
       */
      function createDoneStateEvent(id, output) {
        return {
          type: "xstate.done.state." + id,
          output: output
        };
      }

      /**
       * Returns an event that represents that an invoked service has terminated.
       *
       * An invoked service is terminated when it has reached a top-level final state
       * node, but not when it is canceled.
       *
       * @param invokeId The invoked service ID
       * @param output The data to pass into the event
       */
      function createDoneActorEvent(invokeId, output) {
        return {
          type: "xstate.done.actor." + invokeId,
          output: output,
          actorId: invokeId
        };
      }
      function createErrorActorEvent(id, error) {
        return {
          type: "xstate.error.actor." + id,
          error: error,
          actorId: id
        };
      }
      function createInitEvent(input) {
        return {
          type: XSTATE_INIT,
          input: input
        };
      }

      /**
       * This function makes sure that unhandled errors are thrown in a separate
       * macrotask. It allows those errors to be detected by global error handlers and
       * reported to bug tracking services without interrupting our own stack of
       * execution.
       *
       * @param err Error to be thrown
       */
      function reportUnhandledError(err) {
        setTimeout(function () {
          throw err;
        });
      }
      var symbolObservable = function () {
        return typeof Symbol === 'function' && Symbol.observable || '@@observable';
      }();
      function matchesState(parentStateId, childStateId) {
        var parentStateValue = toStateValue(parentStateId);
        var childStateValue = toStateValue(childStateId);
        if (typeof childStateValue === 'string') {
          if (typeof parentStateValue === 'string') {
            return childStateValue === parentStateValue;
          }

          // Parent more specific than child
          return false;
        }
        if (typeof parentStateValue === 'string') {
          return parentStateValue in childStateValue;
        }
        return Object.keys(parentStateValue).every(function (key) {
          if (!(key in childStateValue)) {
            return false;
          }
          return matchesState(parentStateValue[key], childStateValue[key]);
        });
      }
      function toStatePath(stateId) {
        if (isArray(stateId)) {
          return stateId;
        }
        var result = [];
        var segment = '';
        for (var i = 0; i < stateId.length; i++) {
          var char = stateId.charCodeAt(i);
          switch (char) {
            // \
            case 92:
              // consume the next character
              segment += stateId[i + 1];
              // and skip over it
              i++;
              continue;
            // .
            case 46:
              result.push(segment);
              segment = '';
              continue;
          }
          segment += stateId[i];
        }
        result.push(segment);
        return result;
      }
      function toStateValue(stateValue) {
        if (isMachineSnapshot(stateValue)) {
          return stateValue.value;
        }
        if (typeof stateValue !== 'string') {
          return stateValue;
        }
        var statePath = toStatePath(stateValue);
        return pathToStateValue(statePath);
      }
      function pathToStateValue(statePath) {
        if (statePath.length === 1) {
          return statePath[0];
        }
        var value = {};
        var marker = value;
        for (var i = 0; i < statePath.length - 1; i++) {
          if (i === statePath.length - 2) {
            marker[statePath[i]] = statePath[i + 1];
          } else {
            var previous = marker;
            marker = {};
            previous[statePath[i]] = marker;
          }
        }
        return value;
      }
      function mapValues(collection, iteratee) {
        var result = {};
        var collectionKeys = Object.keys(collection);
        for (var i = 0; i < collectionKeys.length; i++) {
          var key = collectionKeys[i];
          result[key] = iteratee(collection[key], key, collection, i);
        }
        return result;
      }
      function toArrayStrict(value) {
        if (isArray(value)) {
          return value;
        }
        return [value];
      }
      function toArray(value) {
        if (value === undefined) {
          return [];
        }
        return toArrayStrict(value);
      }
      function resolveOutput(mapper, context, event, self) {
        if (typeof mapper === 'function') {
          return mapper({
            context: context,
            event: event,
            self: self
          });
        }
        return mapper;
      }
      function isArray(value) {
        return Array.isArray(value);
      }
      function isErrorActorEvent(event) {
        return event.type.startsWith('xstate.error.actor');
      }
      function toTransitionConfigArray(configLike) {
        return toArrayStrict(configLike).map(function (transitionLike) {
          if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
            return {
              target: transitionLike
            };
          }
          return transitionLike;
        });
      }
      function normalizeTarget(target) {
        if (target === undefined || target === TARGETLESS_KEY) {
          return undefined;
        }
        return toArray(target);
      }
      function toObserver(nextHandler, errorHandler, completionHandler) {
        var _ref, _ref2, _ref3;
        var isObserver = typeof nextHandler === 'object';
        var self = isObserver ? nextHandler : undefined;
        return {
          next: (_ref = isObserver ? nextHandler.next : nextHandler) == null ? void 0 : _ref.bind(self),
          error: (_ref2 = isObserver ? nextHandler.error : errorHandler) == null ? void 0 : _ref2.bind(self),
          complete: (_ref3 = isObserver ? nextHandler.complete : completionHandler) == null ? void 0 : _ref3.bind(self)
        };
      }
      function createInvokeId(stateNodeId, index) {
        return index + "." + stateNodeId;
      }
      function resolveReferencedActor(machine, src) {
        var match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
        if (!match) {
          return machine.implementations.actors[src];
        }
        var indexStr = match[1],
          nodeId = match[2];
        var node = machine.getStateNodeById(nodeId);
        var invokeConfig = node.config.invoke;
        return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
      }

      /**
       * Checks if an event type matches an event descriptor, supporting wildcards.
       * Event descriptors can be:
       *
       * - Exact matches: "event.type"
       * - Wildcard: "*"
       * - Partial matches: "event.*"
       *
       * @param eventType - The actual event type string
       * @param descriptor - The event descriptor to match against
       * @returns True if the event type matches the descriptor
       */
      function matchesEventDescriptor(eventType, descriptor) {
        if (descriptor === eventType) {
          return true;
        }
        if (descriptor === WILDCARD) {
          return true;
        }
        if (!descriptor.endsWith('.*')) {
          return false;
        }
        var partialEventTokens = descriptor.split('.');
        var eventTokens = eventType.split('.');
        for (var tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
          var partialEventToken = partialEventTokens[tokenIndex];
          var eventToken = eventTokens[tokenIndex];
          if (partialEventToken === '*') {
            var isLastToken = tokenIndex === partialEventTokens.length - 1;
            return isLastToken;
          }
          if (partialEventToken !== eventToken) {
            return false;
          }
        }
        return true;
      }
      function createScheduledEventId(actorRef, id) {
        return actorRef.sessionId + "." + id;
      }
      var idCounter = 0;
      function createSystem(rootActor, options) {
        var _ref4;
        var children = new Map();
        var keyedActors = new Map();
        var reverseKeyedActors = new WeakMap();
        var inspectionObservers = new Set();
        var timerMap = {};
        var clock = options.clock,
          logger = options.logger;
        var scheduler = {
          schedule: function schedule(source, target, event, delay, id) {
            if (id === void 0) {
              id = Math.random().toString(36).slice(2);
            }
            var scheduledEvent = {
              source: source,
              target: target,
              event: event,
              delay: delay,
              id: id,
              startedAt: Date.now()
            };
            var scheduledEventId = createScheduledEventId(source, id);
            system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
            var timeout = clock.setTimeout(function () {
              delete timerMap[scheduledEventId];
              delete system._snapshot._scheduledEvents[scheduledEventId];
              system._relay(source, target, event);
            }, delay);
            timerMap[scheduledEventId] = timeout;
          },
          cancel: function cancel(source, id) {
            var scheduledEventId = createScheduledEventId(source, id);
            var timeout = timerMap[scheduledEventId];
            delete timerMap[scheduledEventId];
            delete system._snapshot._scheduledEvents[scheduledEventId];
            if (timeout !== undefined) {
              clock.clearTimeout(timeout);
            }
          },
          cancelAll: function cancelAll(actorRef) {
            for (var scheduledEventId in system._snapshot._scheduledEvents) {
              var scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
              if (scheduledEvent.source === actorRef) {
                scheduler.cancel(actorRef, scheduledEvent.id);
              }
            }
          }
        };
        var sendInspectionEvent = function sendInspectionEvent(event) {
          if (!inspectionObservers.size) {
            return;
          }
          var resolvedInspectionEvent = _extends({}, event, {
            rootId: rootActor.sessionId
          });
          inspectionObservers.forEach(function (observer) {
            return observer.next == null ? void 0 : observer.next(resolvedInspectionEvent);
          });
        };
        var system = {
          _snapshot: {
            _scheduledEvents: (_ref4 = (options == null ? void 0 : options.snapshot) && options.snapshot.scheduler) != null ? _ref4 : {}
          },
          _bookId: function _bookId() {
            return "x:" + idCounter++;
          },
          _register: function _register(sessionId, actorRef) {
            children.set(sessionId, actorRef);
            return sessionId;
          },
          _unregister: function _unregister(actorRef) {
            children.delete(actorRef.sessionId);
            var systemId = reverseKeyedActors.get(actorRef);
            if (systemId !== undefined) {
              keyedActors.delete(systemId);
              reverseKeyedActors.delete(actorRef);
            }
          },
          get: function get(systemId) {
            return keyedActors.get(systemId);
          },
          getAll: function getAll() {
            return Object.fromEntries(keyedActors.entries());
          },
          _set: function _set(systemId, actorRef) {
            var existing = keyedActors.get(systemId);
            if (existing && existing !== actorRef) {
              throw new Error("Actor with system ID '" + systemId + "' already exists.");
            }
            keyedActors.set(systemId, actorRef);
            reverseKeyedActors.set(actorRef, systemId);
          },
          inspect: function inspect(observerOrFn) {
            var observer = toObserver(observerOrFn);
            inspectionObservers.add(observer);
            return {
              unsubscribe: function unsubscribe() {
                inspectionObservers.delete(observer);
              }
            };
          },
          _sendInspectionEvent: sendInspectionEvent,
          _relay: function _relay(source, target, event) {
            system._sendInspectionEvent({
              type: '@xstate.event',
              sourceRef: source,
              actorRef: target,
              event: event
            });
            target._send(event);
          },
          scheduler: scheduler,
          getSnapshot: function getSnapshot() {
            return {
              _scheduledEvents: _extends({}, system._snapshot._scheduledEvents)
            };
          },
          start: function start() {
            var scheduledEvents = system._snapshot._scheduledEvents;
            system._snapshot._scheduledEvents = {};
            for (var scheduledId in scheduledEvents) {
              var _scheduledEvents$sche = scheduledEvents[scheduledId],
                source = _scheduledEvents$sche.source,
                target = _scheduledEvents$sche.target,
                event = _scheduledEvents$sche.event,
                delay = _scheduledEvents$sche.delay,
                id = _scheduledEvents$sche.id;
              scheduler.schedule(source, target, event, delay, id);
            }
          },
          _clock: clock,
          _logger: logger
        };
        return system;
      }

      // those are needed to make JSDoc `@link` work properly

      var executingCustomAction = false;
      var $$ACTOR_TYPE = 1;

      // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
      var ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
        ProcessingStatus[ProcessingStatus['NotStarted'] = 0] = 'NotStarted';
        ProcessingStatus[ProcessingStatus['Running'] = 1] = 'Running';
        ProcessingStatus[ProcessingStatus['Stopped'] = 2] = 'Stopped';
        return ProcessingStatus;
      }({});
      var defaultOptions = {
        clock: {
          setTimeout: function (_setTimeout) {
            function setTimeout(_x, _x2) {
              return _setTimeout.apply(this, arguments);
            }
            setTimeout.toString = function () {
              return _setTimeout.toString();
            };
            return setTimeout;
          }(function (fn, ms) {
            return setTimeout(fn, ms);
          }),
          clearTimeout: function (_clearTimeout) {
            function clearTimeout(_x3) {
              return _clearTimeout.apply(this, arguments);
            }
            clearTimeout.toString = function () {
              return _clearTimeout.toString();
            };
            return clearTimeout;
          }(function (id) {
            return clearTimeout(id);
          })
        },
        logger: console.log.bind(console),
        devTools: false
      };

      /**
       * An Actor is a running process that can receive events, send events and change
       * its behavior based on the events it receives, which can cause effects outside
       * of the actor. When you run a state machine, it becomes an actor.
       */
      var Actor = /*#__PURE__*/function () {
        /**
         * Creates a new actor instance for the given logic with the provided options,
         * if any.
         *
         * @param logic The logic to create an actor from
         * @param options Actor options
         */
        function Actor(logic, options) {
          var _options$logger,
            _options$clock,
            _resolvedOptions$src,
            _this = this,
            _options$snapshot;
          this.logic = logic;
          /** The current internal state of the actor. */
          this._snapshot = void 0;
          /**
           * The clock that is responsible for setting and clearing timeouts, such as
           * delayed events and transitions.
           */
          this.clock = void 0;
          this.options = void 0;
          /** The unique identifier for this actor relative to its parent. */
          this.id = void 0;
          this.mailbox = new Mailbox(this._process.bind(this));
          this.observers = new Set();
          this.eventListeners = new Map();
          this.logger = void 0;
          /** @internal */
          this._processingStatus = ProcessingStatus.NotStarted;
          // Actor Ref
          this._parent = void 0;
          /** @internal */
          this._syncSnapshot = void 0;
          this.ref = void 0;
          // TODO: add typings for system
          this._actorScope = void 0;
          this.systemId = void 0;
          /** The globally unique process ID for this invocation. */
          this.sessionId = void 0;
          /** The system to which this actor belongs. */
          this.system = void 0;
          this._doneEvent = void 0;
          this.src = void 0;
          // array of functions to defer
          this._deferred = [];
          var resolvedOptions = _extends({}, defaultOptions, options);
          var clock = resolvedOptions.clock,
            logger = resolvedOptions.logger,
            parent = resolvedOptions.parent,
            syncSnapshot = resolvedOptions.syncSnapshot,
            id = resolvedOptions.id,
            systemId = resolvedOptions.systemId,
            inspect = resolvedOptions.inspect;
          this.system = parent ? parent.system : createSystem(this, {
            clock: clock,
            logger: logger
          });
          if (inspect && !parent) {
            // Always inspect at the system-level
            this.system.inspect(toObserver(inspect));
          }
          this.sessionId = this.system._bookId();
          this.id = id != null ? id : this.sessionId;
          this.logger = (_options$logger = options == null ? void 0 : options.logger) != null ? _options$logger : this.system._logger;
          this.clock = (_options$clock = options == null ? void 0 : options.clock) != null ? _options$clock : this.system._clock;
          this._parent = parent;
          this._syncSnapshot = syncSnapshot;
          this.options = resolvedOptions;
          this.src = (_resolvedOptions$src = resolvedOptions.src) != null ? _resolvedOptions$src : logic;
          this.ref = this;
          this._actorScope = {
            self: this,
            id: this.id,
            sessionId: this.sessionId,
            logger: this.logger,
            defer: function defer(fn) {
              _this._deferred.push(fn);
            },
            system: this.system,
            stopChild: function stopChild(child) {
              if (child._parent !== _this) {
                throw new Error("Cannot stop child actor " + child.id + " of " + _this.id + " because it is not a child");
              }
              child._stop();
            },
            emit: function emit(emittedEvent) {
              var listeners = _this.eventListeners.get(emittedEvent.type);
              var wildcardListener = _this.eventListeners.get('*');
              if (!listeners && !wildcardListener) {
                return;
              }
              var allListeners = [].concat(listeners ? listeners.values() : [], wildcardListener ? wildcardListener.values() : []);
              for (var _iterator = _createForOfIteratorHelperLoose(allListeners), _step; !(_step = _iterator()).done;) {
                var handler = _step.value;
                try {
                  handler(emittedEvent);
                } catch (err) {
                  reportUnhandledError(err);
                }
              }
            },
            actionExecutor: function actionExecutor(action) {
              var exec = function exec() {
                _this._actorScope.system._sendInspectionEvent({
                  type: '@xstate.action',
                  actorRef: _this,
                  action: {
                    type: action.type,
                    params: action.params
                  }
                });
                if (!action.exec) {
                  return;
                }
                var saveExecutingCustomAction = executingCustomAction;
                try {
                  executingCustomAction = true;
                  action.exec(action.info, action.params);
                } finally {
                  executingCustomAction = saveExecutingCustomAction;
                }
              };
              if (_this._processingStatus === ProcessingStatus.Running) {
                exec();
              } else {
                _this._deferred.push(exec);
              }
            }
          };

          // Ensure that the send method is bound to this Actor instance
          // if destructured
          this.send = this.send.bind(this);
          this.system._sendInspectionEvent({
            type: '@xstate.actor',
            actorRef: this
          });
          if (systemId) {
            this.systemId = systemId;
            this.system._set(systemId, this);
          }
          this._initState((_options$snapshot = options == null ? void 0 : options.snapshot) != null ? _options$snapshot : options == null ? void 0 : options.state);
          if (systemId && this._snapshot.status !== 'active') {
            this.system._unregister(this);
          }
        }
        var _proto2 = Actor.prototype;
        _proto2._initState = function _initState(persistedState) {
          try {
            var _this$options;
            this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, (_this$options = this.options) == null ? void 0 : _this$options.input);
          } catch (err) {
            // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
            // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
            // so right now this is a lie of sorts
            this._snapshot = {
              status: 'error',
              output: undefined,
              error: err
            };
          }
        };
        _proto2.update = function update(snapshot, event) {
          // Update state
          this._snapshot = snapshot;

          // Execute deferred effects
          var deferredFn;
          while (deferredFn = this._deferred.shift()) {
            try {
              deferredFn();
            } catch (err) {
              // this error can only be caught when executing *initial* actions
              // it's the only time when we call actions provided by the user through those deferreds
              // when the actor is already running we always execute them synchronously while transitioning
              // no "builtin deferred" should actually throw an error since they are either safe
              // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
              this._deferred.length = 0;
              this._snapshot = _extends({}, snapshot, {
                status: 'error',
                error: err
              });
            }
          }
          switch (this._snapshot.status) {
            case 'active':
              for (var _iterator2 = _createForOfIteratorHelperLoose(this.observers), _step2; !(_step2 = _iterator2()).done;) {
                var observer = _step2.value;
                try {
                  observer.next == null || observer.next(snapshot);
                } catch (err) {
                  reportUnhandledError(err);
                }
              }
              break;
            case 'done':
              // next observers are meant to be notified about done snapshots
              // this can be seen as something that is different from how observable work
              // but with observables `complete` callback is called without any arguments
              // it's more ergonomic for XState to treat a done snapshot as a "next" value
              // and the completion event as something that is separate,
              // something that merely follows emitting that done snapshot
              for (var _iterator3 = _createForOfIteratorHelperLoose(this.observers), _step3; !(_step3 = _iterator3()).done;) {
                var _observer = _step3.value;
                try {
                  _observer.next == null || _observer.next(snapshot);
                } catch (err) {
                  reportUnhandledError(err);
                }
              }
              this._stopProcedure();
              this._complete();
              this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
              if (this._parent) {
                this.system._relay(this, this._parent, this._doneEvent);
              }
              break;
            case 'error':
              this._error(this._snapshot.error);
              break;
          }
          this.system._sendInspectionEvent({
            type: '@xstate.snapshot',
            actorRef: this,
            event: event,
            snapshot: snapshot
          });
        }

        /**
         * Subscribe an observer to an actor’s snapshot values.
         *
         * @remarks
         * The observer will receive the actor’s snapshot value when it is emitted.
         * The observer can be:
         *
         * - A plain function that receives the latest snapshot, or
         * - An observer object whose `.next(snapshot)` method receives the latest
         *   snapshot
         *
         * @example
         *
         * ```ts
         * // Observer as a plain function
         * const subscription = actor.subscribe((snapshot) => {
         *   console.log(snapshot);
         * });
         * ```
         *
         * @example
         *
         * ```ts
         * // Observer as an object
         * const subscription = actor.subscribe({
         *   next(snapshot) {
         *     console.log(snapshot);
         *   },
         *   error(err) {
         *     // ...
         *   },
         *   complete() {
         *     // ...
         *   }
         * });
         * ```
         *
         * The return value of `actor.subscribe(observer)` is a subscription object
         * that has an `.unsubscribe()` method. You can call
         * `subscription.unsubscribe()` to unsubscribe the observer:
         *
         * @example
         *
         * ```ts
         * const subscription = actor.subscribe((snapshot) => {
         *   // ...
         * });
         *
         * // Unsubscribe the observer
         * subscription.unsubscribe();
         * ```
         *
         * When the actor is stopped, all of its observers will automatically be
         * unsubscribed.
         *
         * @param observer - Either a plain function that receives the latest
         *   snapshot, or an observer object whose `.next(snapshot)` method receives
         *   the latest snapshot
         */;
        _proto2.subscribe = function subscribe(nextListenerOrObserver, errorListener, completeListener) {
          var _this2 = this;
          var observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
          if (this._processingStatus !== ProcessingStatus.Stopped) {
            this.observers.add(observer);
          } else {
            switch (this._snapshot.status) {
              case 'done':
                try {
                  observer.complete == null || observer.complete();
                } catch (err) {
                  reportUnhandledError(err);
                }
                break;
              case 'error':
                {
                  var err = this._snapshot.error;
                  if (!observer.error) {
                    reportUnhandledError(err);
                  } else {
                    try {
                      observer.error(err);
                    } catch (err) {
                      reportUnhandledError(err);
                    }
                  }
                  break;
                }
            }
          }
          return {
            unsubscribe: function unsubscribe() {
              _this2.observers.delete(observer);
            }
          };
        };
        _proto2.on = function on(type, handler) {
          var listeners = this.eventListeners.get(type);
          if (!listeners) {
            listeners = new Set();
            this.eventListeners.set(type, listeners);
          }
          var wrappedHandler = handler.bind(undefined);
          listeners.add(wrappedHandler);
          return {
            unsubscribe: function unsubscribe() {
              listeners.delete(wrappedHandler);
            }
          };
        }

        /** Starts the Actor from the initial state */;
        _proto2.start = function start() {
          var _this3 = this;
          if (this._processingStatus === ProcessingStatus.Running) {
            // Do not restart the service if it is already started
            return this;
          }
          if (this._syncSnapshot) {
            this.subscribe({
              next: function next(snapshot) {
                if (snapshot.status === 'active') {
                  _this3.system._relay(_this3, _this3._parent, {
                    type: "xstate.snapshot." + _this3.id,
                    snapshot: snapshot
                  });
                }
              },
              error: function error() {}
            });
          }
          this.system._register(this.sessionId, this);
          if (this.systemId) {
            this.system._set(this.systemId, this);
          }
          this._processingStatus = ProcessingStatus.Running;

          // TODO: this isn't correct when rehydrating
          var initEvent = createInitEvent(this.options.input);
          this.system._sendInspectionEvent({
            type: '@xstate.event',
            sourceRef: this._parent,
            actorRef: this,
            event: initEvent
          });
          var status = this._snapshot.status;
          switch (status) {
            case 'done':
              // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
              // we still need to complete observers, flush deferreds etc
              this.update(this._snapshot, initEvent);
              // TODO: rethink cleanup of observers, mailbox, etc
              return this;
            case 'error':
              this._error(this._snapshot.error);
              return this;
          }
          if (!this._parent) {
            this.system.start();
          }
          if (this.logic.start) {
            try {
              this.logic.start(this._snapshot, this._actorScope);
            } catch (err) {
              this._snapshot = _extends({}, this._snapshot, {
                status: 'error',
                error: err
              });
              this._error(err);
              return this;
            }
          }

          // TODO: this notifies all subscribers but usually this is redundant
          // there is no real change happening here
          // we need to rethink if this needs to be refactored
          this.update(this._snapshot, initEvent);
          if (this.options.devTools) {
            this.attachDevTools();
          }
          this.mailbox.start();
          return this;
        };
        _proto2._process = function _process(event) {
          var nextState;
          var caughtError;
          try {
            nextState = this.logic.transition(this._snapshot, event, this._actorScope);
          } catch (err) {
            // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
            caughtError = {
              err: err
            };
          }
          if (caughtError) {
            var _caughtError = caughtError,
              err = _caughtError.err;
            this._snapshot = _extends({}, this._snapshot, {
              status: 'error',
              error: err
            });
            this._error(err);
            return;
          }
          this.update(nextState, event);
          if (event.type === XSTATE_STOP) {
            this._stopProcedure();
            this._complete();
          }
        };
        _proto2._stop = function _stop() {
          if (this._processingStatus === ProcessingStatus.Stopped) {
            return this;
          }
          this.mailbox.clear();
          if (this._processingStatus === ProcessingStatus.NotStarted) {
            this._processingStatus = ProcessingStatus.Stopped;
            return this;
          }
          this.mailbox.enqueue({
            type: XSTATE_STOP
          });
          return this;
        }

        /** Stops the Actor and unsubscribe all listeners. */;
        _proto2.stop = function stop() {
          if (this._parent) {
            throw new Error('A non-root actor cannot be stopped directly.');
          }
          return this._stop();
        };
        _proto2._complete = function _complete() {
          for (var _iterator4 = _createForOfIteratorHelperLoose(this.observers), _step4; !(_step4 = _iterator4()).done;) {
            var observer = _step4.value;
            try {
              observer.complete == null || observer.complete();
            } catch (err) {
              reportUnhandledError(err);
            }
          }
          this.observers.clear();
        };
        _proto2._reportError = function _reportError(err) {
          if (!this.observers.size) {
            if (!this._parent) {
              reportUnhandledError(err);
            }
            return;
          }
          var reportError = false;
          for (var _iterator5 = _createForOfIteratorHelperLoose(this.observers), _step5; !(_step5 = _iterator5()).done;) {
            var observer = _step5.value;
            var errorListener = observer.error;
            reportError || (reportError = !errorListener);
            try {
              errorListener == null || errorListener(err);
            } catch (err2) {
              reportUnhandledError(err2);
            }
          }
          this.observers.clear();
          if (reportError) {
            reportUnhandledError(err);
          }
        };
        _proto2._error = function _error(err) {
          this._stopProcedure();
          this._reportError(err);
          if (this._parent) {
            this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
          }
        }
        // TODO: atm children don't belong entirely to the actor so
        // in a way - it's not even super aware of them
        // so we can't stop them from here but we really should!
        // right now, they are being stopped within the machine's transition
        // but that could throw and leave us with "orphaned" active actors
        ;

        _proto2._stopProcedure = function _stopProcedure() {
          if (this._processingStatus !== ProcessingStatus.Running) {
            // Actor already stopped; do nothing
            return this;
          }

          // Cancel all delayed events
          this.system.scheduler.cancelAll(this);

          // TODO: mailbox.reset
          this.mailbox.clear();
          // TODO: after `stop` we must prepare ourselves for receiving events again
          // events sent *after* stop signal must be queued
          // it seems like this should be the common behavior for all of our consumers
          // so perhaps this should be unified somehow for all of them
          this.mailbox = new Mailbox(this._process.bind(this));
          this._processingStatus = ProcessingStatus.Stopped;
          this.system._unregister(this);
          return this;
        }

        /** @internal */;
        _proto2._send = function _send(event) {
          if (this._processingStatus === ProcessingStatus.Stopped) {
            return;
          }
          this.mailbox.enqueue(event);
        }

        /**
         * Sends an event to the running Actor to trigger a transition.
         *
         * @param event The event to send
         */;
        _proto2.send = function send(event) {
          this.system._relay(undefined, this, event);
        };
        _proto2.attachDevTools = function attachDevTools() {
          var devTools = this.options.devTools;
          if (devTools) {
            var resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
            resolvedDevToolsAdapter(this);
          }
        };
        _proto2.toJSON = function toJSON() {
          return {
            xstate$$type: $$ACTOR_TYPE,
            id: this.id
          };
        }

        /**
         * Obtain the internal state of the actor, which can be persisted.
         *
         * @remarks
         * The internal state can be persisted from any actor, not only machines.
         *
         * Note that the persisted state is not the same as the snapshot from
         * {@link Actor.getSnapshot}. Persisted state represents the internal state of
         * the actor, while snapshots represent the actor's last emitted value.
         *
         * Can be restored with {@link ActorOptions.state}
         * @see https://stately.ai/docs/persistence
         */;
        _proto2.getPersistedSnapshot = function getPersistedSnapshot(options) {
          return this.logic.getPersistedSnapshot(this._snapshot, options);
        };
        _proto2[symbolObservable] = function () {
          return this;
        }

        /**
         * Read an actor’s snapshot synchronously.
         *
         * @remarks
         * The snapshot represent an actor's last emitted value.
         *
         * When an actor receives an event, its internal state may change. An actor
         * may emit a snapshot when a state transition occurs.
         *
         * Note that some actors, such as callback actors generated with
         * `fromCallback`, will not emit snapshots.
         * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
         * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
         */;
        _proto2.getSnapshot = function getSnapshot() {
          return this._snapshot;
        };
        return Actor;
      }();
      /**
       * Creates a new actor instance for the given actor logic with the provided
       * options, if any.
       *
       * @remarks
       * When you create an actor from actor logic via `createActor(logic)`, you
       * implicitly create an actor system where the created actor is the root actor.
       * Any actors spawned from this root actor and its descendants are part of that
       * actor system.
       * @example
       *
       * ```ts
       * import { createActor } from 'xstate';
       * import { someActorLogic } from './someActorLogic.ts';
       *
       * // Creating the actor, which implicitly creates an actor system with itself as the root actor
       * const actor = createActor(someActorLogic);
       *
       * actor.subscribe((snapshot) => {
       *   console.log(snapshot);
       * });
       *
       * // Actors must be started by calling `actor.start()`, which will also start the actor system.
       * actor.start();
       *
       * // Actors can receive events
       * actor.send({ type: 'someEvent' });
       *
       * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
       * actor.stop();
       * ```
       *
       * @param logic - The actor logic to create an actor from. For a state machine
       *   actor logic creator, see {@link createMachine}. Other actor logic creators
       *   include {@link fromCallback}, {@link fromEventObservable},
       *   {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
       * @param options - Actor options
       */
      function createActor(logic) {
        for (var _len = arguments.length, _ref5 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          _ref5[_key - 1] = arguments[_key];
        }
        var options = _ref5[0];
        return new Actor(logic, options);
      }

      /**
       * @deprecated Use `Actor` instead.
       * @alias
       */

      function resolveCancel(_, snapshot, actionArgs, actionParams, _ref6) {
        var sendId = _ref6.sendId;
        var resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;
        return [snapshot, {
          sendId: resolvedSendId
        }, undefined];
      }
      function executeCancel(actorScope, params) {
        actorScope.defer(function () {
          actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
        });
      }
      /**
       * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The
       * canceled `sendTo(...)` action will not send its event or execute, unless the
       * `delay` has already elapsed before `cancel(...)` is called.
       *
       * @example
       *
       * ```ts
       * import { createMachine, sendTo, cancel } from 'xstate';
       *
       * const machine = createMachine({
       *   // ...
       *   on: {
       *     sendEvent: {
       *       actions: sendTo(
       *         'some-actor',
       *         { type: 'someEvent' },
       *         {
       *           id: 'some-id',
       *           delay: 1000
       *         }
       *       )
       *     },
       *     cancelEvent: {
       *       actions: cancel('some-id')
       *     }
       *   }
       * });
       * ```
       *
       * @param sendId The `id` of the `sendTo(...)` action to cancel.
       */
      function cancel(sendId) {
        function cancel(_args, _params) {}
        cancel.type = 'xstate.cancel';
        cancel.sendId = sendId;
        cancel.resolve = resolveCancel;
        cancel.execute = executeCancel;
        return cancel;
      }
      function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, _ref7) {
        var _extends2;
        var id = _ref7.id,
          systemId = _ref7.systemId,
          src = _ref7.src,
          input = _ref7.input,
          syncSnapshot = _ref7.syncSnapshot;
        var logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;
        var resolvedId = typeof id === 'function' ? id(actionArgs) : id;
        var actorRef;
        var resolvedInput = undefined;
        if (logic) {
          resolvedInput = typeof input === 'function' ? input({
            context: snapshot.context,
            event: actionArgs.event,
            self: actorScope.self
          }) : input;
          actorRef = createActor(logic, {
            id: resolvedId,
            src: src,
            parent: actorScope.self,
            syncSnapshot: syncSnapshot,
            systemId: systemId,
            input: resolvedInput
          });
        }
        return [cloneMachineSnapshot(snapshot, {
          children: _extends({}, snapshot.children, (_extends2 = {}, _extends2[resolvedId] = actorRef, _extends2))
        }), {
          id: id,
          systemId: systemId,
          actorRef: actorRef,
          src: src,
          input: resolvedInput
        }, undefined];
      }
      function executeSpawn(actorScope, _ref8) {
        var actorRef = _ref8.actorRef;
        if (!actorRef) {
          return;
        }
        actorScope.defer(function () {
          if (actorRef._processingStatus === ProcessingStatus.Stopped) {
            return;
          }
          actorRef.start();
        });
      }
      function spawnChild() {
        for (var _len2 = arguments.length, _ref9 = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          _ref9[_key2] = arguments[_key2];
        }
        var src = _ref9[0],
          _ref9$ = _ref9[1],
          _ref9$2 = _ref9$ === void 0 ? {} : _ref9$,
          id = _ref9$2.id,
          systemId = _ref9$2.systemId,
          input = _ref9$2.input,
          _ref9$2$syncSnapshot = _ref9$2.syncSnapshot,
          syncSnapshot = _ref9$2$syncSnapshot === void 0 ? false : _ref9$2$syncSnapshot;
        function spawnChild(_args, _params) {}
        spawnChild.type = 'xstate.spawnChild';
        spawnChild.id = id;
        spawnChild.systemId = systemId;
        spawnChild.src = src;
        spawnChild.input = input;
        spawnChild.syncSnapshot = syncSnapshot;
        spawnChild.resolve = resolveSpawn;
        spawnChild.execute = executeSpawn;
        return spawnChild;
      }
      function resolveStop(_, snapshot, args, actionParams, _ref10) {
        var actorRef = _ref10.actorRef;
        var actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;
        var resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;
        var children = snapshot.children;
        if (resolvedActorRef) {
          children = _extends({}, children);
          delete children[resolvedActorRef.id];
        }
        return [cloneMachineSnapshot(snapshot, {
          children: children
        }), resolvedActorRef, undefined];
      }
      function executeStop(actorScope, actorRef) {
        if (!actorRef) {
          return;
        }

        // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately
        // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)
        // this could throw on `systemId` collision, for example, when dealing with reentering transitions
        actorScope.system._unregister(actorRef);

        // this allows us to prevent an actor from being started if it gets stopped within the same macrostep
        // this can happen, for example, when the invoking state is being exited immediately by an always transition
        if (actorRef._processingStatus !== ProcessingStatus.Running) {
          actorScope.stopChild(actorRef);
          return;
        }
        // stopping a child enqueues a stop event in the child actor's mailbox
        // we need for all of the already enqueued events to be processed before we stop the child
        // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)
        // and we don't want to ignore those events
        actorScope.defer(function () {
          actorScope.stopChild(actorRef);
        });
      }
      /**
       * Stops a child actor.
       *
       * @param actorRef The actor to stop.
       */
      function stopChild(actorRef) {
        function stop(_args, _params) {}
        stop.type = 'xstate.stopChild';
        stop.actorRef = actorRef;
        stop.resolve = resolveStop;
        stop.execute = executeStop;
        return stop;
      }

      // TODO: throw on cycles (depth check should be enough)
      function evaluateGuard(guard, context, event, snapshot) {
        var machine = snapshot.machine;
        var isInline = typeof guard === 'function';
        var resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
        if (!isInline && !resolved) {
          throw new Error("Guard '" + (typeof guard === 'string' ? guard : guard.type) + "' is not implemented.'.");
        }
        if (typeof resolved !== 'function') {
          return evaluateGuard(resolved, context, event, snapshot);
        }
        var guardArgs = {
          context: context,
          event: event
        };
        var guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({
          context: context,
          event: event
        }) : guard.params : undefined;
        if (!('check' in resolved)) {
          // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
          // inline guards expect `TExpressionGuard` to be set to `undefined`
          // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
          return resolved(guardArgs, guardParams);
        }
        var builtinGuard = resolved;
        return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params
        );
      }

      var isAtomicStateNode = function isAtomicStateNode(stateNode) {
        return stateNode.type === 'atomic' || stateNode.type === 'final';
      };
      function getChildren(stateNode) {
        return Object.values(stateNode.states).filter(function (sn) {
          return sn.type !== 'history';
        });
      }
      function getProperAncestors(stateNode, toStateNode) {
        var ancestors = [];
        if (toStateNode === stateNode) {
          return ancestors;
        }

        // add all ancestors
        var m = stateNode.parent;
        while (m && m !== toStateNode) {
          ancestors.push(m);
          m = m.parent;
        }
        return ancestors;
      }
      function getAllStateNodes(stateNodes) {
        var nodeSet = new Set(stateNodes);
        var adjList = getAdjList(nodeSet);

        // add descendants
        for (var _iterator6 = _createForOfIteratorHelperLoose(nodeSet), _step6; !(_step6 = _iterator6()).done;) {
          var s = _step6.value;
          // if previously active, add existing child nodes
          if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
            getInitialStateNodesWithTheirAncestors(s).forEach(function (sn) {
              return nodeSet.add(sn);
            });
          } else {
            if (s.type === 'parallel') {
              for (var _iterator8 = _createForOfIteratorHelperLoose(getChildren(s)), _step8; !(_step8 = _iterator8()).done;) {
                var child = _step8.value;
                if (child.type === 'history') {
                  continue;
                }
                if (!nodeSet.has(child)) {
                  var initialStates = getInitialStateNodesWithTheirAncestors(child);
                  for (var _iterator9 = _createForOfIteratorHelperLoose(initialStates), _step9; !(_step9 = _iterator9()).done;) {
                    var initialStateNode = _step9.value;
                    nodeSet.add(initialStateNode);
                  }
                }
              }
            }
          }
        }

        // add all ancestors
        for (var _iterator7 = _createForOfIteratorHelperLoose(nodeSet), _step7; !(_step7 = _iterator7()).done;) {
          var _s = _step7.value;
          var m = _s.parent;
          while (m) {
            nodeSet.add(m);
            m = m.parent;
          }
        }
        return nodeSet;
      }
      function getValueFromAdj(baseNode, adjList) {
        var childStateNodes = adjList.get(baseNode);
        if (!childStateNodes) {
          return {}; // todo: fix?
        }

        if (baseNode.type === 'compound') {
          var childStateNode = childStateNodes[0];
          if (childStateNode) {
            if (isAtomicStateNode(childStateNode)) {
              return childStateNode.key;
            }
          } else {
            return {};
          }
        }
        var stateValue = {};
        for (var _iterator10 = _createForOfIteratorHelperLoose(childStateNodes), _step10; !(_step10 = _iterator10()).done;) {
          var _childStateNode = _step10.value;
          stateValue[_childStateNode.key] = getValueFromAdj(_childStateNode, adjList);
        }
        return stateValue;
      }
      function getAdjList(stateNodes) {
        var adjList = new Map();
        for (var _iterator11 = _createForOfIteratorHelperLoose(stateNodes), _step11; !(_step11 = _iterator11()).done;) {
          var s = _step11.value;
          if (!adjList.has(s)) {
            adjList.set(s, []);
          }
          if (s.parent) {
            if (!adjList.has(s.parent)) {
              adjList.set(s.parent, []);
            }
            adjList.get(s.parent).push(s);
          }
        }
        return adjList;
      }
      function getStateValue(rootNode, stateNodes) {
        var config = getAllStateNodes(stateNodes);
        return getValueFromAdj(rootNode, getAdjList(config));
      }
      function isInFinalState(stateNodeSet, stateNode) {
        if (stateNode.type === 'compound') {
          return getChildren(stateNode).some(function (s) {
            return s.type === 'final' && stateNodeSet.has(s);
          });
        }
        if (stateNode.type === 'parallel') {
          return getChildren(stateNode).every(function (sn) {
            return isInFinalState(stateNodeSet, sn);
          });
        }
        return stateNode.type === 'final';
      }
      var isStateId = function isStateId(str) {
        return str[0] === STATE_IDENTIFIER$1;
      };
      function getCandidates(stateNode, receivedEventType) {
        var candidates = stateNode.transitions.get(receivedEventType) || Array.from(stateNode.transitions.keys()).filter(function (eventDescriptor) {
          return matchesEventDescriptor(receivedEventType, eventDescriptor);
        }).sort(function (a, b) {
          return b.length - a.length;
        }).flatMap(function (key) {
          return stateNode.transitions.get(key);
        });
        return candidates;
      }

      /** All delayed transitions from the config. */
      function getDelayedTransitions(stateNode) {
        var afterConfig = stateNode.config.after;
        if (!afterConfig) {
          return [];
        }
        var mutateEntryExit = function mutateEntryExit(delay) {
          var afterEvent = createAfterEvent(delay, stateNode.id);
          var eventType = afterEvent.type;
          stateNode.entry.push(raise(afterEvent, {
            id: eventType,
            delay: delay
          }));
          stateNode.exit.push(cancel(eventType));
          return eventType;
        };
        var delayedTransitions = Object.keys(afterConfig).flatMap(function (delay) {
          var configTransition = afterConfig[delay];
          var resolvedTransition = typeof configTransition === 'string' ? {
            target: configTransition
          } : configTransition;
          var resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
          var eventType = mutateEntryExit(resolvedDelay);
          return toArray(resolvedTransition).map(function (transition) {
            return _extends({}, transition, {
              event: eventType,
              delay: resolvedDelay
            });
          });
        });
        return delayedTransitions.map(function (delayedTransition) {
          var delay = delayedTransition.delay;
          return _extends({}, formatTransition(stateNode, delayedTransition.event, delayedTransition), {
            delay: delay
          });
        });
      }
      function formatTransition(stateNode, descriptor, transitionConfig) {
        var _transitionConfig$ree;
        var normalizedTarget = normalizeTarget(transitionConfig.target);
        var reenter = (_transitionConfig$ree = transitionConfig.reenter) != null ? _transitionConfig$ree : false;
        var target = resolveTarget(stateNode, normalizedTarget);
        var transition = _extends({}, transitionConfig, {
          actions: toArray(transitionConfig.actions),
          guard: transitionConfig.guard,
          target: target,
          source: stateNode,
          reenter: reenter,
          eventType: descriptor,
          toJSON: function toJSON() {
            return _extends({}, transition, {
              source: "#" + stateNode.id,
              target: target ? target.map(function (t) {
                return "#" + t.id;
              }) : undefined
            });
          }
        });
        return transition;
      }
      function formatTransitions(stateNode) {
        var transitions = new Map();
        if (stateNode.config.on) {
          var _loop = function _loop() {
            var descriptor = _Object$keys[_i];
            if (descriptor === NULL_EVENT) {
              throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
            }
            var transitionsConfig = stateNode.config.on[descriptor];
            transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(function (t) {
              return formatTransition(stateNode, descriptor, t);
            }));
          };
          for (var _i = 0, _Object$keys = Object.keys(stateNode.config.on); _i < _Object$keys.length; _i++) {
            _loop();
          }
        }
        if (stateNode.config.onDone) {
          var descriptor = "xstate.done.state." + stateNode.id;
          transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(function (t) {
            return formatTransition(stateNode, descriptor, t);
          }));
        }
        var _loop2 = function _loop2() {
          var invokeDef = _step12.value;
          if (invokeDef.onDone) {
            var _descriptor = "xstate.done.actor." + invokeDef.id;
            transitions.set(_descriptor, toTransitionConfigArray(invokeDef.onDone).map(function (t) {
              return formatTransition(stateNode, _descriptor, t);
            }));
          }
          if (invokeDef.onError) {
            var _descriptor2 = "xstate.error.actor." + invokeDef.id;
            transitions.set(_descriptor2, toTransitionConfigArray(invokeDef.onError).map(function (t) {
              return formatTransition(stateNode, _descriptor2, t);
            }));
          }
          if (invokeDef.onSnapshot) {
            var _descriptor3 = "xstate.snapshot." + invokeDef.id;
            transitions.set(_descriptor3, toTransitionConfigArray(invokeDef.onSnapshot).map(function (t) {
              return formatTransition(stateNode, _descriptor3, t);
            }));
          }
        };
        for (var _iterator12 = _createForOfIteratorHelperLoose(stateNode.invoke), _step12; !(_step12 = _iterator12()).done;) {
          _loop2();
        }
        for (var _iterator13 = _createForOfIteratorHelperLoose(stateNode.after), _step13; !(_step13 = _iterator13()).done;) {
          var delayedTransition = _step13.value;
          var existing = transitions.get(delayedTransition.eventType);
          if (!existing) {
            existing = [];
            transitions.set(delayedTransition.eventType, existing);
          }
          existing.push(delayedTransition);
        }
        return transitions;
      }
      function formatInitialTransition(stateNode, _target) {
        var resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;
        if (!resolvedTarget && _target) {
          throw new Error(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
          "Initial state node \"" + _target + "\" not found on parent state node #" + stateNode.id);
        }
        var transition = {
          source: stateNode,
          actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),
          eventType: null,
          reenter: false,
          target: resolvedTarget ? [resolvedTarget] : [],
          toJSON: function toJSON() {
            return _extends({}, transition, {
              source: "#" + stateNode.id,
              target: resolvedTarget ? ["#" + resolvedTarget.id] : []
            });
          }
        };
        return transition;
      }
      function resolveTarget(stateNode, targets) {
        if (targets === undefined) {
          // an undefined target signals that the state node should not transition from that state when receiving that event
          return undefined;
        }
        return targets.map(function (target) {
          if (typeof target !== 'string') {
            return target;
          }
          if (isStateId(target)) {
            return stateNode.machine.getStateNodeById(target);
          }
          var isInternalTarget = target[0] === STATE_DELIMITER;
          // If internal target is defined on machine,
          // do not include machine key on target
          if (isInternalTarget && !stateNode.parent) {
            return getStateNodeByPath(stateNode, target.slice(1));
          }
          var resolvedTarget = isInternalTarget ? stateNode.key + target : target;
          if (stateNode.parent) {
            try {
              var targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
              return targetStateNode;
            } catch (err) {
              throw new Error("Invalid transition definition for state node '" + stateNode.id + "':\n" + err.message);
            }
          } else {
            throw new Error("Invalid target: \"" + target + "\" is not a valid target from the root node. Did you mean \"." + target + "\"?");
          }
        });
      }
      function resolveHistoryDefaultTransition(stateNode) {
        var normalizedTarget = normalizeTarget(stateNode.config.target);
        if (!normalizedTarget) {
          return stateNode.parent.initial;
        }
        return {
          target: normalizedTarget.map(function (t) {
            return typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t;
          })
        };
      }
      function isHistoryNode(stateNode) {
        return stateNode.type === 'history';
      }
      function getInitialStateNodesWithTheirAncestors(stateNode) {
        var states = getInitialStateNodes(stateNode);
        for (var _iterator14 = _createForOfIteratorHelperLoose(states), _step14; !(_step14 = _iterator14()).done;) {
          var initialState = _step14.value;
          for (var _iterator15 = _createForOfIteratorHelperLoose(getProperAncestors(initialState, stateNode)), _step15; !(_step15 = _iterator15()).done;) {
            var ancestor = _step15.value;
            states.add(ancestor);
          }
        }
        return states;
      }
      function getInitialStateNodes(stateNode) {
        var set = new Set();
        function iter(descStateNode) {
          if (set.has(descStateNode)) {
            return;
          }
          set.add(descStateNode);
          if (descStateNode.type === 'compound') {
            iter(descStateNode.initial.target[0]);
          } else if (descStateNode.type === 'parallel') {
            for (var _iterator16 = _createForOfIteratorHelperLoose(getChildren(descStateNode)), _step16; !(_step16 = _iterator16()).done;) {
              var child = _step16.value;
              iter(child);
            }
          }
        }
        iter(stateNode);
        return set;
      }
      /** Returns the child state node from its relative `stateKey`, or throws. */
      function getStateNode(stateNode, stateKey) {
        if (isStateId(stateKey)) {
          return stateNode.machine.getStateNodeById(stateKey);
        }
        if (!stateNode.states) {
          throw new Error("Unable to retrieve child state '" + stateKey + "' from '" + stateNode.id + "'; no child states exist.");
        }
        var result = stateNode.states[stateKey];
        if (!result) {
          throw new Error("Child state '" + stateKey + "' does not exist on '" + stateNode.id + "'");
        }
        return result;
      }

      /**
       * Returns the relative state node from the given `statePath`, or throws.
       *
       * @param statePath The string or string array relative path to the state node.
       */
      function getStateNodeByPath(stateNode, statePath) {
        if (typeof statePath === 'string' && isStateId(statePath)) {
          try {
            return stateNode.machine.getStateNodeById(statePath);
          } catch (_unused) {
            // try individual paths
            // throw e;
          }
        }
        var arrayStatePath = toStatePath(statePath).slice();
        var currentStateNode = stateNode;
        while (arrayStatePath.length) {
          var key = arrayStatePath.shift();
          if (!key.length) {
            break;
          }
          currentStateNode = getStateNode(currentStateNode, key);
        }
        return currentStateNode;
      }

      /**
       * Returns the state nodes represented by the current state value.
       *
       * @param stateValue The state value or State instance
       */
      function getStateNodes(stateNode, stateValue) {
        if (typeof stateValue === 'string') {
          var childStateNode = stateNode.states[stateValue];
          if (!childStateNode) {
            throw new Error("State '" + stateValue + "' does not exist on '" + stateNode.id + "'");
          }
          return [stateNode, childStateNode];
        }
        var childStateKeys = Object.keys(stateValue);
        var childStateNodes = childStateKeys.map(function (subStateKey) {
          return getStateNode(stateNode, subStateKey);
        }).filter(Boolean);
        return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce(function (allSubStateNodes, subStateKey) {
          var subStateNode = getStateNode(stateNode, subStateKey);
          if (!subStateNode) {
            return allSubStateNodes;
          }
          var subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
          return allSubStateNodes.concat(subStateNodes);
        }, []));
      }
      function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
        var childStateNode = getStateNode(stateNode, stateValue);
        var next = childStateNode.next(snapshot, event);
        if (!next || !next.length) {
          return stateNode.next(snapshot, event);
        }
        return next;
      }
      function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
        var subStateKeys = Object.keys(stateValue);
        var childStateNode = getStateNode(stateNode, subStateKeys[0]);
        var next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
        if (!next || !next.length) {
          return stateNode.next(snapshot, event);
        }
        return next;
      }
      function transitionParallelNode(stateNode, stateValue, snapshot, event) {
        var allInnerTransitions = [];
        for (var _i2 = 0, _Object$keys2 = Object.keys(stateValue); _i2 < _Object$keys2.length; _i2++) {
          var subStateKey = _Object$keys2[_i2];
          var subStateValue = stateValue[subStateKey];
          if (!subStateValue) {
            continue;
          }
          var subStateNode = getStateNode(stateNode, subStateKey);
          var innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
          if (innerTransitions) {
            allInnerTransitions.push.apply(allInnerTransitions, innerTransitions);
          }
        }
        if (!allInnerTransitions.length) {
          return stateNode.next(snapshot, event);
        }
        return allInnerTransitions;
      }
      function transitionNode(stateNode, stateValue, snapshot, event) {
        // leaf node
        if (typeof stateValue === 'string') {
          return transitionAtomicNode(stateNode, stateValue, snapshot, event);
        }

        // compound node
        if (Object.keys(stateValue).length === 1) {
          return transitionCompoundNode(stateNode, stateValue, snapshot, event);
        }

        // parallel node
        return transitionParallelNode(stateNode, stateValue, snapshot, event);
      }
      function getHistoryNodes(stateNode) {
        return Object.keys(stateNode.states).map(function (key) {
          return stateNode.states[key];
        }).filter(function (sn) {
          return sn.type === 'history';
        });
      }
      function isDescendant(childStateNode, parentStateNode) {
        var marker = childStateNode;
        while (marker.parent && marker.parent !== parentStateNode) {
          marker = marker.parent;
        }
        return marker.parent === parentStateNode;
      }
      function hasIntersection(s1, s2) {
        var set1 = new Set(s1);
        var set2 = new Set(s2);
        for (var _iterator17 = _createForOfIteratorHelperLoose(set1), _step17; !(_step17 = _iterator17()).done;) {
          var item = _step17.value;
          if (set2.has(item)) {
            return true;
          }
        }
        for (var _iterator18 = _createForOfIteratorHelperLoose(set2), _step18; !(_step18 = _iterator18()).done;) {
          var _item = _step18.value;
          if (set1.has(_item)) {
            return true;
          }
        }
        return false;
      }
      function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
        var filteredTransitions = new Set();
        for (var _iterator19 = _createForOfIteratorHelperLoose(enabledTransitions), _step19; !(_step19 = _iterator19()).done;) {
          var t1 = _step19.value;
          var t1Preempted = false;
          var transitionsToRemove = new Set();
          for (var _iterator20 = _createForOfIteratorHelperLoose(filteredTransitions), _step20; !(_step20 = _iterator20()).done;) {
            var t2 = _step20.value;
            if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
              if (isDescendant(t1.source, t2.source)) {
                transitionsToRemove.add(t2);
              } else {
                t1Preempted = true;
                break;
              }
            }
          }
          if (!t1Preempted) {
            for (var _iterator21 = _createForOfIteratorHelperLoose(transitionsToRemove), _step21; !(_step21 = _iterator21()).done;) {
              var t3 = _step21.value;
              filteredTransitions.delete(t3);
            }
            filteredTransitions.add(t1);
          }
        }
        return Array.from(filteredTransitions);
      }
      function findLeastCommonAncestor(stateNodes) {
        var head = stateNodes[0],
          tail = stateNodes.slice(1);
        var _loop3 = function _loop3() {
            var ancestor = _step22.value;
            if (tail.every(function (sn) {
              return isDescendant(sn, ancestor);
            })) {
              return {
                v: ancestor
              };
            }
          },
          _ret;
        for (var _iterator22 = _createForOfIteratorHelperLoose(getProperAncestors(head, undefined)), _step22; !(_step22 = _iterator22()).done;) {
          _ret = _loop3();
          if (_ret) return _ret.v;
        }
      }
      function getEffectiveTargetStates(transition, historyValue) {
        if (!transition.target) {
          return [];
        }
        var targets = new Set();
        for (var _iterator23 = _createForOfIteratorHelperLoose(transition.target), _step23; !(_step23 = _iterator23()).done;) {
          var targetNode = _step23.value;
          if (isHistoryNode(targetNode)) {
            if (historyValue[targetNode.id]) {
              for (var _iterator24 = _createForOfIteratorHelperLoose(historyValue[targetNode.id]), _step24; !(_step24 = _iterator24()).done;) {
                var node = _step24.value;
                targets.add(node);
              }
            } else {
              for (var _iterator25 = _createForOfIteratorHelperLoose(getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)), _step25; !(_step25 = _iterator25()).done;) {
                var _node = _step25.value;
                targets.add(_node);
              }
            }
          } else {
            targets.add(targetNode);
          }
        }
        return Array.from(targets);
      }
      function getTransitionDomain(transition, historyValue) {
        var targetStates = getEffectiveTargetStates(transition, historyValue);
        if (!targetStates) {
          return;
        }
        if (!transition.reenter && targetStates.every(function (target) {
          return target === transition.source || isDescendant(target, transition.source);
        })) {
          return transition.source;
        }
        var lca = findLeastCommonAncestor(targetStates.concat(transition.source));
        if (lca) {
          return lca;
        }

        // at this point we know that it's a root transition since LCA couldn't be found
        if (transition.reenter) {
          return;
        }
        return transition.source.machine.root;
      }
      function computeExitSet(transitions, stateNodeSet, historyValue) {
        var statesToExit = new Set();
        for (var _iterator26 = _createForOfIteratorHelperLoose(transitions), _step26; !(_step26 = _iterator26()).done;) {
          var _t$target;
          var t = _step26.value;
          if ((_t$target = t.target) != null && _t$target.length) {
            var domain = getTransitionDomain(t, historyValue);
            if (t.reenter && t.source === domain) {
              statesToExit.add(domain);
            }
            for (var _iterator27 = _createForOfIteratorHelperLoose(stateNodeSet), _step27; !(_step27 = _iterator27()).done;) {
              var stateNode = _step27.value;
              if (isDescendant(stateNode, domain)) {
                statesToExit.add(stateNode);
              }
            }
          }
        }
        return Array.from(statesToExit);
      }
      function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
        if (prevStateNodes.length !== nextStateNodeSet.size) {
          return false;
        }
        for (var _iterator28 = _createForOfIteratorHelperLoose(prevStateNodes), _step28; !(_step28 = _iterator28()).done;) {
          var node = _step28.value;
          if (!nextStateNodeSet.has(node)) {
            return false;
          }
        }
        return true;
      }

      /** https://www.w3.org/TR/scxml/#microstepProcedure */
      function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
        if (!transitions.length) {
          return currentSnapshot;
        }
        var mutStateNodeSet = new Set(currentSnapshot._nodes);
        var historyValue = currentSnapshot.historyValue;
        var filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
        var nextState = currentSnapshot;

        // Exit states
        if (!isInitial) {
          var _exitStates = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
          nextState = _exitStates[0];
          historyValue = _exitStates[1];
        }

        // Execute transition content
        nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(function (t) {
          return t.actions;
        }), internalQueue, undefined);

        // Enter states
        nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
        var nextStateNodes = Array.from(mutStateNodeSet);
        if (nextState.status === 'done') {
          nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort(function (a, b) {
            return b.order - a.order;
          }).flatMap(function (state) {
            return state.exit;
          }), internalQueue, undefined);
        }

        // eslint-disable-next-line no-useless-catch
        try {
          if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
            return nextState;
          }
          return cloneMachineSnapshot(nextState, {
            _nodes: nextStateNodes,
            historyValue: historyValue
          });
        } catch (e) {
          // TODO: Refactor this once proper error handling is implemented.
          // See https://github.com/statelyai/rfcs/pull/4
          throw e;
        }
      }
      function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
        if (rootNode.output === undefined) {
          return;
        }
        var doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);
        return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
      }
      function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
        var nextSnapshot = currentSnapshot;
        var statesToEnter = new Set();
        // those are states that were directly targeted or indirectly targeted by the explicit target
        // in other words, those are states for which initial actions should be executed
        // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
        var statesForDefaultEntry = new Set();
        computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);

        // In the initial state, the root state node is "entered".
        if (isInitial) {
          statesForDefaultEntry.add(currentSnapshot.machine.root);
        }
        var completedNodes = new Set();
        for (var _iterator29 = _createForOfIteratorHelperLoose(Array.from(statesToEnter).sort(function (a, b) {
            return a.order - b.order;
          })), _step29; !(_step29 = _iterator29()).done;) {
          var stateNodeToEnter = _step29.value;
          mutStateNodeSet.add(stateNodeToEnter);
          var actions = [];

          // Add entry actions
          actions.push.apply(actions, stateNodeToEnter.entry);
          for (var _iterator30 = _createForOfIteratorHelperLoose(stateNodeToEnter.invoke), _step30; !(_step30 = _iterator30()).done;) {
            var invokeDef = _step30.value;
            actions.push(spawnChild(invokeDef.src, _extends({}, invokeDef, {
              syncSnapshot: !!invokeDef.onSnapshot
            })));
          }
          if (statesForDefaultEntry.has(stateNodeToEnter)) {
            var initialActions = stateNodeToEnter.initial.actions;
            actions.push.apply(actions, initialActions);
          }
          nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(function (invokeDef) {
            return invokeDef.id;
          }));
          if (stateNodeToEnter.type === 'final') {
            var parent = stateNodeToEnter.parent;
            var ancestorMarker = (parent == null ? void 0 : parent.type) === 'parallel' ? parent : parent == null ? void 0 : parent.parent;
            var rootCompletionNode = ancestorMarker || stateNodeToEnter;
            if ((parent == null ? void 0 : parent.type) === 'compound') {
              internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));
            }
            while (((_ancestorMarker = ancestorMarker) == null ? void 0 : _ancestorMarker.type) === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
              var _ancestorMarker;
              completedNodes.add(ancestorMarker);
              internalQueue.push(createDoneStateEvent(ancestorMarker.id));
              rootCompletionNode = ancestorMarker;
              ancestorMarker = ancestorMarker.parent;
            }
            if (ancestorMarker) {
              continue;
            }
            nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
              status: 'done',
              output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
            });
          }
        }
        return nextSnapshot;
      }
      function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
        for (var _iterator31 = _createForOfIteratorHelperLoose(transitions), _step31; !(_step31 = _iterator31()).done;) {
          var t = _step31.value;
          var domain = getTransitionDomain(t, historyValue);
          for (var _iterator32 = _createForOfIteratorHelperLoose(t.target || []), _step32; !(_step32 = _iterator32()).done;) {
            var s = _step32.value;
            if (!isHistoryNode(s) && (
            // if the target is different than the source then it will *definitely* be entered
            t.source !== s ||
            // we know that the domain can't lie within the source
            // if it's different than the source then it's outside of it and it means that the target has to be entered as well
            t.source !== domain ||
            // reentering transitions always enter the target, even if it's the source itself
            t.reenter)) {
              statesToEnter.add(s);
              statesForDefaultEntry.add(s);
            }
            addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
          }
          var targetStates = getEffectiveTargetStates(t, historyValue);
          for (var _iterator33 = _createForOfIteratorHelperLoose(targetStates), _step33; !(_step33 = _iterator33()).done;) {
            var _s2 = _step33.value;
            var ancestors = getProperAncestors(_s2, domain);
            if ((domain == null ? void 0 : domain.type) === 'parallel') {
              ancestors.push(domain);
            }
            addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);
          }
        }
      }
      function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
        if (isHistoryNode(stateNode)) {
          if (historyValue[stateNode.id]) {
            var historyStateNodes = historyValue[stateNode.id];
            for (var _iterator34 = _createForOfIteratorHelperLoose(historyStateNodes), _step34; !(_step34 = _iterator34()).done;) {
              var s = _step34.value;
              statesToEnter.add(s);
              addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
            }
            for (var _iterator35 = _createForOfIteratorHelperLoose(historyStateNodes), _step35; !(_step35 = _iterator35()).done;) {
              var _s3 = _step35.value;
              addProperAncestorStatesToEnter(_s3, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
            }
          } else {
            var historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
            for (var _iterator36 = _createForOfIteratorHelperLoose(historyDefaultTransition.target), _step36; !(_step36 = _iterator36()).done;) {
              var _stateNode$parent;
              var _s4 = _step36.value;
              statesToEnter.add(_s4);
              if (historyDefaultTransition === ((_stateNode$parent = stateNode.parent) == null ? void 0 : _stateNode$parent.initial)) {
                statesForDefaultEntry.add(stateNode.parent);
              }
              addDescendantStatesToEnter(_s4, historyValue, statesForDefaultEntry, statesToEnter);
            }
            for (var _iterator37 = _createForOfIteratorHelperLoose(historyDefaultTransition.target), _step37; !(_step37 = _iterator37()).done;) {
              var _s5 = _step37.value;
              addProperAncestorStatesToEnter(_s5, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
            }
          }
        } else {
          if (stateNode.type === 'compound') {
            var _stateNode$initial$ta = stateNode.initial.target,
              initialState = _stateNode$initial$ta[0];
            if (!isHistoryNode(initialState)) {
              statesToEnter.add(initialState);
              statesForDefaultEntry.add(initialState);
            }
            addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
            addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
          } else {
            if (stateNode.type === 'parallel') {
              var _loop4 = function _loop4() {
                var child = _step38.value;
                if (!Array.from(statesToEnter).some(function (s) {
                  return isDescendant(s, child);
                })) {
                  if (!isHistoryNode(child)) {
                    statesToEnter.add(child);
                    statesForDefaultEntry.add(child);
                  }
                  addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
                }
              };
              for (var _iterator38 = _createForOfIteratorHelperLoose(getChildren(stateNode).filter(function (sn) {
                  return !isHistoryNode(sn);
                })), _step38; !(_step38 = _iterator38()).done;) {
                _loop4();
              }
            }
          }
        }
      }
      function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
        for (var _iterator39 = _createForOfIteratorHelperLoose(ancestors), _step39; !(_step39 = _iterator39()).done;) {
          var anc = _step39.value;
          if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
            statesToEnter.add(anc);
          }
          if (anc.type === 'parallel') {
            var _loop5 = function _loop5() {
              var child = _step40.value;
              if (!Array.from(statesToEnter).some(function (s) {
                return isDescendant(s, child);
              })) {
                statesToEnter.add(child);
                addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
              }
            };
            for (var _iterator40 = _createForOfIteratorHelperLoose(getChildren(anc).filter(function (sn) {
                return !isHistoryNode(sn);
              })), _step40; !(_step40 = _iterator40()).done;) {
              _loop5();
            }
          }
        }
      }
      function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
        addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
      }
      function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
        var nextSnapshot = currentSnapshot;
        var statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
        statesToExit.sort(function (a, b) {
          return b.order - a.order;
        });
        var changedHistory;

        // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
        var _loop6 = function _loop6() {
          var exitStateNode = _step41.value;
          for (var _iterator43 = _createForOfIteratorHelperLoose(getHistoryNodes(exitStateNode)), _step43; !(_step43 = _iterator43()).done;) {
            var _changedHistory;
            var historyNode = _step43.value;
            var predicate = void 0;
            if (historyNode.history === 'deep') {
              predicate = function predicate(sn) {
                return isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
              };
            } else {
              predicate = function predicate(sn) {
                return sn.parent === exitStateNode;
              };
            }
            (_changedHistory = changedHistory) != null ? _changedHistory : changedHistory = _extends({}, historyValue);
            changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
          }
        };
        for (var _iterator41 = _createForOfIteratorHelperLoose(statesToExit), _step41; !(_step41 = _iterator41()).done;) {
          _loop6();
        }
        for (var _iterator42 = _createForOfIteratorHelperLoose(statesToExit), _step42; !(_step42 = _iterator42()).done;) {
          var s = _step42.value;
          nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [].concat(s.exit, s.invoke.map(function (def) {
            return stopChild(def.id);
          })), internalQueue, undefined);
          mutStateNodeSet.delete(s);
        }
        return [nextSnapshot, changedHistory || historyValue];
      }
      function getAction(machine, actionType) {
        return machine.implementations.actions[actionType];
      }
      function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
        var machine = currentSnapshot.machine;
        var intermediateSnapshot = currentSnapshot;
        for (var _iterator44 = _createForOfIteratorHelperLoose(actions), _step44; !(_step44 = _iterator44()).done;) {
          var action = _step44.value;
          var isInline = typeof action === 'function';
          var resolvedAction = isInline ? action :
          // the existing type of `.actions` assumes non-nullable `TExpressionAction`
          // it's fine to cast this here to get a common type and lack of errors in the rest of the code
          // our logic below makes sure that we call those 2 "variants" correctly

          getAction(machine, typeof action === 'string' ? action : action.type);
          var actionArgs = {
            context: intermediateSnapshot.context,
            event: event,
            self: actorScope.self,
            system: actorScope.system
          };
          var actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({
            context: intermediateSnapshot.context,
            event: event
          }) : action.params : undefined;
          if (!resolvedAction || !('resolve' in resolvedAction)) {
            actorScope.actionExecutor({
              type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',
              info: actionArgs,
              params: actionParams,
              exec: resolvedAction
            });
            continue;
          }
          var builtinAction = resolvedAction;
          var _builtinAction$resolv = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,
            // this holds all params
            extra),
            nextState = _builtinAction$resolv[0],
            params = _builtinAction$resolv[1],
            _actions = _builtinAction$resolv[2];
          intermediateSnapshot = nextState;
          if ('retryResolve' in builtinAction) {
            retries == null || retries.push([builtinAction, params]);
          }
          if ('execute' in builtinAction) {
            actorScope.actionExecutor({
              type: builtinAction.type,
              info: actionArgs,
              params: params,
              exec: builtinAction.execute.bind(null, actorScope, params)
            });
          }
          if (_actions) {
            intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, _actions, extra, retries);
          }
        }
        return intermediateSnapshot;
      }
      function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
        var retries = deferredActorIds ? [] : undefined;
        var nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
          internalQueue: internalQueue,
          deferredActorIds: deferredActorIds
        }, retries);
        retries == null || retries.forEach(function (_ref18) {
          var builtinAction = _ref18[0],
            params = _ref18[1];
          builtinAction.retryResolve(actorScope, nextState, params);
        });
        return nextState;
      }
      function macrostep(snapshot, event, actorScope, internalQueue) {
        var nextSnapshot = snapshot;
        var microstates = [];
        function addMicrostate(microstate, event, transitions) {
          actorScope.system._sendInspectionEvent({
            type: '@xstate.microstep',
            actorRef: actorScope.self,
            event: event,
            snapshot: microstate,
            _transitions: transitions
          });
          microstates.push(microstate);
        }

        // Handle stop event
        if (event.type === XSTATE_STOP) {
          nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
            status: 'stopped'
          });
          addMicrostate(nextSnapshot, event, []);
          return {
            snapshot: nextSnapshot,
            microstates: microstates
          };
        }
        var nextEvent = event;

        // Assume the state is at rest (no raised events)
        // Determine the next state based on the next microstep
        if (nextEvent.type !== XSTATE_INIT) {
          var currentEvent = nextEvent;
          var isErr = isErrorActorEvent(currentEvent);
          var transitions = selectTransitions(currentEvent, nextSnapshot);
          if (isErr && !transitions.length) {
            // TODO: we should likely only allow transitions selected by very explicit descriptors
            // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
            // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
            nextSnapshot = cloneMachineSnapshot(snapshot, {
              status: 'error',
              error: currentEvent.error
            });
            addMicrostate(nextSnapshot, currentEvent, []);
            return {
              snapshot: nextSnapshot,
              microstates: microstates
            };
          }
          nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false,
          // isInitial
          internalQueue);
          addMicrostate(nextSnapshot, currentEvent, transitions);
        }
        var shouldSelectEventlessTransitions = true;
        while (nextSnapshot.status === 'active') {
          var enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];

          // eventless transitions should always be selected after selecting *regular* transitions
          // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
          var previousState = enabledTransitions.length ? nextSnapshot : undefined;
          if (!enabledTransitions.length) {
            if (!internalQueue.length) {
              break;
            }
            nextEvent = internalQueue.shift();
            enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
          }
          nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
          shouldSelectEventlessTransitions = nextSnapshot !== previousState;
          addMicrostate(nextSnapshot, nextEvent, enabledTransitions);
        }
        if (nextSnapshot.status !== 'active') {
          stopChildren(nextSnapshot, nextEvent, actorScope);
        }
        return {
          snapshot: nextSnapshot,
          microstates: microstates
        };
      }
      function stopChildren(nextState, event, actorScope) {
        return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(function (child) {
          return stopChild(child);
        }), [], undefined);
      }
      function selectTransitions(event, nextState) {
        return nextState.machine.getTransitionData(nextState, event);
      }
      function selectEventlessTransitions(nextState, event) {
        var enabledTransitionSet = new Set();
        var atomicStates = nextState._nodes.filter(isAtomicStateNode);
        for (var _iterator45 = _createForOfIteratorHelperLoose(atomicStates), _step45; !(_step45 = _iterator45()).done;) {
          var stateNode = _step45.value;
          loop: for (var _iterator46 = _createForOfIteratorHelperLoose([stateNode].concat(getProperAncestors(stateNode, undefined))), _step46; !(_step46 = _iterator46()).done;) {
            var s = _step46.value;
            if (!s.always) {
              continue;
            }
            for (var _iterator47 = _createForOfIteratorHelperLoose(s.always), _step47; !(_step47 = _iterator47()).done;) {
              var _transition = _step47.value;
              if (_transition.guard === undefined || evaluateGuard(_transition.guard, nextState.context, event, nextState)) {
                enabledTransitionSet.add(_transition);
                break loop;
              }
            }
          }
        }
        return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
      }

      /**
       * Resolves a partial state value with its full representation in the state
       * node's machine.
       *
       * @param stateValue The partial state value to resolve.
       */
      function resolveStateValue(rootNode, stateValue) {
        var allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
        return getStateValue(rootNode, Array.from(allStateNodes));
      }
      function isMachineSnapshot(value) {
        return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
      }
      var machineSnapshotMatches = function matches(testValue) {
        return matchesState(testValue, this.value);
      };
      var machineSnapshotHasTag = function hasTag(tag) {
        return this.tags.has(tag);
      };
      var machineSnapshotCan = function can(event) {
        var transitionData = this.machine.getTransitionData(this, event);
        return !!(transitionData != null && transitionData.length) &&
        // Check that at least one transition is not forbidden
        transitionData.some(function (t) {
          return t.target !== undefined || t.actions.length;
        });
      };
      var machineSnapshotToJSON = function toJSON() {
        var nodes = this._nodes,
          tags = this.tags,
          machine = this.machine,
          getMeta = this.getMeta,
          toJSON = this.toJSON,
          can = this.can,
          hasTag = this.hasTag,
          matches = this.matches,
          jsonValues = _objectWithoutPropertiesLoose(this, _excluded);
        return _extends({}, jsonValues, {
          tags: Array.from(tags)
        });
      };
      var machineSnapshotGetMeta = function getMeta() {
        return this._nodes.reduce(function (acc, stateNode) {
          if (stateNode.meta !== undefined) {
            acc[stateNode.id] = stateNode.meta;
          }
          return acc;
        }, {});
      };
      function createMachineSnapshot(config, machine) {
        return {
          status: config.status,
          output: config.output,
          error: config.error,
          machine: machine,
          context: config.context,
          _nodes: config._nodes,
          value: getStateValue(machine.root, config._nodes),
          tags: new Set(config._nodes.flatMap(function (sn) {
            return sn.tags;
          })),
          children: config.children,
          historyValue: config.historyValue || {},
          matches: machineSnapshotMatches,
          hasTag: machineSnapshotHasTag,
          can: machineSnapshotCan,
          getMeta: machineSnapshotGetMeta,
          toJSON: machineSnapshotToJSON
        };
      }
      function cloneMachineSnapshot(snapshot, config) {
        if (config === void 0) {
          config = {};
        }
        return createMachineSnapshot(_extends({}, snapshot, config), snapshot.machine);
      }
      function serializeHistoryValue(historyValue) {
        if (typeof historyValue !== 'object' || historyValue === null) {
          return {};
        }
        var result = {};
        for (var key in historyValue) {
          var value = historyValue[key];
          if (Array.isArray(value)) {
            result[key] = value.map(function (item) {
              return {
                id: item.id
              };
            });
          }
        }
        return result;
      }
      function _getPersistedSnapshot(snapshot, options) {
        var nodes = snapshot._nodes,
          tags = snapshot.tags,
          machine = snapshot.machine,
          children = snapshot.children,
          context = snapshot.context,
          can = snapshot.can,
          hasTag = snapshot.hasTag,
          matches = snapshot.matches,
          getMeta = snapshot.getMeta,
          toJSON = snapshot.toJSON,
          jsonValues = _objectWithoutPropertiesLoose(snapshot, _excluded2);
        var childrenJson = {};
        for (var id in children) {
          var child = children[id];
          childrenJson[id] = {
            snapshot: child.getPersistedSnapshot(options),
            src: child.src,
            systemId: child.systemId,
            syncSnapshot: child._syncSnapshot
          };
        }
        var persisted = _extends({}, jsonValues, {
          context: persistContext(context),
          children: childrenJson,
          historyValue: serializeHistoryValue(jsonValues.historyValue)
        });
        return persisted;
      }
      function persistContext(contextPart) {
        var _copy3;
        var copy;
        for (var key in contextPart) {
          var value = contextPart[key];
          if (value && typeof value === 'object') {
            if ('sessionId' in value && 'send' in value && 'ref' in value) {
              var _copy;
              (_copy = copy) != null ? _copy : copy = Array.isArray(contextPart) ? contextPart.slice() : _extends({}, contextPart);
              copy[key] = {
                xstate$$type: $$ACTOR_TYPE,
                id: value.id
              };
            } else {
              var result = persistContext(value);
              if (result !== value) {
                var _copy2;
                (_copy2 = copy) != null ? _copy2 : copy = Array.isArray(contextPart) ? contextPart.slice() : _extends({}, contextPart);
                copy[key] = result;
              }
            }
          }
        }
        return (_copy3 = copy) != null ? _copy3 : contextPart;
      }
      function resolveRaise(_, snapshot, args, actionParams, _ref19, _ref20) {
        var eventOrExpr = _ref19.event,
          id = _ref19.id,
          delay = _ref19.delay;
        var internalQueue = _ref20.internalQueue;
        var delaysMap = snapshot.machine.implementations.delays;
        if (typeof eventOrExpr === 'string') {
          throw new Error(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          "Only event objects may be used with raise; use raise({ type: \"" + eventOrExpr + "\" }) instead");
        }
        var resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
        var resolvedDelay;
        if (typeof delay === 'string') {
          var configDelay = delaysMap && delaysMap[delay];
          resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;
        } else {
          resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;
        }
        if (typeof resolvedDelay !== 'number') {
          internalQueue.push(resolvedEvent);
        }
        return [snapshot, {
          event: resolvedEvent,
          id: id,
          delay: resolvedDelay
        }, undefined];
      }
      function executeRaise(actorScope, params) {
        var event = params.event,
          delay = params.delay,
          id = params.id;
        if (typeof delay === 'number') {
          actorScope.defer(function () {
            var self = actorScope.self;
            actorScope.system.scheduler.schedule(self, self, event, delay, id);
          });
          return;
        }
      }
      /**
       * Raises an event. This places the event in the internal event queue, so that
       * the event is immediately consumed by the machine in the current step.
       *
       * @param eventType The event to raise.
       */
      function raise(eventOrExpr, options) {
        function raise(_args, _params) {}
        raise.type = 'xstate.raise';
        raise.event = eventOrExpr;
        raise.id = options == null ? void 0 : options.id;
        raise.delay = options == null ? void 0 : options.delay;
        raise.resolve = resolveRaise;
        raise.execute = executeRaise;
        return raise;
      }
      function createSpawner(actorScope, _ref26, event, spawnedChildren) {
        var machine = _ref26.machine,
          context = _ref26.context;
        var spawn = function spawn(src, options) {
          if (typeof src === 'string') {
            var logic = resolveReferencedActor(machine, src);
            if (!logic) {
              throw new Error("Actor logic '" + src + "' not implemented in machine '" + machine.id + "'");
            }
            var actorRef = createActor(logic, {
              id: options == null ? void 0 : options.id,
              parent: actorScope.self,
              syncSnapshot: options == null ? void 0 : options.syncSnapshot,
              input: typeof (options == null ? void 0 : options.input) === 'function' ? options.input({
                context: context,
                event: event,
                self: actorScope.self
              }) : options == null ? void 0 : options.input,
              src: src,
              systemId: options == null ? void 0 : options.systemId
            });
            spawnedChildren[actorRef.id] = actorRef;
            return actorRef;
          } else {
            var _actorRef = createActor(src, {
              id: options == null ? void 0 : options.id,
              parent: actorScope.self,
              syncSnapshot: options == null ? void 0 : options.syncSnapshot,
              input: options == null ? void 0 : options.input,
              src: src,
              systemId: options == null ? void 0 : options.systemId
            });
            return _actorRef;
          }
        };
        return function (src, options) {
          var actorRef = spawn(src, options); // TODO: fix types
          spawnedChildren[actorRef.id] = actorRef;
          actorScope.defer(function () {
            if (actorRef._processingStatus === ProcessingStatus.Stopped) {
              return;
            }
            actorRef.start();
          });
          return actorRef;
        };
      }
      function resolveAssign(actorScope, snapshot, actionArgs, actionParams, _ref27) {
        var assignment = _ref27.assignment;
        if (!snapshot.context) {
          throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
        }
        var spawnedChildren = {};
        var assignArgs = {
          context: snapshot.context,
          event: actionArgs.event,
          spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),
          self: actorScope.self,
          system: actorScope.system
        };
        var partialUpdate = {};
        if (typeof assignment === 'function') {
          partialUpdate = assignment(assignArgs, actionParams);
        } else {
          for (var _i3 = 0, _Object$keys3 = Object.keys(assignment); _i3 < _Object$keys3.length; _i3++) {
            var key = _Object$keys3[_i3];
            var propAssignment = assignment[key];
            partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs, actionParams) : propAssignment;
          }
        }
        var updatedContext = Object.assign({}, snapshot.context, partialUpdate);
        return [cloneMachineSnapshot(snapshot, {
          context: updatedContext,
          children: Object.keys(spawnedChildren).length ? _extends({}, snapshot.children, spawnedChildren) : snapshot.children
        }), undefined, undefined];
      }
      /**
       * Updates the current context of the machine.
       *
       * @example
       *
       * ```ts
       * import { createMachine, assign } from 'xstate';
       *
       * const countMachine = createMachine({
       *   context: {
       *     count: 0,
       *     message: ''
       *   },
       *   on: {
       *     inc: {
       *       actions: assign({
       *         count: ({ context }) => context.count + 1
       *       })
       *     },
       *     updateMessage: {
       *       actions: assign(({ context, event }) => {
       *         return {
       *           message: event.message.trim()
       *         };
       *       })
       *     }
       *   }
       * });
       * ```
       *
       * @param assignment An object that represents the partial context to update, or
       *   a function that returns an object that represents the partial context to
       *   update.
       */
      function assign(assignment) {
        function assign(_args, _params) {}
        assign.type = 'xstate.assign';
        assign.assignment = assignment;
        assign.resolve = resolveAssign;
        return assign;
      }
      var cache = new WeakMap();
      function memo(object, key, fn) {
        var memoizedData = cache.get(object);
        if (!memoizedData) {
          var _memoizedData;
          memoizedData = (_memoizedData = {}, _memoizedData[key] = fn(), _memoizedData);
          cache.set(object, memoizedData);
        } else if (!(key in memoizedData)) {
          memoizedData[key] = fn();
        }
        return memoizedData[key];
      }
      var EMPTY_OBJECT = {};
      var toSerializableAction = function toSerializableAction(action) {
        if (typeof action === 'string') {
          return {
            type: action
          };
        }
        if (typeof action === 'function') {
          if ('resolve' in action) {
            return {
              type: action.type
            };
          }
          return {
            type: action.name
          };
        }
        return action;
      };
      var StateNode = /*#__PURE__*/function () {
        function StateNode(config, options) {
          var _this4 = this;
          this.config = config;
          /**
           * The relative key of the state node, which represents its location in the
           * overall state value.
           */
          this.key = void 0;
          /** The unique ID of the state node. */
          this.id = void 0;
          /**
           * The type of this state node:
           *
           * - `'atomic'` - no child state nodes
           * - `'compound'` - nested child state nodes (XOR)
           * - `'parallel'` - orthogonal nested child state nodes (AND)
           * - `'history'` - history state node
           * - `'final'` - final state node
           */
          this.type = void 0;
          /** The string path from the root machine node to this node. */
          this.path = void 0;
          /** The child state nodes. */
          this.states = void 0;
          /**
           * The type of history on this state node. Can be:
           *
           * - `'shallow'` - recalls only top-level historical state value
           * - `'deep'` - recalls historical state value at all levels
           */
          this.history = void 0;
          /** The action(s) to be executed upon entering the state node. */
          this.entry = void 0;
          /** The action(s) to be executed upon exiting the state node. */
          this.exit = void 0;
          /** The parent state node. */
          this.parent = void 0;
          /** The root machine node. */
          this.machine = void 0;
          /**
           * The meta data associated with this state node, which will be returned in
           * State instances.
           */
          this.meta = void 0;
          /**
           * The output data sent with the "xstate.done.state._id_" event if this is a
           * final state node.
           */
          this.output = void 0;
          /**
           * The order this state node appears. Corresponds to the implicit document
           * order.
           */
          this.order = -1;
          this.description = void 0;
          this.tags = [];
          this.transitions = void 0;
          this.always = void 0;
          this.parent = options._parent;
          this.key = options._key;
          this.machine = options._machine;
          this.path = this.parent ? this.parent.path.concat(this.key) : [];
          this.id = this.config.id || [this.machine.id].concat(this.path).join(STATE_DELIMITER);
          this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
          this.description = this.config.description;
          this.order = this.machine.idMap.size;
          this.machine.idMap.set(this.id, this);
          this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) {
            var stateNode = new StateNode(stateConfig, {
              _parent: _this4,
              _key: key,
              _machine: _this4.machine
            });
            return stateNode;
          }) : EMPTY_OBJECT;
          if (this.type === 'compound' && !this.config.initial) {
            throw new Error("No initial state specified for compound state node \"#" + this.id + "\". Try adding { initial: \"" + Object.keys(this.states)[0] + "\" } to the state config.");
          }

          // History config
          this.history = this.config.history === true ? 'shallow' : this.config.history || false;
          this.entry = toArray(this.config.entry).slice();
          this.exit = toArray(this.config.exit).slice();
          this.meta = this.config.meta;
          this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
          this.tags = toArray(config.tags).slice();
        }

        /** @internal */
        var _proto3 = StateNode.prototype;
        _proto3._initialize = function _initialize() {
          var _this5 = this;
          this.transitions = formatTransitions(this);
          if (this.config.always) {
            this.always = toTransitionConfigArray(this.config.always).map(function (t) {
              return formatTransition(_this5, NULL_EVENT, t);
            });
          }
          Object.keys(this.states).forEach(function (key) {
            _this5.states[key]._initialize();
          });
        }

        /** The well-structured state node definition. */;
        /** @internal */
        _proto3.toJSON = function toJSON() {
          return this.definition;
        }

        /** The logic invoked as actors by this state node. */;
        /** @internal */
        _proto3.next = function next(snapshot, event) {
          var _this6 = this;
          var eventType = event.type;
          var actions = [];
          var selectedTransition;
          var candidates = memo(this, "candidates-" + eventType, function () {
            return getCandidates(_this6, eventType);
          });
          for (var _iterator48 = _createForOfIteratorHelperLoose(candidates), _step48; !(_step48 = _iterator48()).done;) {
            var candidate = _step48.value;
            var guard = candidate.guard;
            var resolvedContext = snapshot.context;
            var guardPassed = false;
            try {
              guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
            } catch (err) {
              var guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;
              throw new Error("Unable to evaluate guard " + (guardType ? "'" + guardType + "' " : '') + "in transition for event '" + eventType + "' in state node '" + this.id + "':\n" + err.message);
            }
            if (guardPassed) {
              actions.push.apply(actions, candidate.actions);
              selectedTransition = candidate;
              break;
            }
          }
          return selectedTransition ? [selectedTransition] : undefined;
        }

        /** All the event types accepted by this state node and its descendants. */;
        _createClass(StateNode, [{
          key: "definition",
          get: function get() {
            var _this7 = this;
            return {
              id: this.id,
              key: this.key,
              version: this.machine.version,
              type: this.type,
              initial: this.initial ? {
                target: this.initial.target,
                source: this,
                actions: this.initial.actions.map(toSerializableAction),
                eventType: null,
                reenter: false,
                toJSON: function toJSON() {
                  return {
                    target: _this7.initial.target.map(function (t) {
                      return "#" + t.id;
                    }),
                    source: "#" + _this7.id,
                    actions: _this7.initial.actions.map(toSerializableAction),
                    eventType: null
                  };
                }
              } : undefined,
              history: this.history,
              states: mapValues(this.states, function (state) {
                return state.definition;
              }),
              on: this.on,
              transitions: Array.from(this.transitions.values()).flat().map(function (t) {
                return _extends({}, t, {
                  actions: t.actions.map(toSerializableAction)
                });
              }),
              entry: this.entry.map(toSerializableAction),
              exit: this.exit.map(toSerializableAction),
              meta: this.meta,
              order: this.order || -1,
              output: this.output,
              invoke: this.invoke,
              description: this.description,
              tags: this.tags
            };
          }
        }, {
          key: "invoke",
          get: function get() {
            var _this8 = this;
            return memo(this, 'invoke', function () {
              return toArray(_this8.config.invoke).map(function (invokeConfig, i) {
                var _invokeConfig$id;
                var src = invokeConfig.src,
                  systemId = invokeConfig.systemId;
                var resolvedId = (_invokeConfig$id = invokeConfig.id) != null ? _invokeConfig$id : createInvokeId(_this8.id, i);
                var sourceName = typeof src === 'string' ? src : "xstate.invoke." + createInvokeId(_this8.id, i);
                return _extends({}, invokeConfig, {
                  src: sourceName,
                  id: resolvedId,
                  systemId: systemId,
                  toJSON: function toJSON() {
                    var onDone = invokeConfig.onDone,
                      onError = invokeConfig.onError,
                      invokeDefValues = _objectWithoutPropertiesLoose(invokeConfig, _excluded5);
                    return _extends({}, invokeDefValues, {
                      type: 'xstate.invoke',
                      src: sourceName,
                      id: resolvedId
                    });
                  }
                });
              });
            });
          }

          /** The mapping of events to transitions. */
        }, {
          key: "on",
          get: function get() {
            var _this9 = this;
            return memo(this, 'on', function () {
              var transitions = _this9.transitions;
              return Array.from(transitions).flatMap(function (_ref28) {
                var descriptor = _ref28[0],
                  t = _ref28[1];
                return t.map(function (t) {
                  return [descriptor, t];
                });
              }).reduce(function (map, _ref29) {
                var descriptor = _ref29[0],
                  transition = _ref29[1];
                map[descriptor] = map[descriptor] || [];
                map[descriptor].push(transition);
                return map;
              }, {});
            });
          }
        }, {
          key: "after",
          get: function get() {
            var _this10 = this;
            return memo(this, 'delayedTransitions', function () {
              return getDelayedTransitions(_this10);
            });
          }
        }, {
          key: "initial",
          get: function get() {
            var _this11 = this;
            return memo(this, 'initial', function () {
              return formatInitialTransition(_this11, _this11.config.initial);
            });
          }
        }, {
          key: "events",
          get: function get() {
            var _this12 = this;
            return memo(this, 'events', function () {
              var states = _this12.states;
              var events = new Set(_this12.ownEvents);
              if (states) {
                for (var _i4 = 0, _Object$keys4 = Object.keys(states); _i4 < _Object$keys4.length; _i4++) {
                  var stateId = _Object$keys4[_i4];
                  var state = states[stateId];
                  if (state.states) {
                    for (var _iterator49 = _createForOfIteratorHelperLoose(state.events), _step49; !(_step49 = _iterator49()).done;) {
                      var event = _step49.value;
                      events.add("" + event);
                    }
                  }
                }
              }
              return Array.from(events);
            });
          }

          /**
           * All the events that have transitions directly from this state node.
           *
           * Excludes any inert events.
           */
        }, {
          key: "ownEvents",
          get: function get() {
            var _this13 = this;
            var keys = Object.keys(Object.fromEntries(this.transitions));
            var events = new Set(keys.filter(function (descriptor) {
              return _this13.transitions.get(descriptor).some(function (transition) {
                return !(!transition.target && !transition.actions.length && !transition.reenter);
              });
            }));
            return Array.from(events);
          }
        }]);
        return StateNode;
      }();
      var STATE_IDENTIFIER = '#';
      var StateMachine = /*#__PURE__*/function () {
        function StateMachine(config, implementations) {
          var _implementations$acto, _implementations$acti, _implementations$dela, _implementations$guar;
          this.config = config;
          /** The machine's own version. */
          this.version = void 0;
          this.schemas = void 0;
          this.implementations = void 0;
          /** @internal */
          this.__xstatenode = true;
          /** @internal */
          this.idMap = new Map();
          this.root = void 0;
          this.id = void 0;
          this.states = void 0;
          this.events = void 0;
          this.id = config.id || '(machine)';
          this.implementations = {
            actors: (_implementations$acto = implementations == null ? void 0 : implementations.actors) != null ? _implementations$acto : {},
            actions: (_implementations$acti = implementations == null ? void 0 : implementations.actions) != null ? _implementations$acti : {},
            delays: (_implementations$dela = implementations == null ? void 0 : implementations.delays) != null ? _implementations$dela : {},
            guards: (_implementations$guar = implementations == null ? void 0 : implementations.guards) != null ? _implementations$guar : {}
          };
          this.version = this.config.version;
          this.schemas = this.config.schemas;
          this.transition = this.transition.bind(this);
          this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
          this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
          this.restoreSnapshot = this.restoreSnapshot.bind(this);
          this.start = this.start.bind(this);
          this.root = new StateNode(config, {
            _key: this.id,
            _machine: this
          });
          this.root._initialize();
          this.states = this.root.states; // TODO: remove!
          this.events = this.root.events;
        }

        /**
         * Clones this state machine with the provided implementations.
         *
         * @param implementations Options (`actions`, `guards`, `actors`, `delays`) to
         *   recursively merge with the existing options.
         * @returns A new `StateMachine` instance with the provided implementations.
         */
        var _proto4 = StateMachine.prototype;
        _proto4.provide = function provide(implementations) {
          var _this$implementations = this.implementations,
            actions = _this$implementations.actions,
            guards = _this$implementations.guards,
            actors = _this$implementations.actors,
            delays = _this$implementations.delays;
          return new StateMachine(this.config, {
            actions: _extends({}, actions, implementations.actions),
            guards: _extends({}, guards, implementations.guards),
            actors: _extends({}, actors, implementations.actors),
            delays: _extends({}, delays, implementations.delays)
          });
        };
        _proto4.resolveState = function resolveState(config) {
          var resolvedStateValue = resolveStateValue(this.root, config.value);
          var nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
          return createMachineSnapshot({
            _nodes: Array.from(nodeSet),
            context: config.context || {},
            children: {},
            status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
            output: config.output,
            error: config.error,
            historyValue: config.historyValue
          }, this);
        }

        /**
         * Determines the next snapshot given the current `snapshot` and received
         * `event`. Calculates a full macrostep from all microsteps.
         *
         * @param snapshot The current snapshot
         * @param event The received event
         */;
        _proto4.transition = function transition(snapshot, event, actorScope) {
          return macrostep(snapshot, event, actorScope, []).snapshot;
        }

        /**
         * Determines the next state given the current `state` and `event`. Calculates
         * a microstep.
         *
         * @param state The current state
         * @param event The received event
         */;
        _proto4.microstep = function microstep(snapshot, event, actorScope) {
          return macrostep(snapshot, event, actorScope, []).microstates;
        };
        _proto4.getTransitionData = function getTransitionData(snapshot, event) {
          return transitionNode(this.root, snapshot.value, snapshot, event) || [];
        }

        /**
         * The initial state _before_ evaluating any microsteps. This "pre-initial"
         * state is provided to initial actions executed in the initial state.
         */;
        _proto4.getPreInitialState = function getPreInitialState(actorScope, initEvent, internalQueue) {
          var context = this.config.context;
          var preInitial = createMachineSnapshot({
            context: typeof context !== 'function' && context ? context : {},
            _nodes: [this.root],
            children: {},
            status: 'active'
          }, this);
          if (typeof context === 'function') {
            var assignment = function assignment(_ref30) {
              var spawn = _ref30.spawn,
                event = _ref30.event,
                self = _ref30.self;
              return context({
                spawn: spawn,
                input: event.input,
                self: self
              });
            };
            return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, undefined);
          }
          return preInitial;
        }

        /**
         * Returns the initial `State` instance, with reference to `self` as an
         * `ActorRef`.
         */;
        _proto4.getInitialSnapshot = function getInitialSnapshot(actorScope, input) {
          var initEvent = createInitEvent(input); // TODO: fix;
          var internalQueue = [];
          var preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);
          var nextState = microstep([{
            target: Array.from(getInitialStateNodes(this.root)),
            source: this.root,
            reenter: true,
            actions: [],
            eventType: null,
            toJSON: null // TODO: fix
          }], preInitialState, actorScope, initEvent, true, internalQueue);
          var _macrostep = macrostep(nextState, initEvent, actorScope, internalQueue),
            macroState = _macrostep.snapshot;
          return macroState;
        };
        _proto4.start = function start(snapshot) {
          Object.values(snapshot.children).forEach(function (child) {
            if (child.getSnapshot().status === 'active') {
              child.start();
            }
          });
        };
        _proto4.getStateNodeById = function getStateNodeById(stateId) {
          var fullPath = toStatePath(stateId);
          var relativePath = fullPath.slice(1);
          var resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
          var stateNode = this.idMap.get(resolvedStateId);
          if (!stateNode) {
            throw new Error("Child state node '#" + resolvedStateId + "' does not exist on machine '" + this.id + "'");
          }
          return getStateNodeByPath(stateNode, relativePath);
        };
        _proto4.toJSON = function toJSON() {
          return this.definition;
        };
        _proto4.getPersistedSnapshot = function getPersistedSnapshot(snapshot, options) {
          return _getPersistedSnapshot(snapshot, options);
        };
        _proto4.restoreSnapshot = function restoreSnapshot(snapshot, _actorScope) {
          var _this14 = this;
          var children = {};
          var snapshotChildren = snapshot.children;
          Object.keys(snapshotChildren).forEach(function (actorId) {
            var actorData = snapshotChildren[actorId];
            var childState = actorData.snapshot;
            var src = actorData.src;
            var logic = typeof src === 'string' ? resolveReferencedActor(_this14, src) : src;
            if (!logic) {
              return;
            }
            var actorRef = createActor(logic, {
              id: actorId,
              parent: _actorScope.self,
              syncSnapshot: actorData.syncSnapshot,
              snapshot: childState,
              src: src,
              systemId: actorData.systemId
            });
            children[actorId] = actorRef;
          });
          function resolveHistoryReferencedState(root, referenced) {
            if (referenced instanceof StateNode) {
              return referenced;
            }
            try {
              return root.machine.getStateNodeById(referenced.id);
            } catch (_unused2) {}
          }
          function reviveHistoryValue(root, historyValue) {
            if (!historyValue || typeof historyValue !== 'object') {
              return {};
            }
            var revived = {};
            for (var key in historyValue) {
              var arr = historyValue[key];
              for (var _iterator50 = _createForOfIteratorHelperLoose(arr), _step50; !(_step50 = _iterator50()).done;) {
                var _revived$key;
                var item = _step50.value;
                var resolved = resolveHistoryReferencedState(root, item);
                if (!resolved) {
                  continue;
                }
                (_revived$key = revived[key]) != null ? _revived$key : revived[key] = [];
                revived[key].push(resolved);
              }
            }
            return revived;
          }
          var revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);
          var restoredSnapshot = createMachineSnapshot(_extends({}, snapshot, {
            children: children,
            _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),
            historyValue: revivedHistoryValue
          }), this);
          var seen = new Set();
          function reviveContext(contextPart, children) {
            if (seen.has(contextPart)) {
              return;
            }
            seen.add(contextPart);
            for (var key in contextPart) {
              var value = contextPart[key];
              if (value && typeof value === 'object') {
                if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {
                  contextPart[key] = children[value.id];
                  continue;
                }
                reviveContext(value, children);
              }
            }
          }
          reviveContext(restoredSnapshot.context, children);
          return restoredSnapshot;
        };
        _createClass(StateMachine, [{
          key: "definition",
          get: function get() {
            return this.root.definition;
          }
        }]);
        return StateMachine;
      }();
      function resolveEmit(_, snapshot, args, actionParams, _ref31) {
        var eventOrExpr = _ref31.event;
        var resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
        return [snapshot, {
          event: resolvedEvent
        }, undefined];
      }
      function executeEmit(actorScope, _ref32) {
        var event = _ref32.event;
        actorScope.defer(function () {
          return actorScope.emit(event);
        });
      }
      /**
       * Emits an event to event handlers registered on the actor via `actor.on(event,
       * handler)`.
       *
       * @example
       *
       * ```ts
       * import { emit } from 'xstate';
       *
       * const machine = createMachine({
       *   // ...
       *   on: {
       *     something: {
       *       actions: emit({
       *         type: 'emitted',
       *         some: 'data'
       *       })
       *     }
       *   }
       *   // ...
       * });
       *
       * const actor = createActor(machine).start();
       *
       * actor.on('emitted', (event) => {
       *   console.log(event);
       * });
       *
       * actor.send({ type: 'something' });
       * // logs:
       * // {
       * //   type: 'emitted',
       * //   some: 'data'
       * // }
       * ```
       */
      function emit /** The event to emit, or an expression that returns an event to emit. */(eventOrExpr) {
        function emit(_args, _params) {}
        emit.type = 'xstate.emit';
        emit.event = eventOrExpr;
        emit.resolve = resolveEmit;
        emit.execute = executeEmit;
        return emit;
      }

      // this is needed to make JSDoc `@link` work properly

      /**
       * @remarks
       * `T | unknown` reduces to `unknown` and that can be problematic when it comes
       * to contextual typing. It especially is a problem when the union has a
       * function member, like here:
       *
       * ```ts
       * declare function test(
       *   cbOrVal: ((arg: number) => unknown) | unknown
       * ): void;
       * test((arg) => {}); // oops, implicit any
       * ```
       *
       * This type can be used to avoid this problem. This union represents the same
       * value space as `unknown`.
       */

      // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887

      // @TODO: we can't use native `NoInfer` as we need those:
      // https://github.com/microsoft/TypeScript/pull/61092
      // https://github.com/microsoft/TypeScript/pull/61077
      // but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed

      /** @deprecated Use the built-in `NoInfer` type instead */

      /** The full definition of an event, with a string `type`. */

      /**
       * The string or object representing the state value relative to the parent
       * state node.
       *
       * @remarks
       * - For a child atomic state node, this is a string, e.g., `"pending"`.
       * - For complex state nodes, this is an object, e.g., `{ success:
       *   "someChildState" }`.
       */

      /** @deprecated Use `AnyMachineSnapshot` instead */

      // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
      /** @ignore */

      var SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
        SpecialTargets['Parent'] = '#_parent';
        SpecialTargets['Internal'] = '#_internal';
        return SpecialTargets;
      }({});

      /** @deprecated Use `AnyActor` instead. */

      // Based on RxJS types

      // TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic

      /** @deprecated Use `Actor<T>` instead. */

      /**
       * Represents logic which can be used by an actor.
       *
       * @template TSnapshot - The type of the snapshot.
       * @template TEvent - The type of the event object.
       * @template TInput - The type of the input.
       * @template TSystem - The type of the actor system.
       */

      /** @deprecated */

      // TODO: cover all that can be actually returned

      function resolveSendTo(actorScope, snapshot, args, actionParams, _ref33, extra) {
        var to = _ref33.to,
          eventOrExpr = _ref33.event,
          id = _ref33.id,
          delay = _ref33.delay;
        var delaysMap = snapshot.machine.implementations.delays;
        if (typeof eventOrExpr === 'string') {
          throw new Error(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          "Only event objects may be used with sendTo; use sendTo({ type: \"" + eventOrExpr + "\" }) instead");
        }
        var resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
        var resolvedDelay;
        if (typeof delay === 'string') {
          var configDelay = delaysMap && delaysMap[delay];
          resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;
        } else {
          resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;
        }
        var resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;
        var targetActorRef;
        if (typeof resolvedTarget === 'string') {
          // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
          if (resolvedTarget === SpecialTargets.Parent) {
            targetActorRef = actorScope.self._parent;
          }
          // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
          else if (resolvedTarget === SpecialTargets.Internal) {
            targetActorRef = actorScope.self;
          } else if (resolvedTarget.startsWith('#_')) {
            // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
            // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.
            targetActorRef = snapshot.children[resolvedTarget.slice(2)];
          } else {
            var _extra$deferredActorI;
            targetActorRef = (_extra$deferredActorI = extra.deferredActorIds) != null && _extra$deferredActorI.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];
          }
          if (!targetActorRef) {
            throw new Error("Unable to send event to actor '" + resolvedTarget + "' from machine '" + snapshot.machine.id + "'.");
          }
        } else {
          targetActorRef = resolvedTarget || actorScope.self;
        }
        return [snapshot, {
          to: targetActorRef,
          targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,
          event: resolvedEvent,
          id: id,
          delay: resolvedDelay
        }, undefined];
      }
      function retryResolveSendTo(_, snapshot, params) {
        if (typeof params.to === 'string') {
          params.to = snapshot.children[params.to];
        }
      }
      function executeSendTo(actorScope, params) {
        // this forms an outgoing events queue
        // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender
        actorScope.defer(function () {
          var to = params.to,
            event = params.event,
            delay = params.delay,
            id = params.id;
          if (typeof delay === 'number') {
            actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);
            return;
          }
          actorScope.system._relay(actorScope.self,
          // at this point, in a deferred task, it should already be mutated by retryResolveSendTo
          // if it initially started as a string
          to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);
        });
      }
      /**
       * Sends an event to an actor.
       *
       * @param actor The `ActorRef` to send the event to.
       * @param event The event to send, or an expression that evaluates to the event
       *   to send
       * @param options Send action options
       *
       *   - `id` - The unique send event identifier (used with `cancel()`).
       *   - `delay` - The number of milliseconds to delay the sending of the event.
       */
      function sendTo(to, eventOrExpr, options) {
        function sendTo(_args, _params) {}
        sendTo.type = 'xstate.sendTo';
        sendTo.to = to;
        sendTo.event = eventOrExpr;
        sendTo.id = options == null ? void 0 : options.id;
        sendTo.delay = options == null ? void 0 : options.delay;
        sendTo.resolve = resolveSendTo;
        sendTo.retryResolve = retryResolveSendTo;
        sendTo.execute = executeSendTo;
        return sendTo;
      }

      /**
       * Sends an event to this machine's parent.
       *
       * @param event The event to send to the parent machine.
       * @param options Options to pass into the send event.
       */
      function sendParent(event, options) {
        return sendTo(SpecialTargets.Parent, event, options);
      }
      function resolveEnqueueActions(actorScope, snapshot, args, actionParams, _ref35) {
        var collect = _ref35.collect;
        var actions = [];
        var enqueue = function enqueue(action) {
          actions.push(action);
        };
        enqueue.assign = function () {
          actions.push(assign.apply(void 0, arguments));
        };
        enqueue.cancel = function () {
          actions.push(cancel.apply(void 0, arguments));
        };
        enqueue.raise = function () {
          // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)
          // then it fails to typecheck that because `...args` use `string` in place of `TDelay`
          actions.push(raise.apply(void 0, arguments));
        };
        enqueue.sendTo = function () {
          // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)
          // then it fails to typecheck that because `...args` use `string` in place of `TDelay
          actions.push(sendTo.apply(void 0, arguments));
        };
        enqueue.sendParent = function () {
          actions.push(sendParent.apply(void 0, arguments));
        };
        enqueue.spawnChild = function () {
          actions.push(spawnChild.apply(void 0, arguments));
        };
        enqueue.stopChild = function () {
          actions.push(stopChild.apply(void 0, arguments));
        };
        enqueue.emit = function () {
          actions.push(emit.apply(void 0, arguments));
        };
        collect({
          context: args.context,
          event: args.event,
          enqueue: enqueue,
          check: function check(guard) {
            return evaluateGuard(guard, snapshot.context, args.event, snapshot);
          },
          self: actorScope.self,
          system: actorScope.system
        }, actionParams);
        return [snapshot, undefined, actions];
      }
      /**
       * Creates an action object that will execute actions that are queued by the
       * `enqueue(action)` function.
       *
       * @example
       *
       * ```ts
       * import { createMachine, enqueueActions } from 'xstate';
       *
       * const machine = createMachine({
       *   entry: enqueueActions(({ enqueue, check }) => {
       *     enqueue.assign({ count: 0 });
       *
       *     if (check('someGuard')) {
       *       enqueue.assign({ count: 1 });
       *     }
       *
       *     enqueue('someAction');
       *   })
       * });
       * ```
       */
      function enqueueActions(collect) {
        function enqueueActions(_args, _params) {}
        enqueueActions.type = 'xstate.enqueueActions';
        enqueueActions.collect = collect;
        enqueueActions.resolve = resolveEnqueueActions;
        return enqueueActions;
      }
      function resolveLog(_, snapshot, actionArgs, actionParams, _ref36) {
        var value = _ref36.value,
          label = _ref36.label;
        return [snapshot, {
          value: typeof value === 'function' ? value(actionArgs, actionParams) : value,
          label: label
        }, undefined];
      }
      function executeLog(_ref37, _ref38) {
        var logger = _ref37.logger;
        var value = _ref38.value,
          label = _ref38.label;
        if (label) {
          logger(label, value);
        } else {
          logger(value);
        }
      }
      /**
       * @param expr The expression function to evaluate which will be logged. Takes
       *   in 2 arguments:
       *
       *   - `ctx` - the current state context
       *   - `event` - the event that caused this action to be executed.
       *
       * @param label The label to give to the logged expression.
       */
      function log(value, label) {
        if (value === void 0) {
          value = function value(_ref39) {
            var context = _ref39.context,
              event = _ref39.event;
            return {
              context: context,
              event: event
            };
          };
        }
        function log(_args, _params) {}
        log.type = 'xstate.log';
        log.value = value;
        log.label = label;
        log.resolve = resolveLog;
        log.execute = executeLog;
        return log;
      }

      /**
       * Creates a state machine (statechart) with the given configuration.
       *
       * The state machine represents the pure logic of a state machine actor.
       *
       * @example
       *
       * ```ts
       * import { createMachine } from 'xstate';
       *
       * const lightMachine = createMachine({
       *   id: 'light',
       *   initial: 'green',
       *   states: {
       *     green: {
       *       on: {
       *         TIMER: { target: 'yellow' }
       *       }
       *     },
       *     yellow: {
       *       on: {
       *         TIMER: { target: 'red' }
       *       }
       *     },
       *     red: {
       *       on: {
       *         TIMER: { target: 'green' }
       *       }
       *     }
       *   }
       * });
       *
       * const lightActor = createActor(lightMachine);
       * lightActor.start();
       *
       * lightActor.send({ type: 'TIMER' });
       * ```
       *
       * @param config The state machine configuration.
       * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`
       *   to provide machine implementations instead.
       */
      function _createMachine(config, implementations) {
        return new StateMachine(config, implementations);
      }

      // at the moment we allow extra actors - ones that are not specified by `children`
      // this could be reconsidered in the future

      // used to keep only StateSchema relevant keys
      // this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs

      function setup(_ref41) {
        var schemas = _ref41.schemas,
          actors = _ref41.actors,
          actions = _ref41.actions,
          guards = _ref41.guards,
          delays = _ref41.delays;
        return {
          assign: assign,
          sendTo: sendTo,
          raise: raise,
          log: log,
          cancel: cancel,
          stopChild: stopChild,
          enqueueActions: enqueueActions,
          emit: emit,
          spawnChild: spawnChild,
          createStateConfig: function createStateConfig(config) {
            return config;
          },
          createAction: function createAction(fn) {
            return fn;
          },
          createMachine: function createMachine(config) {
            return _createMachine(_extends({}, config, {
              schemas: schemas
            }), {
              actors: actors,
              actions: actions,
              guards: guards,
              delays: delays
            });
          },
          extend: function extend(extended) {
            return setup({
              schemas: schemas,
              actors: actors,
              actions: _extends({}, actions, extended.actions),
              guards: _extends({}, guards, extended.guards),
              delays: _extends({}, delays, extended.delays)
            });
          }
        };
      }
      cclegacy._RF.pop();
      var _class;
      cclegacy._RF.push({}, "5323cLfQZ5BaqQXlFFAGaNB", "option", undefined);
      var None = /*#__PURE__*/function () {
        function None() {}
        None.getInstance = function getInstance() {
          return None.instance;
        };
        var _proto2 = None.prototype;
        _proto2.isSome = function isSome() {
          return false;
        };
        _proto2.isNone = function isNone() {
          return true;
        };
        _proto2.map = function map(_fn) {
          return none;
        };
        _proto2.andThen = function andThen(_fn) {
          return none;
        };
        _proto2.or = function or(other) {
          return other;
        };
        _proto2.orElse = function orElse(fn) {
          return fn();
        };
        _proto2.andDo = function andDo(_fn) {
          return none;
        };
        _proto2.orDo = function orDo(_fn) {
          _fn();
          return none;
        };
        _proto2.unwrapOr = function unwrapOr(defaultValue) {
          return defaultValue;
        };
        _proto2.match = function match(_someFn, noneFn) {
          return noneFn();
        };
        _proto2.filter = function filter(_predicate) {
          return none;
        };
        _proto2.toResult = function toResult(err_msg) {
          return err(err_msg != null ? err_msg : 'None.toResult called on None');
        };
        return None;
      }();
      _class = None;
      None.instance = new _class();

      /**
       * None 是单例的
       */
      var none = None.getInstance();
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "da860I1QPpI/Yr7PjjylTan", "LogBuilder", undefined);
      var LogBuilder = /*#__PURE__*/function () {
        function LogBuilder(_logger, thisArg, className, mothodName) {
          var _className, _thisArg$node$uuid;
          if (_logger === void 0) {
            _logger = logger;
          }
          if (className === void 0) {
            className = '';
          }
          if (mothodName === void 0) {
            mothodName = '';
          }
          this._contexts = {};
          this.className = '';
          this.methodName = '';
          this.logger = logger;
          this.logger = _logger;
          this.className = (_className = className) != null ? _className : thisArg == null ? void 0 : thisArg.name;
          this._contexts.nodeUuid = (_thisArg$node$uuid = thisArg == null ? void 0 : thisArg.node.uuid) != null ? _thisArg$node$uuid : '';
          this.methodName = mothodName;
        }
        var _proto = LogBuilder.prototype;
        _proto.This = function This(thisArg) {
          this.setContext('nodeUuid', thisArg.node.uuid);
          this.className = thisArg.name;
          this.setContext('funcName', this.className + "." + this.methodName);
          return this;
        };
        _proto.Class = function Class(name) {
          this.className = name;
          this.setContext('funcName', this.className + "." + this.methodName);
          return this;
        };
        _proto.Method = function Method(name) {
          this.methodName = name;
          this.setContext('funcName', this.className + "." + this.methodName);
          return this;
        };
        _proto.setContext = function setContext(key, value) {
          this._contexts[key] = value;
          return this;
        };
        _proto.debug = function debug(msg) {
          this.logger.debug(msg, this._contexts);
        };
        _proto.info = function info(msg) {
          this.logger.info(msg, this._contexts);
        };
        _proto.log = function log(msg) {
          this.logger.log(msg, this._contexts);
        };
        _proto.warn = function warn(msg) {
          this.logger.warn(msg, this._contexts);
        };
        _proto.error = function error(msg) {
          this.logger.error(msg, this._contexts);
        };
        _createClass(LogBuilder, [{
          key: "context",
          get: function get() {
            return _extends({}, this._contexts);
          }
        }]);
        return LogBuilder;
      }();
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "76640+59SVEMq+w2F8+LJss", "BaseEventCmp", undefined);

      /**
       * 事件组件基类，提供通用的事件处理功能
       * @template T - 事件模式类型
       */
      var BaseEventCmp = /*#__PURE__*/function (_Component) {
        _inheritsLoose(BaseEventCmp, _Component);
        function BaseEventCmp() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.$TSchema = null;
          _this.$TEvent = null;
          _this.$TArgs = null;
          _this.log = new LogBuilder();
          return _this;
        }
        var _proto = BaseEventCmp.prototype;
        _proto.onLoad = function onLoad() {
          var _this$log;
          (_this$log = this.log) == null || _this$log.This(this);
        }

        /**
         * 监听事件
         * @param event 事件名称
         * @param callback 事件回调函数
         * @param target 事件回调函数的执行上下文
         */;
        _proto.on = function on(event, callback, target) {
          var _this$log2, _this$log3, _this$node;
          (_this$log2 = this.log) == null || _this$log2.Method('on');
          var eventKey = event.toString();
          (_this$log3 = this.log) == null || _this$log3.log("\u6CE8\u518C\u4E8B\u4EF6\u76D1\u542C\u5668\uFF1A" + eventKey);
          (_this$node = this.node) == null || _this$node.on(eventKey, callback, target);
        }

        /**
         * 取消监听事件
         * @param event 事件名称
         * @param callback 事件回调函数
         * @param target 事件回调函数的执行上下文
         */;
        _proto.off = function off(event, callback, target) {
          var _this$log4, _this$log5, _this$node2;
          (_this$log4 = this.log) == null || _this$log4.Method('off');
          var eventKey = event.toString();
          (_this$log5 = this.log) == null || _this$log5.log("\u6CE8\u9500\u4E8B\u4EF6\u76D1\u542C\u5668\uFF1A" + eventKey);
          (_this$node2 = this.node) == null || _this$node2.off(eventKey, callback, target);
        }

        /**
         * 触发事件
         * @param event 事件名称
         * @param args 事件参数
         */;
        _proto.emit = function emit(event) {
          var _this$log6, _this$log7, _this$node3;
          (_this$log6 = this.log) == null || _this$log6.Method('emit');
          var eventKey = event.toString();
          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
            args[_key2 - 1] = arguments[_key2];
          }
          (_this$log7 = this.log) == null || _this$log7.log("\u89E6\u53D1\u4E8B\u4EF6\uFF1A" + eventKey + " " + args);
          (_this$node3 = this.node) == null || _this$node3.emit.apply(_this$node3, [eventKey].concat(args));
        }

        /**
         * 监听一次事件，触发后自动移除
         * @param event 事件名称
         * @param callback 事件回调函数
         * @param target 事件回调函数的执行上下文
         */;
        _proto.once = function once(event, callback, target) {
          var _this$log8, _this$log9, _this$node4;
          (_this$log8 = this.log) == null || _this$log8.Method('once');
          var eventKey = event.toString();
          (_this$log9 = this.log) == null || _this$log9.log("\u6CE8\u518C\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668\uFF1A" + eventKey);
          (_this$node4 = this.node) == null || _this$node4.once(eventKey, callback, target);
        };
        return BaseEventCmp;
      }(Component);
      cclegacy._RF.pop();
      var _dec, _dec2, _dec3, _dec4, _class$1;
      cclegacy._RF.push({}, "38840luhEROOovjdz0E0aXZ", "GameEventCmp", undefined);
      var ccclass = _decorator.ccclass,
        menu = _decorator.menu,
        executionOrder = _decorator.executionOrder,
        disallowMultiple = _decorator.disallowMultiple;
      var GameEventCmp = (_dec = ccclass('GameEventCmp'), _dec2 = menu('Event/GameEventCmp'), _dec3 = executionOrder(-1), _dec4 = disallowMultiple(true), _dec(_class$1 = _dec2(_class$1 = _dec3(_class$1 = _dec4(_class$1 = /*#__PURE__*/function (_ref) {
        _inheritsLoose(GameEventCmp, _ref);
        function GameEventCmp() {
          return _ref.apply(this, arguments) || this;
        }
        return GameEventCmp;
      }(BaseEventCmp)) || _class$1) || _class$1) || _class$1) || _class$1);
      cclegacy._RF.pop();
      var _dec$1, _dec2$1, _dec3$1, _dec4$1, _class$2;
      cclegacy._RF.push({}, "aa0e1eGog5K2pqxzAgUqb2Z", "LineEventCmp", undefined);
      var ccclass$1 = _decorator.ccclass,
        menu$1 = _decorator.menu,
        executionOrder$1 = _decorator.executionOrder,
        disallowMultiple$1 = _decorator.disallowMultiple;
      var LineEventCmp = (_dec$1 = ccclass$1('LineEventCmp'), _dec2$1 = menu$1('Event/LineEventCmp'), _dec3$1 = executionOrder$1(-1), _dec4$1 = disallowMultiple$1(true), _dec$1(_class$2 = _dec2$1(_class$2 = _dec3$1(_class$2 = _dec4$1(_class$2 = /*#__PURE__*/function (_BaseEventCmp) {
        _inheritsLoose(LineEventCmp, _BaseEventCmp);
        function LineEventCmp() {
          return _BaseEventCmp.apply(this, arguments) || this;
        }
        return LineEventCmp;
      }(BaseEventCmp)) || _class$2) || _class$2) || _class$2) || _class$2);
      cclegacy._RF.pop();
      var _dec$2, _dec2$2, _dec3$2, _dec4$2, _class$3;
      cclegacy._RF.push({}, "b610dD+8o1MjarBU5RSrU63", "MonsterEventCmp", undefined);
      var ccclass$2 = _decorator.ccclass,
        menu$2 = _decorator.menu,
        executionOrder$2 = _decorator.executionOrder,
        disallowMultiple$2 = _decorator.disallowMultiple;
      var MonsterEventCmp = (_dec$2 = ccclass$2('MonsterEventCmp'), _dec2$2 = menu$2('Event/MonsterEventCmp'), _dec3$2 = executionOrder$2(-1), _dec4$2 = disallowMultiple$2(true), _dec$2(_class$3 = _dec2$2(_class$3 = _dec3$2(_class$3 = _dec4$2(_class$3 = /*#__PURE__*/function (_ref) {
        _inheritsLoose(MonsterEventCmp, _ref);
        function MonsterEventCmp() {
          return _ref.apply(this, arguments) || this;
        }
        return MonsterEventCmp;
      }(BaseEventCmp)) || _class$3) || _class$3) || _class$3) || _class$3);
      cclegacy._RF.pop();
      var _dec$3, _dec2$3, _dec3$3, _dec4$3, _class$4;
      cclegacy._RF.push({}, "83102dtgkBPbI+ItXNWN9p0", "PlayerEventCmp", undefined);
      var ccclass$3 = _decorator.ccclass,
        menu$3 = _decorator.menu,
        executionOrder$3 = _decorator.executionOrder,
        disallowMultiple$3 = _decorator.disallowMultiple;
      var PlayerEventCmp = (_dec$3 = ccclass$3('PlayerEventCmp'), _dec2$3 = menu$3('Event/PlayerEventCmp'), _dec3$3 = executionOrder$3(-1), _dec4$3 = disallowMultiple$3(true), _dec$3(_class$4 = _dec2$3(_class$4 = _dec3$3(_class$4 = _dec4$3(_class$4 = /*#__PURE__*/function (_ref) {
        _inheritsLoose(PlayerEventCmp, _ref);
        function PlayerEventCmp() {
          return _ref.apply(this, arguments) || this;
        }
        return PlayerEventCmp;
      }(BaseEventCmp)) || _class$4) || _class$4) || _class$4) || _class$4);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "2e68aV05q5JHbcPfO6qVHJh", "ColliderSchema", undefined); // 扇形的碰撞事件
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "68c65gKYUJMmqw63ZW44w02", "GameSchema", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "430a1OsUSxD5In+WmCa+Fw/", "LineSchema", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "fe0aaFA4j1GrIsDzPH0ak9D", "MonsterSchema", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "1f9184tWolBE7o9jj5zD5An", "PlayerSchema", undefined);
      cclegacy._RF.pop();

      /** Detect free variable `global` from Node.js. */
      var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

      /** Detect free variable `self`. */
      var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

      /** Used as a reference to the global object. */
      var root = freeGlobal || freeSelf || Function('return this')();

      /** Built-in value references. */
      var Symbol$1 = root.Symbol;

      /** Used for built-in method references. */
      var objectProto = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty = objectProto.hasOwnProperty;

      /**
       * Used to resolve the
       * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
       * of values.
       */
      var nativeObjectToString = objectProto.toString;

      /** Built-in value references. */
      var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;

      /**
       * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
       *
       * @private
       * @param {*} value The value to query.
       * @returns {string} Returns the raw `toStringTag`.
       */
      function getRawTag(value) {
        var isOwn = hasOwnProperty.call(value, symToStringTag),
          tag = value[symToStringTag];
        try {
          value[symToStringTag] = undefined;
          var unmasked = true;
        } catch (e) {}
        var result = nativeObjectToString.call(value);
        if (unmasked) {
          if (isOwn) {
            value[symToStringTag] = tag;
          } else {
            delete value[symToStringTag];
          }
        }
        return result;
      }

      /** Used for built-in method references. */
      var objectProto$1 = Object.prototype;

      /**
       * Used to resolve the
       * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
       * of values.
       */
      var nativeObjectToString$1 = objectProto$1.toString;

      /**
       * Converts `value` to a string using `Object.prototype.toString`.
       *
       * @private
       * @param {*} value The value to convert.
       * @returns {string} Returns the converted string.
       */
      function objectToString(value) {
        return nativeObjectToString$1.call(value);
      }

      /** `Object#toString` result references. */
      var nullTag = '[object Null]',
        undefinedTag = '[object Undefined]';

      /** Built-in value references. */
      var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;

      /**
       * The base implementation of `getTag` without fallbacks for buggy environments.
       *
       * @private
       * @param {*} value The value to query.
       * @returns {string} Returns the `toStringTag`.
       */
      function baseGetTag(value) {
        if (value == null) {
          return value === undefined ? undefinedTag : nullTag;
        }
        return symToStringTag$1 && symToStringTag$1 in Object(value) ? getRawTag(value) : objectToString(value);
      }

      /**
       * Checks if `value` is object-like. A value is object-like if it's not `null`
       * and has a `typeof` result of "object".
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
       * @example
       *
       * _.isObjectLike({});
       * // => true
       *
       * _.isObjectLike([1, 2, 3]);
       * // => true
       *
       * _.isObjectLike(_.noop);
       * // => false
       *
       * _.isObjectLike(null);
       * // => false
       */
      function isObjectLike(value) {
        return value != null && typeof value == 'object';
      }

      /** `Object#toString` result references. */
      var symbolTag = '[object Symbol]';

      /**
       * Checks if `value` is classified as a `Symbol` primitive or object.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
       * @example
       *
       * _.isSymbol(Symbol.iterator);
       * // => true
       *
       * _.isSymbol('abc');
       * // => false
       */
      function isSymbol(value) {
        return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
      }

      /** Used as references for various `Number` constants. */
      var NAN = 0 / 0;

      /**
       * The base implementation of `_.toNumber` which doesn't ensure correct
       * conversions of binary, hexadecimal, or octal string values.
       *
       * @private
       * @param {*} value The value to process.
       * @returns {number} Returns the number.
       */
      function baseToNumber(value) {
        if (typeof value == 'number') {
          return value;
        }
        if (isSymbol(value)) {
          return NAN;
        }
        return +value;
      }

      /**
       * A specialized version of `_.map` for arrays without support for iteratee
       * shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array} Returns the new mapped array.
       */
      function arrayMap(array, iteratee) {
        var index = -1,
          length = array == null ? 0 : array.length,
          result = Array(length);
        while (++index < length) {
          result[index] = iteratee(array[index], index, array);
        }
        return result;
      }

      /**
       * Checks if `value` is classified as an `Array` object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an array, else `false`.
       * @example
       *
       * _.isArray([1, 2, 3]);
       * // => true
       *
       * _.isArray(document.body.children);
       * // => false
       *
       * _.isArray('abc');
       * // => false
       *
       * _.isArray(_.noop);
       * // => false
       */
      var isArray$1 = Array.isArray;

      /** Used as references for various `Number` constants. */
      var INFINITY = 1 / 0;

      /** Used to convert symbols to primitives and strings. */
      var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
        symbolToString = symbolProto ? symbolProto.toString : undefined;

      /**
       * The base implementation of `_.toString` which doesn't convert nullish
       * values to empty strings.
       *
       * @private
       * @param {*} value The value to process.
       * @returns {string} Returns the string.
       */
      function baseToString(value) {
        // Exit early for strings to avoid a performance hit in some environments.
        if (typeof value == 'string') {
          return value;
        }
        if (isArray$1(value)) {
          // Recursively convert values (susceptible to call stack limits).
          return arrayMap(value, baseToString) + '';
        }
        if (isSymbol(value)) {
          return symbolToString ? symbolToString.call(value) : '';
        }
        var result = value + '';
        return result == '0' && 1 / value == -INFINITY ? '-0' : result;
      }

      /**
       * Creates a function that performs a mathematical operation on two values.
       *
       * @private
       * @param {Function} operator The function to perform the operation.
       * @param {number} [defaultValue] The value used for `undefined` arguments.
       * @returns {Function} Returns the new mathematical operation function.
       */
      function createMathOperation(operator, defaultValue) {
        return function (value, other) {
          var result;
          if (value === undefined && other === undefined) {
            return defaultValue;
          }
          if (value !== undefined) {
            result = value;
          }
          if (other !== undefined) {
            if (result === undefined) {
              return other;
            }
            if (typeof value == 'string' || typeof other == 'string') {
              value = baseToString(value);
              other = baseToString(other);
            } else {
              value = baseToNumber(value);
              other = baseToNumber(other);
            }
            result = operator(value, other);
          }
          return result;
        };
      }

      /**
       * Adds two numbers.
       *
       * @static
       * @memberOf _
       * @since 3.4.0
       * @category Math
       * @param {number} augend The first number in an addition.
       * @param {number} addend The second number in an addition.
       * @returns {number} Returns the total.
       * @example
       *
       * _.add(6, 4);
       * // => 10
       */
      var add = createMathOperation(function (augend, addend) {
        return augend + addend;
      }, 0);

      /** Used to match a single whitespace character. */
      var reWhitespace = /\s/;

      /**
       * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
       * character of `string`.
       *
       * @private
       * @param {string} string The string to inspect.
       * @returns {number} Returns the index of the last non-whitespace character.
       */
      function trimmedEndIndex(string) {
        var index = string.length;
        while (index-- && reWhitespace.test(string.charAt(index))) {}
        return index;
      }

      /** Used to match leading whitespace. */
      var reTrimStart = /^\s+/;

      /**
       * The base implementation of `_.trim`.
       *
       * @private
       * @param {string} string The string to trim.
       * @returns {string} Returns the trimmed string.
       */
      function baseTrim(string) {
        return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
      }

      /**
       * Checks if `value` is the
       * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
       * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an object, else `false`.
       * @example
       *
       * _.isObject({});
       * // => true
       *
       * _.isObject([1, 2, 3]);
       * // => true
       *
       * _.isObject(_.noop);
       * // => true
       *
       * _.isObject(null);
       * // => false
       */
      function isObject(value) {
        var type = typeof value;
        return value != null && (type == 'object' || type == 'function');
      }

      /** Used as references for various `Number` constants. */
      var NAN$1 = 0 / 0;

      /** Used to detect bad signed hexadecimal string values. */
      var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

      /** Used to detect binary string values. */
      var reIsBinary = /^0b[01]+$/i;

      /** Used to detect octal string values. */
      var reIsOctal = /^0o[0-7]+$/i;

      /** Built-in method references without a dependency on `root`. */
      var freeParseInt = parseInt;

      /**
       * Converts `value` to a number.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to process.
       * @returns {number} Returns the number.
       * @example
       *
       * _.toNumber(3.2);
       * // => 3.2
       *
       * _.toNumber(Number.MIN_VALUE);
       * // => 5e-324
       *
       * _.toNumber(Infinity);
       * // => Infinity
       *
       * _.toNumber('3.2');
       * // => 3.2
       */
      function toNumber(value) {
        if (typeof value == 'number') {
          return value;
        }
        if (isSymbol(value)) {
          return NAN$1;
        }
        if (isObject(value)) {
          var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
          value = isObject(other) ? other + '' : other;
        }
        if (typeof value != 'string') {
          return value === 0 ? value : +value;
        }
        value = baseTrim(value);
        var isBinary = reIsBinary.test(value);
        return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN$1 : +value;
      }

      /** Used as references for various `Number` constants. */
      var INFINITY$1 = 1 / 0,
        MAX_INTEGER = 1.7976931348623157e+308;

      /**
       * Converts `value` to a finite number.
       *
       * @static
       * @memberOf _
       * @since 4.12.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {number} Returns the converted number.
       * @example
       *
       * _.toFinite(3.2);
       * // => 3.2
       *
       * _.toFinite(Number.MIN_VALUE);
       * // => 5e-324
       *
       * _.toFinite(Infinity);
       * // => 1.7976931348623157e+308
       *
       * _.toFinite('3.2');
       * // => 3.2
       */
      function toFinite(value) {
        if (!value) {
          return value === 0 ? value : 0;
        }
        value = toNumber(value);
        if (value === INFINITY$1 || value === -INFINITY$1) {
          var sign = value < 0 ? -1 : 1;
          return sign * MAX_INTEGER;
        }
        return value === value ? value : 0;
      }

      /**
       * Converts `value` to an integer.
       *
       * **Note:** This method is loosely based on
       * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {number} Returns the converted integer.
       * @example
       *
       * _.toInteger(3.2);
       * // => 3
       *
       * _.toInteger(Number.MIN_VALUE);
       * // => 0
       *
       * _.toInteger(Infinity);
       * // => 1.7976931348623157e+308
       *
       * _.toInteger('3.2');
       * // => 3
       */
      function toInteger(value) {
        var result = toFinite(value),
          remainder = result % 1;
        return result === result ? remainder ? result - remainder : result : 0;
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT = 'Expected a function';

      /**
       * The opposite of `_.before`; this method creates a function that invokes
       * `func` once it's called `n` or more times.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {number} n The number of calls before `func` is invoked.
       * @param {Function} func The function to restrict.
       * @returns {Function} Returns the new restricted function.
       * @example
       *
       * var saves = ['profile', 'settings'];
       *
       * var done = _.after(saves.length, function() {
       *   console.log('done saving!');
       * });
       *
       * _.forEach(saves, function(type) {
       *   asyncSave({ 'type': type, 'complete': done });
       * });
       * // => Logs 'done saving!' after the two async saves have completed.
       */
      function after(n, func) {
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT);
        }
        n = toInteger(n);
        return function () {
          if (--n < 1) {
            return func.apply(this, arguments);
          }
        };
      }

      /**
       * This method returns the first argument it receives.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {*} value Any value.
       * @returns {*} Returns `value`.
       * @example
       *
       * var object = { 'a': 1 };
       *
       * console.log(_.identity(object) === object);
       * // => true
       */
      function identity(value) {
        return value;
      }

      /** `Object#toString` result references. */
      var asyncTag = '[object AsyncFunction]',
        funcTag = '[object Function]',
        genTag = '[object GeneratorFunction]',
        proxyTag = '[object Proxy]';

      /**
       * Checks if `value` is classified as a `Function` object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a function, else `false`.
       * @example
       *
       * _.isFunction(_);
       * // => true
       *
       * _.isFunction(/abc/);
       * // => false
       */
      function isFunction(value) {
        if (!isObject(value)) {
          return false;
        }
        // The use of `Object#toString` avoids issues with the `typeof` operator
        // in Safari 9 which returns 'object' for typed arrays and other constructors.
        var tag = baseGetTag(value);
        return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
      }

      /** Used to detect overreaching core-js shims. */
      var coreJsData = root['__core-js_shared__'];

      /** Used to detect methods masquerading as native. */
      var maskSrcKey = function () {
        var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
        return uid ? 'Symbol(src)_1.' + uid : '';
      }();

      /**
       * Checks if `func` has its source masked.
       *
       * @private
       * @param {Function} func The function to check.
       * @returns {boolean} Returns `true` if `func` is masked, else `false`.
       */
      function isMasked(func) {
        return !!maskSrcKey && maskSrcKey in func;
      }

      /** Used for built-in method references. */
      var funcProto = Function.prototype;

      /** Used to resolve the decompiled source of functions. */
      var funcToString = funcProto.toString;

      /**
       * Converts `func` to its source code.
       *
       * @private
       * @param {Function} func The function to convert.
       * @returns {string} Returns the source code.
       */
      function toSource(func) {
        if (func != null) {
          try {
            return funcToString.call(func);
          } catch (e) {}
          try {
            return func + '';
          } catch (e) {}
        }
        return '';
      }

      /**
       * Used to match `RegExp`
       * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
       */
      var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

      /** Used to detect host constructors (Safari). */
      var reIsHostCtor = /^\[object .+?Constructor\]$/;

      /** Used for built-in method references. */
      var funcProto$1 = Function.prototype,
        objectProto$2 = Object.prototype;

      /** Used to resolve the decompiled source of functions. */
      var funcToString$1 = funcProto$1.toString;

      /** Used to check objects for own properties. */
      var hasOwnProperty$1 = objectProto$2.hasOwnProperty;

      /** Used to detect if a method is native. */
      var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');

      /**
       * The base implementation of `_.isNative` without bad shim checks.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a native function,
       *  else `false`.
       */
      function baseIsNative(value) {
        if (!isObject(value) || isMasked(value)) {
          return false;
        }
        var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
        return pattern.test(toSource(value));
      }

      /**
       * Gets the value at `key` of `object`.
       *
       * @private
       * @param {Object} [object] The object to query.
       * @param {string} key The key of the property to get.
       * @returns {*} Returns the property value.
       */
      function getValue(object, key) {
        return object == null ? undefined : object[key];
      }

      /**
       * Gets the native function at `key` of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {string} key The key of the method to get.
       * @returns {*} Returns the function if it's native, else `undefined`.
       */
      function getNative(object, key) {
        var value = getValue(object, key);
        return baseIsNative(value) ? value : undefined;
      }

      /* Built-in method references that are verified to be native. */
      var WeakMap$1 = getNative(root, 'WeakMap');

      /** Used to store function metadata. */
      var metaMap = WeakMap$1 && new WeakMap$1();

      /**
       * The base implementation of `setData` without support for hot loop shorting.
       *
       * @private
       * @param {Function} func The function to associate metadata with.
       * @param {*} data The metadata.
       * @returns {Function} Returns `func`.
       */
      var baseSetData = !metaMap ? identity : function (func, data) {
        metaMap.set(func, data);
        return func;
      };

      /** Built-in value references. */
      var objectCreate = Object.create;

      /**
       * The base implementation of `_.create` without support for assigning
       * properties to the created object.
       *
       * @private
       * @param {Object} proto The object to inherit from.
       * @returns {Object} Returns the new object.
       */
      var baseCreate = function () {
        function object() {}
        return function (proto) {
          if (!isObject(proto)) {
            return {};
          }
          if (objectCreate) {
            return objectCreate(proto);
          }
          object.prototype = proto;
          var result = new object();
          object.prototype = undefined;
          return result;
        };
      }();

      /**
       * Creates a function that produces an instance of `Ctor` regardless of
       * whether it was invoked as part of a `new` expression or by `call` or `apply`.
       *
       * @private
       * @param {Function} Ctor The constructor to wrap.
       * @returns {Function} Returns the new wrapped function.
       */
      function createCtor(Ctor) {
        return function () {
          // Use a `switch` statement to work with class constructors. See
          // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
          // for more details.
          var args = arguments;
          switch (args.length) {
            case 0:
              return new Ctor();
            case 1:
              return new Ctor(args[0]);
            case 2:
              return new Ctor(args[0], args[1]);
            case 3:
              return new Ctor(args[0], args[1], args[2]);
            case 4:
              return new Ctor(args[0], args[1], args[2], args[3]);
            case 5:
              return new Ctor(args[0], args[1], args[2], args[3], args[4]);
            case 6:
              return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
            case 7:
              return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
          }
          var thisBinding = baseCreate(Ctor.prototype),
            result = Ctor.apply(thisBinding, args);

          // Mimic the constructor's `return` behavior.
          // See https://es5.github.io/#x13.2.2 for more details.
          return isObject(result) ? result : thisBinding;
        };
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG = 1;

      /**
       * Creates a function that wraps `func` to invoke it with the optional `this`
       * binding of `thisArg`.
       *
       * @private
       * @param {Function} func The function to wrap.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @param {*} [thisArg] The `this` binding of `func`.
       * @returns {Function} Returns the new wrapped function.
       */
      function createBind(func, bitmask, thisArg) {
        var isBind = bitmask & WRAP_BIND_FLAG,
          Ctor = createCtor(func);
        function wrapper() {
          var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
          return fn.apply(isBind ? thisArg : this, arguments);
        }
        return wrapper;
      }

      /**
       * A faster alternative to `Function#apply`, this function invokes `func`
       * with the `this` binding of `thisArg` and the arguments of `args`.
       *
       * @private
       * @param {Function} func The function to invoke.
       * @param {*} thisArg The `this` binding of `func`.
       * @param {Array} args The arguments to invoke `func` with.
       * @returns {*} Returns the result of `func`.
       */
      function apply(func, thisArg, args) {
        switch (args.length) {
          case 0:
            return func.call(thisArg);
          case 1:
            return func.call(thisArg, args[0]);
          case 2:
            return func.call(thisArg, args[0], args[1]);
          case 3:
            return func.call(thisArg, args[0], args[1], args[2]);
        }
        return func.apply(thisArg, args);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax = Math.max;

      /**
       * Creates an array that is the composition of partially applied arguments,
       * placeholders, and provided arguments into a single array of arguments.
       *
       * @private
       * @param {Array} args The provided arguments.
       * @param {Array} partials The arguments to prepend to those provided.
       * @param {Array} holders The `partials` placeholder indexes.
       * @params {boolean} [isCurried] Specify composing for a curried function.
       * @returns {Array} Returns the new array of composed arguments.
       */
      function composeArgs(args, partials, holders, isCurried) {
        var argsIndex = -1,
          argsLength = args.length,
          holdersLength = holders.length,
          leftIndex = -1,
          leftLength = partials.length,
          rangeLength = nativeMax(argsLength - holdersLength, 0),
          result = Array(leftLength + rangeLength),
          isUncurried = !isCurried;
        while (++leftIndex < leftLength) {
          result[leftIndex] = partials[leftIndex];
        }
        while (++argsIndex < holdersLength) {
          if (isUncurried || argsIndex < argsLength) {
            result[holders[argsIndex]] = args[argsIndex];
          }
        }
        while (rangeLength--) {
          result[leftIndex++] = args[argsIndex++];
        }
        return result;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$1 = Math.max;

      /**
       * This function is like `composeArgs` except that the arguments composition
       * is tailored for `_.partialRight`.
       *
       * @private
       * @param {Array} args The provided arguments.
       * @param {Array} partials The arguments to append to those provided.
       * @param {Array} holders The `partials` placeholder indexes.
       * @params {boolean} [isCurried] Specify composing for a curried function.
       * @returns {Array} Returns the new array of composed arguments.
       */
      function composeArgsRight(args, partials, holders, isCurried) {
        var argsIndex = -1,
          argsLength = args.length,
          holdersIndex = -1,
          holdersLength = holders.length,
          rightIndex = -1,
          rightLength = partials.length,
          rangeLength = nativeMax$1(argsLength - holdersLength, 0),
          result = Array(rangeLength + rightLength),
          isUncurried = !isCurried;
        while (++argsIndex < rangeLength) {
          result[argsIndex] = args[argsIndex];
        }
        var offset = argsIndex;
        while (++rightIndex < rightLength) {
          result[offset + rightIndex] = partials[rightIndex];
        }
        while (++holdersIndex < holdersLength) {
          if (isUncurried || argsIndex < argsLength) {
            result[offset + holders[holdersIndex]] = args[argsIndex++];
          }
        }
        return result;
      }

      /**
       * Gets the number of `placeholder` occurrences in `array`.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} placeholder The placeholder to search for.
       * @returns {number} Returns the placeholder count.
       */
      function countHolders(array, placeholder) {
        var length = array.length,
          result = 0;
        while (length--) {
          if (array[length] === placeholder) {
            ++result;
          }
        }
        return result;
      }

      /**
       * The function whose prototype chain sequence wrappers inherit from.
       *
       * @private
       */
      function baseLodash() {
        // No operation performed.
      }

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH = 4294967295;

      /**
       * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
       *
       * @private
       * @constructor
       * @param {*} value The value to wrap.
       */
      function LazyWrapper(value) {
        this.__wrapped__ = value;
        this.__actions__ = [];
        this.__dir__ = 1;
        this.__filtered__ = false;
        this.__iteratees__ = [];
        this.__takeCount__ = MAX_ARRAY_LENGTH;
        this.__views__ = [];
      }

      // Ensure `LazyWrapper` is an instance of `baseLodash`.
      LazyWrapper.prototype = baseCreate(baseLodash.prototype);
      LazyWrapper.prototype.constructor = LazyWrapper;

      /**
       * This method returns `undefined`.
       *
       * @static
       * @memberOf _
       * @since 2.3.0
       * @category Util
       * @example
       *
       * _.times(2, _.noop);
       * // => [undefined, undefined]
       */
      function noop() {
        // No operation performed.
      }

      /**
       * Gets metadata for `func`.
       *
       * @private
       * @param {Function} func The function to query.
       * @returns {*} Returns the metadata for `func`.
       */
      var getData = !metaMap ? noop : function (func) {
        return metaMap.get(func);
      };

      /** Used to lookup unminified function names. */
      var realNames = {};

      /** Used for built-in method references. */
      var objectProto$3 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$2 = objectProto$3.hasOwnProperty;

      /**
       * Gets the name of `func`.
       *
       * @private
       * @param {Function} func The function to query.
       * @returns {string} Returns the function name.
       */
      function getFuncName(func) {
        var result = func.name + '',
          array = realNames[result],
          length = hasOwnProperty$2.call(realNames, result) ? array.length : 0;
        while (length--) {
          var data = array[length],
            otherFunc = data.func;
          if (otherFunc == null || otherFunc == func) {
            return data.name;
          }
        }
        return result;
      }

      /**
       * The base constructor for creating `lodash` wrapper objects.
       *
       * @private
       * @param {*} value The value to wrap.
       * @param {boolean} [chainAll] Enable explicit method chain sequences.
       */
      function LodashWrapper(value, chainAll) {
        this.__wrapped__ = value;
        this.__actions__ = [];
        this.__chain__ = !!chainAll;
        this.__index__ = 0;
        this.__values__ = undefined;
      }
      LodashWrapper.prototype = baseCreate(baseLodash.prototype);
      LodashWrapper.prototype.constructor = LodashWrapper;

      /**
       * Copies the values of `source` to `array`.
       *
       * @private
       * @param {Array} source The array to copy values from.
       * @param {Array} [array=[]] The array to copy values to.
       * @returns {Array} Returns `array`.
       */
      function copyArray(source, array) {
        var index = -1,
          length = source.length;
        array || (array = Array(length));
        while (++index < length) {
          array[index] = source[index];
        }
        return array;
      }

      /**
       * Creates a clone of `wrapper`.
       *
       * @private
       * @param {Object} wrapper The wrapper to clone.
       * @returns {Object} Returns the cloned wrapper.
       */
      function wrapperClone(wrapper) {
        if (wrapper instanceof LazyWrapper) {
          return wrapper.clone();
        }
        var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
        result.__actions__ = copyArray(wrapper.__actions__);
        result.__index__ = wrapper.__index__;
        result.__values__ = wrapper.__values__;
        return result;
      }

      /** Used for built-in method references. */
      var objectProto$4 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$3 = objectProto$4.hasOwnProperty;

      /**
       * Creates a `lodash` object which wraps `value` to enable implicit method
       * chain sequences. Methods that operate on and return arrays, collections,
       * and functions can be chained together. Methods that retrieve a single value
       * or may return a primitive value will automatically end the chain sequence
       * and return the unwrapped value. Otherwise, the value must be unwrapped
       * with `_#value`.
       *
       * Explicit chain sequences, which must be unwrapped with `_#value`, may be
       * enabled using `_.chain`.
       *
       * The execution of chained methods is lazy, that is, it's deferred until
       * `_#value` is implicitly or explicitly called.
       *
       * Lazy evaluation allows several methods to support shortcut fusion.
       * Shortcut fusion is an optimization to merge iteratee calls; this avoids
       * the creation of intermediate arrays and can greatly reduce the number of
       * iteratee executions. Sections of a chain sequence qualify for shortcut
       * fusion if the section is applied to an array and iteratees accept only
       * one argument. The heuristic for whether a section qualifies for shortcut
       * fusion is subject to change.
       *
       * Chaining is supported in custom builds as long as the `_#value` method is
       * directly or indirectly included in the build.
       *
       * In addition to lodash methods, wrappers have `Array` and `String` methods.
       *
       * The wrapper `Array` methods are:
       * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
       *
       * The wrapper `String` methods are:
       * `replace` and `split`
       *
       * The wrapper methods that support shortcut fusion are:
       * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
       * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
       * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
       *
       * The chainable wrapper methods are:
       * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
       * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
       * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
       * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
       * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
       * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
       * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
       * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
       * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
       * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
       * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
       * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
       * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
       * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
       * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
       * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
       * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
       * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
       * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
       * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
       * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
       * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
       * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
       * `zipObject`, `zipObjectDeep`, and `zipWith`
       *
       * The wrapper methods that are **not** chainable by default are:
       * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
       * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
       * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
       * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
       * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
       * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
       * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
       * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
       * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
       * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
       * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
       * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
       * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
       * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
       * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
       * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
       * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
       * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
       * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
       * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
       * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
       * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
       * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
       * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
       * `upperFirst`, `value`, and `words`
       *
       * @name _
       * @constructor
       * @category Seq
       * @param {*} value The value to wrap in a `lodash` instance.
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * var wrapped = _([1, 2, 3]);
       *
       * // Returns an unwrapped value.
       * wrapped.reduce(_.add);
       * // => 6
       *
       * // Returns a wrapped value.
       * var squares = wrapped.map(square);
       *
       * _.isArray(squares);
       * // => false
       *
       * _.isArray(squares.value());
       * // => true
       */
      function lodash(value) {
        if (isObjectLike(value) && !isArray$1(value) && !(value instanceof LazyWrapper)) {
          if (value instanceof LodashWrapper) {
            return value;
          }
          if (hasOwnProperty$3.call(value, '__wrapped__')) {
            return wrapperClone(value);
          }
        }
        return new LodashWrapper(value);
      }

      // Ensure wrappers are instances of `baseLodash`.
      lodash.prototype = baseLodash.prototype;
      lodash.prototype.constructor = lodash;

      /**
       * Checks if `func` has a lazy counterpart.
       *
       * @private
       * @param {Function} func The function to check.
       * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
       *  else `false`.
       */
      function isLaziable(func) {
        var funcName = getFuncName(func),
          other = lodash[funcName];
        if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
          return false;
        }
        if (func === other) {
          return true;
        }
        var data = getData(other);
        return !!data && func === data[0];
      }

      /** Used to detect hot functions by number of calls within a span of milliseconds. */
      var HOT_COUNT = 800,
        HOT_SPAN = 16;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeNow = Date.now;

      /**
       * Creates a function that'll short out and invoke `identity` instead
       * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
       * milliseconds.
       *
       * @private
       * @param {Function} func The function to restrict.
       * @returns {Function} Returns the new shortable function.
       */
      function shortOut(func) {
        var count = 0,
          lastCalled = 0;
        return function () {
          var stamp = nativeNow(),
            remaining = HOT_SPAN - (stamp - lastCalled);
          lastCalled = stamp;
          if (remaining > 0) {
            if (++count >= HOT_COUNT) {
              return arguments[0];
            }
          } else {
            count = 0;
          }
          return func.apply(undefined, arguments);
        };
      }

      /**
       * Sets metadata for `func`.
       *
       * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
       * period of time, it will trip its breaker and transition to an identity
       * function to avoid garbage collection pauses in V8. See
       * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
       * for more details.
       *
       * @private
       * @param {Function} func The function to associate metadata with.
       * @param {*} data The metadata.
       * @returns {Function} Returns `func`.
       */
      var setData = shortOut(baseSetData);

      /** Used to match wrap detail comments. */
      var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
        reSplitDetails = /,? & /;

      /**
       * Extracts wrapper details from the `source` body comment.
       *
       * @private
       * @param {string} source The source to inspect.
       * @returns {Array} Returns the wrapper details.
       */
      function getWrapDetails(source) {
        var match = source.match(reWrapDetails);
        return match ? match[1].split(reSplitDetails) : [];
      }

      /** Used to match wrap detail comments. */
      var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;

      /**
       * Inserts wrapper `details` in a comment at the top of the `source` body.
       *
       * @private
       * @param {string} source The source to modify.
       * @returns {Array} details The details to insert.
       * @returns {string} Returns the modified source.
       */
      function insertWrapDetails(source, details) {
        var length = details.length;
        if (!length) {
          return source;
        }
        var lastIndex = length - 1;
        details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
        details = details.join(length > 2 ? ', ' : ' ');
        return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
      }

      /**
       * Creates a function that returns `value`.
       *
       * @static
       * @memberOf _
       * @since 2.4.0
       * @category Util
       * @param {*} value The value to return from the new function.
       * @returns {Function} Returns the new constant function.
       * @example
       *
       * var objects = _.times(2, _.constant({ 'a': 1 }));
       *
       * console.log(objects);
       * // => [{ 'a': 1 }, { 'a': 1 }]
       *
       * console.log(objects[0] === objects[1]);
       * // => true
       */
      function constant(value) {
        return function () {
          return value;
        };
      }
      var defineProperty = function () {
        try {
          var func = getNative(Object, 'defineProperty');
          func({}, '', {});
          return func;
        } catch (e) {}
      }();

      /**
       * The base implementation of `setToString` without support for hot loop shorting.
       *
       * @private
       * @param {Function} func The function to modify.
       * @param {Function} string The `toString` result.
       * @returns {Function} Returns `func`.
       */
      var baseSetToString = !defineProperty ? identity : function (func, string) {
        return defineProperty(func, 'toString', {
          'configurable': true,
          'enumerable': false,
          'value': constant(string),
          'writable': true
        });
      };

      /**
       * Sets the `toString` method of `func` to return `string`.
       *
       * @private
       * @param {Function} func The function to modify.
       * @param {Function} string The `toString` result.
       * @returns {Function} Returns `func`.
       */
      var setToString = shortOut(baseSetToString);

      /**
       * A specialized version of `_.forEach` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array} Returns `array`.
       */
      function arrayEach(array, iteratee) {
        var index = -1,
          length = array == null ? 0 : array.length;
        while (++index < length) {
          if (iteratee(array[index], index, array) === false) {
            break;
          }
        }
        return array;
      }

      /**
       * The base implementation of `_.findIndex` and `_.findLastIndex` without
       * support for iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {Function} predicate The function invoked per iteration.
       * @param {number} fromIndex The index to search from.
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function baseFindIndex(array, predicate, fromIndex, fromRight) {
        var length = array.length,
          index = fromIndex + (fromRight ? 1 : -1);
        while (fromRight ? index-- : ++index < length) {
          if (predicate(array[index], index, array)) {
            return index;
          }
        }
        return -1;
      }

      /**
       * The base implementation of `_.isNaN` without support for number objects.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
       */
      function baseIsNaN(value) {
        return value !== value;
      }

      /**
       * A specialized version of `_.indexOf` which performs strict equality
       * comparisons of values, i.e. `===`.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} fromIndex The index to search from.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function strictIndexOf(array, value, fromIndex) {
        var index = fromIndex - 1,
          length = array.length;
        while (++index < length) {
          if (array[index] === value) {
            return index;
          }
        }
        return -1;
      }

      /**
       * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} fromIndex The index to search from.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function baseIndexOf(array, value, fromIndex) {
        return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
      }

      /**
       * A specialized version of `_.includes` for arrays without support for
       * specifying an index to search from.
       *
       * @private
       * @param {Array} [array] The array to inspect.
       * @param {*} target The value to search for.
       * @returns {boolean} Returns `true` if `target` is found, else `false`.
       */
      function arrayIncludes(array, value) {
        var length = array == null ? 0 : array.length;
        return !!length && baseIndexOf(array, value, 0) > -1;
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$1 = 1,
        WRAP_BIND_KEY_FLAG = 2,
        WRAP_CURRY_FLAG = 8,
        WRAP_CURRY_RIGHT_FLAG = 16,
        WRAP_PARTIAL_FLAG = 32,
        WRAP_PARTIAL_RIGHT_FLAG = 64,
        WRAP_ARY_FLAG = 128,
        WRAP_REARG_FLAG = 256,
        WRAP_FLIP_FLAG = 512;

      /** Used to associate wrap methods with their bit flags. */
      var wrapFlags = [['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG]];

      /**
       * Updates wrapper `details` based on `bitmask` flags.
       *
       * @private
       * @returns {Array} details The details to modify.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @returns {Array} Returns `details`.
       */
      function updateWrapDetails(details, bitmask) {
        arrayEach(wrapFlags, function (pair) {
          var value = '_.' + pair[0];
          if (bitmask & pair[1] && !arrayIncludes(details, value)) {
            details.push(value);
          }
        });
        return details.sort();
      }

      /**
       * Sets the `toString` method of `wrapper` to mimic the source of `reference`
       * with wrapper details in a comment at the top of the source body.
       *
       * @private
       * @param {Function} wrapper The function to modify.
       * @param {Function} reference The reference function.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @returns {Function} Returns `wrapper`.
       */
      function setWrapToString(wrapper, reference, bitmask) {
        var source = reference + '';
        return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$2 = 1,
        WRAP_BIND_KEY_FLAG$1 = 2,
        WRAP_CURRY_BOUND_FLAG = 4,
        WRAP_CURRY_FLAG$1 = 8,
        WRAP_PARTIAL_FLAG$1 = 32,
        WRAP_PARTIAL_RIGHT_FLAG$1 = 64;

      /**
       * Creates a function that wraps `func` to continue currying.
       *
       * @private
       * @param {Function} func The function to wrap.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @param {Function} wrapFunc The function to create the `func` wrapper.
       * @param {*} placeholder The placeholder value.
       * @param {*} [thisArg] The `this` binding of `func`.
       * @param {Array} [partials] The arguments to prepend to those provided to
       *  the new function.
       * @param {Array} [holders] The `partials` placeholder indexes.
       * @param {Array} [argPos] The argument positions of the new function.
       * @param {number} [ary] The arity cap of `func`.
       * @param {number} [arity] The arity of `func`.
       * @returns {Function} Returns the new wrapped function.
       */
      function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
        var isCurry = bitmask & WRAP_CURRY_FLAG$1,
          newHolders = isCurry ? holders : undefined,
          newHoldersRight = isCurry ? undefined : holders,
          newPartials = isCurry ? partials : undefined,
          newPartialsRight = isCurry ? undefined : partials;
        bitmask |= isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1;
        bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
        if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
          bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1);
        }
        var newData = [func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity];
        var result = wrapFunc.apply(undefined, newData);
        if (isLaziable(func)) {
          setData(result, newData);
        }
        result.placeholder = placeholder;
        return setWrapToString(result, func, bitmask);
      }

      /**
       * Gets the argument placeholder value for `func`.
       *
       * @private
       * @param {Function} func The function to inspect.
       * @returns {*} Returns the placeholder value.
       */
      function getHolder(func) {
        var object = func;
        return object.placeholder;
      }

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER = 9007199254740991;

      /** Used to detect unsigned integer values. */
      var reIsUint = /^(?:0|[1-9]\d*)$/;

      /**
       * Checks if `value` is a valid array-like index.
       *
       * @private
       * @param {*} value The value to check.
       * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
       * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
       */
      function isIndex(value, length) {
        var type = typeof value;
        length = length == null ? MAX_SAFE_INTEGER : length;
        return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin = Math.min;

      /**
       * Reorder `array` according to the specified indexes where the element at
       * the first index is assigned as the first element, the element at
       * the second index is assigned as the second element, and so on.
       *
       * @private
       * @param {Array} array The array to reorder.
       * @param {Array} indexes The arranged array indexes.
       * @returns {Array} Returns `array`.
       */
      function reorder(array, indexes) {
        var arrLength = array.length,
          length = nativeMin(indexes.length, arrLength),
          oldArray = copyArray(array);
        while (length--) {
          var index = indexes[length];
          array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
        }
        return array;
      }

      /** Used as the internal argument placeholder. */
      var PLACEHOLDER = '__lodash_placeholder__';

      /**
       * Replaces all `placeholder` elements in `array` with an internal placeholder
       * and returns an array of their indexes.
       *
       * @private
       * @param {Array} array The array to modify.
       * @param {*} placeholder The placeholder to replace.
       * @returns {Array} Returns the new array of placeholder indexes.
       */
      function replaceHolders(array, placeholder) {
        var index = -1,
          length = array.length,
          resIndex = 0,
          result = [];
        while (++index < length) {
          var value = array[index];
          if (value === placeholder || value === PLACEHOLDER) {
            array[index] = PLACEHOLDER;
            result[resIndex++] = index;
          }
        }
        return result;
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$3 = 1,
        WRAP_BIND_KEY_FLAG$2 = 2,
        WRAP_CURRY_FLAG$2 = 8,
        WRAP_CURRY_RIGHT_FLAG$1 = 16,
        WRAP_ARY_FLAG$1 = 128,
        WRAP_FLIP_FLAG$1 = 512;

      /**
       * Creates a function that wraps `func` to invoke it with optional `this`
       * binding of `thisArg`, partial application, and currying.
       *
       * @private
       * @param {Function|string} func The function or method name to wrap.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @param {*} [thisArg] The `this` binding of `func`.
       * @param {Array} [partials] The arguments to prepend to those provided to
       *  the new function.
       * @param {Array} [holders] The `partials` placeholder indexes.
       * @param {Array} [partialsRight] The arguments to append to those provided
       *  to the new function.
       * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
       * @param {Array} [argPos] The argument positions of the new function.
       * @param {number} [ary] The arity cap of `func`.
       * @param {number} [arity] The arity of `func`.
       * @returns {Function} Returns the new wrapped function.
       */
      function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
        var isAry = bitmask & WRAP_ARY_FLAG$1,
          isBind = bitmask & WRAP_BIND_FLAG$3,
          isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
          isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
          isFlip = bitmask & WRAP_FLIP_FLAG$1,
          Ctor = isBindKey ? undefined : createCtor(func);
        function wrapper() {
          var length = arguments.length,
            args = Array(length),
            index = length;
          while (index--) {
            args[index] = arguments[index];
          }
          if (isCurried) {
            var placeholder = getHolder(wrapper),
              holdersCount = countHolders(args, placeholder);
          }
          if (partials) {
            args = composeArgs(args, partials, holders, isCurried);
          }
          if (partialsRight) {
            args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
          }
          length -= holdersCount;
          if (isCurried && length < arity) {
            var newHolders = replaceHolders(args, placeholder);
            return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length);
          }
          var thisBinding = isBind ? thisArg : this,
            fn = isBindKey ? thisBinding[func] : func;
          length = args.length;
          if (argPos) {
            args = reorder(args, argPos);
          } else if (isFlip && length > 1) {
            args.reverse();
          }
          if (isAry && ary < length) {
            args.length = ary;
          }
          if (this && this !== root && this instanceof wrapper) {
            fn = Ctor || createCtor(fn);
          }
          return fn.apply(thisBinding, args);
        }
        return wrapper;
      }

      /**
       * Creates a function that wraps `func` to enable currying.
       *
       * @private
       * @param {Function} func The function to wrap.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @param {number} arity The arity of `func`.
       * @returns {Function} Returns the new wrapped function.
       */
      function createCurry(func, bitmask, arity) {
        var Ctor = createCtor(func);
        function wrapper() {
          var length = arguments.length,
            args = Array(length),
            index = length,
            placeholder = getHolder(wrapper);
          while (index--) {
            args[index] = arguments[index];
          }
          var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder);
          length -= holders.length;
          if (length < arity) {
            return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length);
          }
          var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
          return apply(fn, this, args);
        }
        return wrapper;
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$4 = 1;

      /**
       * Creates a function that wraps `func` to invoke it with the `this` binding
       * of `thisArg` and `partials` prepended to the arguments it receives.
       *
       * @private
       * @param {Function} func The function to wrap.
       * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
       * @param {*} thisArg The `this` binding of `func`.
       * @param {Array} partials The arguments to prepend to those provided to
       *  the new function.
       * @returns {Function} Returns the new wrapped function.
       */
      function createPartial(func, bitmask, thisArg, partials) {
        var isBind = bitmask & WRAP_BIND_FLAG$4,
          Ctor = createCtor(func);
        function wrapper() {
          var argsIndex = -1,
            argsLength = arguments.length,
            leftIndex = -1,
            leftLength = partials.length,
            args = Array(leftLength + argsLength),
            fn = this && this !== root && this instanceof wrapper ? Ctor : func;
          while (++leftIndex < leftLength) {
            args[leftIndex] = partials[leftIndex];
          }
          while (argsLength--) {
            args[leftIndex++] = arguments[++argsIndex];
          }
          return apply(fn, isBind ? thisArg : this, args);
        }
        return wrapper;
      }

      /** Used as the internal argument placeholder. */
      var PLACEHOLDER$1 = '__lodash_placeholder__';

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$5 = 1,
        WRAP_BIND_KEY_FLAG$3 = 2,
        WRAP_CURRY_BOUND_FLAG$1 = 4,
        WRAP_CURRY_FLAG$3 = 8,
        WRAP_ARY_FLAG$2 = 128,
        WRAP_REARG_FLAG$1 = 256;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$1 = Math.min;

      /**
       * Merges the function metadata of `source` into `data`.
       *
       * Merging metadata reduces the number of wrappers used to invoke a function.
       * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
       * may be applied regardless of execution order. Methods like `_.ary` and
       * `_.rearg` modify function arguments, making the order in which they are
       * executed important, preventing the merging of metadata. However, we make
       * an exception for a safe combined case where curried functions have `_.ary`
       * and or `_.rearg` applied.
       *
       * @private
       * @param {Array} data The destination metadata.
       * @param {Array} source The source metadata.
       * @returns {Array} Returns `data`.
       */
      function mergeData(data, source) {
        var bitmask = data[1],
          srcBitmask = source[1],
          newBitmask = bitmask | srcBitmask,
          isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2);
        var isCombo = srcBitmask == WRAP_ARY_FLAG$2 && bitmask == WRAP_CURRY_FLAG$3 || srcBitmask == WRAP_ARY_FLAG$2 && bitmask == WRAP_REARG_FLAG$1 && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG$3;

        // Exit early if metadata can't be merged.
        if (!(isCommon || isCombo)) {
          return data;
        }
        // Use source `thisArg` if available.
        if (srcBitmask & WRAP_BIND_FLAG$5) {
          data[2] = source[2];
          // Set when currying a bound function.
          newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1;
        }
        // Compose partial arguments.
        var value = source[3];
        if (value) {
          var partials = data[3];
          data[3] = partials ? composeArgs(partials, value, source[4]) : value;
          data[4] = partials ? replaceHolders(data[3], PLACEHOLDER$1) : source[4];
        }
        // Compose partial right arguments.
        value = source[5];
        if (value) {
          partials = data[5];
          data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
          data[6] = partials ? replaceHolders(data[5], PLACEHOLDER$1) : source[6];
        }
        // Use source `argPos` if available.
        value = source[7];
        if (value) {
          data[7] = value;
        }
        // Use source `ary` if it's smaller.
        if (srcBitmask & WRAP_ARY_FLAG$2) {
          data[8] = data[8] == null ? source[8] : nativeMin$1(data[8], source[8]);
        }
        // Use source `arity` if one is not provided.
        if (data[9] == null) {
          data[9] = source[9];
        }
        // Use source `func` and merge bitmasks.
        data[0] = source[0];
        data[1] = newBitmask;
        return data;
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT$1 = 'Expected a function';

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$6 = 1,
        WRAP_BIND_KEY_FLAG$4 = 2,
        WRAP_CURRY_FLAG$4 = 8,
        WRAP_CURRY_RIGHT_FLAG$2 = 16,
        WRAP_PARTIAL_FLAG$2 = 32,
        WRAP_PARTIAL_RIGHT_FLAG$2 = 64;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$2 = Math.max;

      /**
       * Creates a function that either curries or invokes `func` with optional
       * `this` binding and partially applied arguments.
       *
       * @private
       * @param {Function|string} func The function or method name to wrap.
       * @param {number} bitmask The bitmask flags.
       *    1 - `_.bind`
       *    2 - `_.bindKey`
       *    4 - `_.curry` or `_.curryRight` of a bound function
       *    8 - `_.curry`
       *   16 - `_.curryRight`
       *   32 - `_.partial`
       *   64 - `_.partialRight`
       *  128 - `_.rearg`
       *  256 - `_.ary`
       *  512 - `_.flip`
       * @param {*} [thisArg] The `this` binding of `func`.
       * @param {Array} [partials] The arguments to be partially applied.
       * @param {Array} [holders] The `partials` placeholder indexes.
       * @param {Array} [argPos] The argument positions of the new function.
       * @param {number} [ary] The arity cap of `func`.
       * @param {number} [arity] The arity of `func`.
       * @returns {Function} Returns the new wrapped function.
       */
      function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
        var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4;
        if (!isBindKey && typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$1);
        }
        var length = partials ? partials.length : 0;
        if (!length) {
          bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2);
          partials = holders = undefined;
        }
        ary = ary === undefined ? ary : nativeMax$2(toInteger(ary), 0);
        arity = arity === undefined ? arity : toInteger(arity);
        length -= holders ? holders.length : 0;
        if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) {
          var partialsRight = partials,
            holdersRight = holders;
          partials = holders = undefined;
        }
        var data = isBindKey ? undefined : getData(func);
        var newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
        if (data) {
          mergeData(newData, data);
        }
        func = newData[0];
        bitmask = newData[1];
        thisArg = newData[2];
        partials = newData[3];
        holders = newData[4];
        arity = newData[9] = newData[9] === undefined ? isBindKey ? 0 : func.length : nativeMax$2(newData[9] - length, 0);
        if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) {
          bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2);
        }
        if (!bitmask || bitmask == WRAP_BIND_FLAG$6) {
          var result = createBind(func, bitmask, thisArg);
        } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) {
          result = createCurry(func, bitmask, arity);
        } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) {
          result = createPartial(func, bitmask, thisArg, partials);
        } else {
          result = createHybrid.apply(undefined, newData);
        }
        var setter = data ? baseSetData : setData;
        return setWrapToString(setter(result, newData), func, bitmask);
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_ARY_FLAG$3 = 128;

      /**
       * Creates a function that invokes `func`, with up to `n` arguments,
       * ignoring any additional arguments.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Function
       * @param {Function} func The function to cap arguments for.
       * @param {number} [n=func.length] The arity cap.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Function} Returns the new capped function.
       * @example
       *
       * _.map(['6', '8', '10'], _.ary(parseInt, 1));
       * // => [6, 8, 10]
       */
      function ary(func, n, guard) {
        n = guard ? undefined : n;
        n = func && n == null ? func.length : n;
        return createWrap(func, WRAP_ARY_FLAG$3, undefined, undefined, undefined, undefined, n);
      }

      /**
       * The base implementation of `assignValue` and `assignMergeValue` without
       * value checks.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {string} key The key of the property to assign.
       * @param {*} value The value to assign.
       */
      function baseAssignValue(object, key, value) {
        if (key == '__proto__' && defineProperty) {
          defineProperty(object, key, {
            'configurable': true,
            'enumerable': true,
            'value': value,
            'writable': true
          });
        } else {
          object[key] = value;
        }
      }

      /**
       * Performs a
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * comparison between two values to determine if they are equivalent.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
       * @example
       *
       * var object = { 'a': 1 };
       * var other = { 'a': 1 };
       *
       * _.eq(object, object);
       * // => true
       *
       * _.eq(object, other);
       * // => false
       *
       * _.eq('a', 'a');
       * // => true
       *
       * _.eq('a', Object('a'));
       * // => false
       *
       * _.eq(NaN, NaN);
       * // => true
       */
      function eq(value, other) {
        return value === other || value !== value && other !== other;
      }

      /** Used for built-in method references. */
      var objectProto$5 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$4 = objectProto$5.hasOwnProperty;

      /**
       * Assigns `value` to `key` of `object` if the existing value is not equivalent
       * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {string} key The key of the property to assign.
       * @param {*} value The value to assign.
       */
      function assignValue(object, key, value) {
        var objValue = object[key];
        if (!(hasOwnProperty$4.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) {
          baseAssignValue(object, key, value);
        }
      }

      /**
       * Copies properties of `source` to `object`.
       *
       * @private
       * @param {Object} source The object to copy properties from.
       * @param {Array} props The property identifiers to copy.
       * @param {Object} [object={}] The object to copy properties to.
       * @param {Function} [customizer] The function to customize copied values.
       * @returns {Object} Returns `object`.
       */
      function copyObject(source, props, object, customizer) {
        var isNew = !object;
        object || (object = {});
        var index = -1,
          length = props.length;
        while (++index < length) {
          var key = props[index];
          var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
          if (newValue === undefined) {
            newValue = source[key];
          }
          if (isNew) {
            baseAssignValue(object, key, newValue);
          } else {
            assignValue(object, key, newValue);
          }
        }
        return object;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$3 = Math.max;

      /**
       * A specialized version of `baseRest` which transforms the rest array.
       *
       * @private
       * @param {Function} func The function to apply a rest parameter to.
       * @param {number} [start=func.length-1] The start position of the rest parameter.
       * @param {Function} transform The rest array transform.
       * @returns {Function} Returns the new function.
       */
      function overRest(func, start, transform) {
        start = nativeMax$3(start === undefined ? func.length - 1 : start, 0);
        return function () {
          var args = arguments,
            index = -1,
            length = nativeMax$3(args.length - start, 0),
            array = Array(length);
          while (++index < length) {
            array[index] = args[start + index];
          }
          index = -1;
          var otherArgs = Array(start + 1);
          while (++index < start) {
            otherArgs[index] = args[index];
          }
          otherArgs[start] = transform(array);
          return apply(func, this, otherArgs);
        };
      }

      /**
       * The base implementation of `_.rest` which doesn't validate or coerce arguments.
       *
       * @private
       * @param {Function} func The function to apply a rest parameter to.
       * @param {number} [start=func.length-1] The start position of the rest parameter.
       * @returns {Function} Returns the new function.
       */
      function baseRest(func, start) {
        return setToString(overRest(func, start, identity), func + '');
      }

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER$1 = 9007199254740991;

      /**
       * Checks if `value` is a valid array-like length.
       *
       * **Note:** This method is loosely based on
       * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
       * @example
       *
       * _.isLength(3);
       * // => true
       *
       * _.isLength(Number.MIN_VALUE);
       * // => false
       *
       * _.isLength(Infinity);
       * // => false
       *
       * _.isLength('3');
       * // => false
       */
      function isLength(value) {
        return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
      }

      /**
       * Checks if `value` is array-like. A value is considered array-like if it's
       * not a function and has a `value.length` that's an integer greater than or
       * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
       * @example
       *
       * _.isArrayLike([1, 2, 3]);
       * // => true
       *
       * _.isArrayLike(document.body.children);
       * // => true
       *
       * _.isArrayLike('abc');
       * // => true
       *
       * _.isArrayLike(_.noop);
       * // => false
       */
      function isArrayLike(value) {
        return value != null && isLength(value.length) && !isFunction(value);
      }

      /**
       * Checks if the given arguments are from an iteratee call.
       *
       * @private
       * @param {*} value The potential iteratee value argument.
       * @param {*} index The potential iteratee index or key argument.
       * @param {*} object The potential iteratee object argument.
       * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
       *  else `false`.
       */
      function isIterateeCall(value, index, object) {
        if (!isObject(object)) {
          return false;
        }
        var type = typeof index;
        if (type == 'number' ? isArrayLike(object) && isIndex(index, object.length) : type == 'string' && index in object) {
          return eq(object[index], value);
        }
        return false;
      }

      /**
       * Creates a function like `_.assign`.
       *
       * @private
       * @param {Function} assigner The function to assign values.
       * @returns {Function} Returns the new assigner function.
       */
      function createAssigner(assigner) {
        return baseRest(function (object, sources) {
          var index = -1,
            length = sources.length,
            customizer = length > 1 ? sources[length - 1] : undefined,
            guard = length > 2 ? sources[2] : undefined;
          customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined;
          if (guard && isIterateeCall(sources[0], sources[1], guard)) {
            customizer = length < 3 ? undefined : customizer;
            length = 1;
          }
          object = Object(object);
          while (++index < length) {
            var source = sources[index];
            if (source) {
              assigner(object, source, index, customizer);
            }
          }
          return object;
        });
      }

      /** Used for built-in method references. */
      var objectProto$6 = Object.prototype;

      /**
       * Checks if `value` is likely a prototype object.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
       */
      function isPrototype(value) {
        var Ctor = value && value.constructor,
          proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$6;
        return value === proto;
      }

      /**
       * The base implementation of `_.times` without support for iteratee shorthands
       * or max array length checks.
       *
       * @private
       * @param {number} n The number of times to invoke `iteratee`.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array} Returns the array of results.
       */
      function baseTimes(n, iteratee) {
        var index = -1,
          result = Array(n);
        while (++index < n) {
          result[index] = iteratee(index);
        }
        return result;
      }

      /** `Object#toString` result references. */
      var argsTag = '[object Arguments]';

      /**
       * The base implementation of `_.isArguments`.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an `arguments` object,
       */
      function baseIsArguments(value) {
        return isObjectLike(value) && baseGetTag(value) == argsTag;
      }

      /** Used for built-in method references. */
      var objectProto$7 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$5 = objectProto$7.hasOwnProperty;

      /** Built-in value references. */
      var propertyIsEnumerable = objectProto$7.propertyIsEnumerable;

      /**
       * Checks if `value` is likely an `arguments` object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an `arguments` object,
       *  else `false`.
       * @example
       *
       * _.isArguments(function() { return arguments; }());
       * // => true
       *
       * _.isArguments([1, 2, 3]);
       * // => false
       */
      var isArguments = baseIsArguments(function () {
        return arguments;
      }()) ? baseIsArguments : function (value) {
        return isObjectLike(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
      };

      /**
       * This method returns `false`.
       *
       * @static
       * @memberOf _
       * @since 4.13.0
       * @category Util
       * @returns {boolean} Returns `false`.
       * @example
       *
       * _.times(2, _.stubFalse);
       * // => [false, false]
       */
      function stubFalse() {
        return false;
      }

      /** Detect free variable `exports`. */
      var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

      /** Detect free variable `module`. */
      var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

      /** Detect the popular CommonJS extension `module.exports`. */
      var moduleExports = freeModule && freeModule.exports === freeExports;

      /** Built-in value references. */
      var Buffer = moduleExports ? root.Buffer : undefined;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

      /**
       * Checks if `value` is a buffer.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
       * @example
       *
       * _.isBuffer(new Buffer(2));
       * // => true
       *
       * _.isBuffer(new Uint8Array(2));
       * // => false
       */
      var isBuffer = nativeIsBuffer || stubFalse;

      /** `Object#toString` result references. */
      var argsTag$1 = '[object Arguments]',
        arrayTag = '[object Array]',
        boolTag = '[object Boolean]',
        dateTag = '[object Date]',
        errorTag = '[object Error]',
        funcTag$1 = '[object Function]',
        mapTag = '[object Map]',
        numberTag = '[object Number]',
        objectTag = '[object Object]',
        regexpTag = '[object RegExp]',
        setTag = '[object Set]',
        stringTag = '[object String]',
        weakMapTag = '[object WeakMap]';
      var arrayBufferTag = '[object ArrayBuffer]',
        dataViewTag = '[object DataView]',
        float32Tag = '[object Float32Array]',
        float64Tag = '[object Float64Array]',
        int8Tag = '[object Int8Array]',
        int16Tag = '[object Int16Array]',
        int32Tag = '[object Int32Array]',
        uint8Tag = '[object Uint8Array]',
        uint8ClampedTag = '[object Uint8ClampedArray]',
        uint16Tag = '[object Uint16Array]',
        uint32Tag = '[object Uint32Array]';

      /** Used to identify `toStringTag` values of typed arrays. */
      var typedArrayTags = {};
      typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
      typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;

      /**
       * The base implementation of `_.isTypedArray` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
       */
      function baseIsTypedArray(value) {
        return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
      }

      /**
       * The base implementation of `_.unary` without support for storing metadata.
       *
       * @private
       * @param {Function} func The function to cap arguments for.
       * @returns {Function} Returns the new capped function.
       */
      function baseUnary(func) {
        return function (value) {
          return func(value);
        };
      }

      /** Detect free variable `exports`. */
      var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;

      /** Detect free variable `module`. */
      var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;

      /** Detect the popular CommonJS extension `module.exports`. */
      var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;

      /** Detect free variable `process` from Node.js. */
      var freeProcess = moduleExports$1 && freeGlobal.process;

      /** Used to access faster Node.js helpers. */
      var nodeUtil = function () {
        try {
          // Use `util.types` for Node.js 10+.
          var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
          if (types) {
            return types;
          }

          // Legacy `process.binding('util')` for Node.js < 10.
          return freeProcess && freeProcess.binding && freeProcess.binding('util');
        } catch (e) {}
      }();

      /* Node.js helper references. */
      var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

      /**
       * Checks if `value` is classified as a typed array.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
       * @example
       *
       * _.isTypedArray(new Uint8Array);
       * // => true
       *
       * _.isTypedArray([]);
       * // => false
       */
      var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;

      /** Used for built-in method references. */
      var objectProto$8 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$6 = objectProto$8.hasOwnProperty;

      /**
       * Creates an array of the enumerable property names of the array-like `value`.
       *
       * @private
       * @param {*} value The value to query.
       * @param {boolean} inherited Specify returning inherited property names.
       * @returns {Array} Returns the array of property names.
       */
      function arrayLikeKeys(value, inherited) {
        var isArr = isArray$1(value),
          isArg = !isArr && isArguments(value),
          isBuff = !isArr && !isArg && isBuffer(value),
          isType = !isArr && !isArg && !isBuff && isTypedArray(value),
          skipIndexes = isArr || isArg || isBuff || isType,
          result = skipIndexes ? baseTimes(value.length, String) : [],
          length = result.length;
        for (var key in value) {
          if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && (
          // Safari 9 has enumerable `arguments.length` in strict mode.
          key == 'length' ||
          // Node.js 0.10 has enumerable non-index properties on buffers.
          isBuff && (key == 'offset' || key == 'parent') ||
          // PhantomJS 2 has enumerable non-index properties on typed arrays.
          isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
          // Skip index properties.
          isIndex(key, length)))) {
            result.push(key);
          }
        }
        return result;
      }

      /**
       * Creates a unary function that invokes `func` with its argument transformed.
       *
       * @private
       * @param {Function} func The function to wrap.
       * @param {Function} transform The argument transform.
       * @returns {Function} Returns the new function.
       */
      function overArg(func, transform) {
        return function (arg) {
          return func(transform(arg));
        };
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeKeys = overArg(Object.keys, Object);

      /** Used for built-in method references. */
      var objectProto$9 = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$7 = objectProto$9.hasOwnProperty;

      /**
       * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names.
       */
      function baseKeys(object) {
        if (!isPrototype(object)) {
          return nativeKeys(object);
        }
        var result = [];
        for (var key in Object(object)) {
          if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
            result.push(key);
          }
        }
        return result;
      }

      /**
       * Creates an array of the own enumerable property names of `object`.
       *
       * **Note:** Non-object values are coerced to objects. See the
       * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
       * for more details.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.keys(new Foo);
       * // => ['a', 'b'] (iteration order is not guaranteed)
       *
       * _.keys('hi');
       * // => ['0', '1']
       */
      function keys(object) {
        return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
      }

      /** Used for built-in method references. */
      var objectProto$a = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$8 = objectProto$a.hasOwnProperty;

      /**
       * Assigns own enumerable string keyed properties of source objects to the
       * destination object. Source objects are applied from left to right.
       * Subsequent sources overwrite property assignments of previous sources.
       *
       * **Note:** This method mutates `object` and is loosely based on
       * [`Object.assign`](https://mdn.io/Object/assign).
       *
       * @static
       * @memberOf _
       * @since 0.10.0
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} [sources] The source objects.
       * @returns {Object} Returns `object`.
       * @see _.assignIn
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       * }
       *
       * function Bar() {
       *   this.c = 3;
       * }
       *
       * Foo.prototype.b = 2;
       * Bar.prototype.d = 4;
       *
       * _.assign({ 'a': 0 }, new Foo, new Bar);
       * // => { 'a': 1, 'c': 3 }
       */
      var assign$1 = createAssigner(function (object, source) {
        if (isPrototype(source) || isArrayLike(source)) {
          copyObject(source, keys(source), object);
          return;
        }
        for (var key in source) {
          if (hasOwnProperty$8.call(source, key)) {
            assignValue(object, key, source[key]);
          }
        }
      });

      /**
       * This function is like
       * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
       * except that it includes inherited enumerable properties.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names.
       */
      function nativeKeysIn(object) {
        var result = [];
        if (object != null) {
          for (var key in Object(object)) {
            result.push(key);
          }
        }
        return result;
      }

      /** Used for built-in method references. */
      var objectProto$b = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$9 = objectProto$b.hasOwnProperty;

      /**
       * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names.
       */
      function baseKeysIn(object) {
        if (!isObject(object)) {
          return nativeKeysIn(object);
        }
        var isProto = isPrototype(object),
          result = [];
        for (var key in object) {
          if (!(key == 'constructor' && (isProto || !hasOwnProperty$9.call(object, key)))) {
            result.push(key);
          }
        }
        return result;
      }

      /**
       * Creates an array of the own and inherited enumerable property names of `object`.
       *
       * **Note:** Non-object values are coerced to objects.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.keysIn(new Foo);
       * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
       */
      function keysIn(object) {
        return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
      }

      /**
       * This method is like `_.assign` except that it iterates over own and
       * inherited source properties.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @alias extend
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} [sources] The source objects.
       * @returns {Object} Returns `object`.
       * @see _.assign
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       * }
       *
       * function Bar() {
       *   this.c = 3;
       * }
       *
       * Foo.prototype.b = 2;
       * Bar.prototype.d = 4;
       *
       * _.assignIn({ 'a': 0 }, new Foo, new Bar);
       * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
       */
      var assignIn = createAssigner(function (object, source) {
        copyObject(source, keysIn(source), object);
      });

      /**
       * This method is like `_.assignIn` except that it accepts `customizer`
       * which is invoked to produce the assigned values. If `customizer` returns
       * `undefined`, assignment is handled by the method instead. The `customizer`
       * is invoked with five arguments: (objValue, srcValue, key, object, source).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @alias extendWith
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} sources The source objects.
       * @param {Function} [customizer] The function to customize assigned values.
       * @returns {Object} Returns `object`.
       * @see _.assignWith
       * @example
       *
       * function customizer(objValue, srcValue) {
       *   return _.isUndefined(objValue) ? srcValue : objValue;
       * }
       *
       * var defaults = _.partialRight(_.assignInWith, customizer);
       *
       * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
       * // => { 'a': 1, 'b': 2 }
       */
      var assignInWith = createAssigner(function (object, source, srcIndex, customizer) {
        copyObject(source, keysIn(source), object, customizer);
      });

      /**
       * This method is like `_.assign` except that it accepts `customizer`
       * which is invoked to produce the assigned values. If `customizer` returns
       * `undefined`, assignment is handled by the method instead. The `customizer`
       * is invoked with five arguments: (objValue, srcValue, key, object, source).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} sources The source objects.
       * @param {Function} [customizer] The function to customize assigned values.
       * @returns {Object} Returns `object`.
       * @see _.assignInWith
       * @example
       *
       * function customizer(objValue, srcValue) {
       *   return _.isUndefined(objValue) ? srcValue : objValue;
       * }
       *
       * var defaults = _.partialRight(_.assignWith, customizer);
       *
       * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
       * // => { 'a': 1, 'b': 2 }
       */
      var assignWith = createAssigner(function (object, source, srcIndex, customizer) {
        copyObject(source, keys(source), object, customizer);
      });

      /** Used to match property names within property paths. */
      var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
        reIsPlainProp = /^\w*$/;

      /**
       * Checks if `value` is a property name and not a property path.
       *
       * @private
       * @param {*} value The value to check.
       * @param {Object} [object] The object to query keys on.
       * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
       */
      function isKey(value, object) {
        if (isArray$1(value)) {
          return false;
        }
        var type = typeof value;
        if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
          return true;
        }
        return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
      }

      /* Built-in method references that are verified to be native. */
      var nativeCreate = getNative(Object, 'create');

      /**
       * Removes all key-value entries from the hash.
       *
       * @private
       * @name clear
       * @memberOf Hash
       */
      function hashClear() {
        this.__data__ = nativeCreate ? nativeCreate(null) : {};
        this.size = 0;
      }

      /**
       * Removes `key` and its value from the hash.
       *
       * @private
       * @name delete
       * @memberOf Hash
       * @param {Object} hash The hash to modify.
       * @param {string} key The key of the value to remove.
       * @returns {boolean} Returns `true` if the entry was removed, else `false`.
       */
      function hashDelete(key) {
        var result = this.has(key) && delete this.__data__[key];
        this.size -= result ? 1 : 0;
        return result;
      }

      /** Used to stand-in for `undefined` hash values. */
      var HASH_UNDEFINED = '__lodash_hash_undefined__';

      /** Used for built-in method references. */
      var objectProto$c = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$a = objectProto$c.hasOwnProperty;

      /**
       * Gets the hash value for `key`.
       *
       * @private
       * @name get
       * @memberOf Hash
       * @param {string} key The key of the value to get.
       * @returns {*} Returns the entry value.
       */
      function hashGet(key) {
        var data = this.__data__;
        if (nativeCreate) {
          var result = data[key];
          return result === HASH_UNDEFINED ? undefined : result;
        }
        return hasOwnProperty$a.call(data, key) ? data[key] : undefined;
      }

      /** Used for built-in method references. */
      var objectProto$d = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$b = objectProto$d.hasOwnProperty;

      /**
       * Checks if a hash value for `key` exists.
       *
       * @private
       * @name has
       * @memberOf Hash
       * @param {string} key The key of the entry to check.
       * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
       */
      function hashHas(key) {
        var data = this.__data__;
        return nativeCreate ? data[key] !== undefined : hasOwnProperty$b.call(data, key);
      }

      /** Used to stand-in for `undefined` hash values. */
      var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';

      /**
       * Sets the hash `key` to `value`.
       *
       * @private
       * @name set
       * @memberOf Hash
       * @param {string} key The key of the value to set.
       * @param {*} value The value to set.
       * @returns {Object} Returns the hash instance.
       */
      function hashSet(key, value) {
        var data = this.__data__;
        this.size += this.has(key) ? 0 : 1;
        data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
        return this;
      }

      /**
       * Creates a hash object.
       *
       * @private
       * @constructor
       * @param {Array} [entries] The key-value pairs to cache.
       */
      function Hash(entries) {
        var index = -1,
          length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index < length) {
          var entry = entries[index];
          this.set(entry[0], entry[1]);
        }
      }

      // Add methods to `Hash`.
      Hash.prototype.clear = hashClear;
      Hash.prototype['delete'] = hashDelete;
      Hash.prototype.get = hashGet;
      Hash.prototype.has = hashHas;
      Hash.prototype.set = hashSet;

      /**
       * Removes all key-value entries from the list cache.
       *
       * @private
       * @name clear
       * @memberOf ListCache
       */
      function listCacheClear() {
        this.__data__ = [];
        this.size = 0;
      }

      /**
       * Gets the index at which the `key` is found in `array` of key-value pairs.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} key The key to search for.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function assocIndexOf(array, key) {
        var length = array.length;
        while (length--) {
          if (eq(array[length][0], key)) {
            return length;
          }
        }
        return -1;
      }

      /** Used for built-in method references. */
      var arrayProto = Array.prototype;

      /** Built-in value references. */
      var splice = arrayProto.splice;

      /**
       * Removes `key` and its value from the list cache.
       *
       * @private
       * @name delete
       * @memberOf ListCache
       * @param {string} key The key of the value to remove.
       * @returns {boolean} Returns `true` if the entry was removed, else `false`.
       */
      function listCacheDelete(key) {
        var data = this.__data__,
          index = assocIndexOf(data, key);
        if (index < 0) {
          return false;
        }
        var lastIndex = data.length - 1;
        if (index == lastIndex) {
          data.pop();
        } else {
          splice.call(data, index, 1);
        }
        --this.size;
        return true;
      }

      /**
       * Gets the list cache value for `key`.
       *
       * @private
       * @name get
       * @memberOf ListCache
       * @param {string} key The key of the value to get.
       * @returns {*} Returns the entry value.
       */
      function listCacheGet(key) {
        var data = this.__data__,
          index = assocIndexOf(data, key);
        return index < 0 ? undefined : data[index][1];
      }

      /**
       * Checks if a list cache value for `key` exists.
       *
       * @private
       * @name has
       * @memberOf ListCache
       * @param {string} key The key of the entry to check.
       * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
       */
      function listCacheHas(key) {
        return assocIndexOf(this.__data__, key) > -1;
      }

      /**
       * Sets the list cache `key` to `value`.
       *
       * @private
       * @name set
       * @memberOf ListCache
       * @param {string} key The key of the value to set.
       * @param {*} value The value to set.
       * @returns {Object} Returns the list cache instance.
       */
      function listCacheSet(key, value) {
        var data = this.__data__,
          index = assocIndexOf(data, key);
        if (index < 0) {
          ++this.size;
          data.push([key, value]);
        } else {
          data[index][1] = value;
        }
        return this;
      }

      /**
       * Creates an list cache object.
       *
       * @private
       * @constructor
       * @param {Array} [entries] The key-value pairs to cache.
       */
      function ListCache(entries) {
        var index = -1,
          length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index < length) {
          var entry = entries[index];
          this.set(entry[0], entry[1]);
        }
      }

      // Add methods to `ListCache`.
      ListCache.prototype.clear = listCacheClear;
      ListCache.prototype['delete'] = listCacheDelete;
      ListCache.prototype.get = listCacheGet;
      ListCache.prototype.has = listCacheHas;
      ListCache.prototype.set = listCacheSet;

      /* Built-in method references that are verified to be native. */
      var Map$1 = getNative(root, 'Map');

      /**
       * Removes all key-value entries from the map.
       *
       * @private
       * @name clear
       * @memberOf MapCache
       */
      function mapCacheClear() {
        this.size = 0;
        this.__data__ = {
          'hash': new Hash(),
          'map': new (Map$1 || ListCache)(),
          'string': new Hash()
        };
      }

      /**
       * Checks if `value` is suitable for use as unique object key.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
       */
      function isKeyable(value) {
        var type = typeof value;
        return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
      }

      /**
       * Gets the data for `map`.
       *
       * @private
       * @param {Object} map The map to query.
       * @param {string} key The reference key.
       * @returns {*} Returns the map data.
       */
      function getMapData(map, key) {
        var data = map.__data__;
        return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
      }

      /**
       * Removes `key` and its value from the map.
       *
       * @private
       * @name delete
       * @memberOf MapCache
       * @param {string} key The key of the value to remove.
       * @returns {boolean} Returns `true` if the entry was removed, else `false`.
       */
      function mapCacheDelete(key) {
        var result = getMapData(this, key)['delete'](key);
        this.size -= result ? 1 : 0;
        return result;
      }

      /**
       * Gets the map value for `key`.
       *
       * @private
       * @name get
       * @memberOf MapCache
       * @param {string} key The key of the value to get.
       * @returns {*} Returns the entry value.
       */
      function mapCacheGet(key) {
        return getMapData(this, key).get(key);
      }

      /**
       * Checks if a map value for `key` exists.
       *
       * @private
       * @name has
       * @memberOf MapCache
       * @param {string} key The key of the entry to check.
       * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
       */
      function mapCacheHas(key) {
        return getMapData(this, key).has(key);
      }

      /**
       * Sets the map `key` to `value`.
       *
       * @private
       * @name set
       * @memberOf MapCache
       * @param {string} key The key of the value to set.
       * @param {*} value The value to set.
       * @returns {Object} Returns the map cache instance.
       */
      function mapCacheSet(key, value) {
        var data = getMapData(this, key),
          size = data.size;
        data.set(key, value);
        this.size += data.size == size ? 0 : 1;
        return this;
      }

      /**
       * Creates a map cache object to store key-value pairs.
       *
       * @private
       * @constructor
       * @param {Array} [entries] The key-value pairs to cache.
       */
      function MapCache(entries) {
        var index = -1,
          length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index < length) {
          var entry = entries[index];
          this.set(entry[0], entry[1]);
        }
      }

      // Add methods to `MapCache`.
      MapCache.prototype.clear = mapCacheClear;
      MapCache.prototype['delete'] = mapCacheDelete;
      MapCache.prototype.get = mapCacheGet;
      MapCache.prototype.has = mapCacheHas;
      MapCache.prototype.set = mapCacheSet;

      /** Error message constants. */
      var FUNC_ERROR_TEXT$2 = 'Expected a function';

      /**
       * Creates a function that memoizes the result of `func`. If `resolver` is
       * provided, it determines the cache key for storing the result based on the
       * arguments provided to the memoized function. By default, the first argument
       * provided to the memoized function is used as the map cache key. The `func`
       * is invoked with the `this` binding of the memoized function.
       *
       * **Note:** The cache is exposed as the `cache` property on the memoized
       * function. Its creation may be customized by replacing the `_.memoize.Cache`
       * constructor with one whose instances implement the
       * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
       * method interface of `clear`, `delete`, `get`, `has`, and `set`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to have its output memoized.
       * @param {Function} [resolver] The function to resolve the cache key.
       * @returns {Function} Returns the new memoized function.
       * @example
       *
       * var object = { 'a': 1, 'b': 2 };
       * var other = { 'c': 3, 'd': 4 };
       *
       * var values = _.memoize(_.values);
       * values(object);
       * // => [1, 2]
       *
       * values(other);
       * // => [3, 4]
       *
       * object.a = 2;
       * values(object);
       * // => [1, 2]
       *
       * // Modify the result cache.
       * values.cache.set(object, ['a', 'b']);
       * values(object);
       * // => ['a', 'b']
       *
       * // Replace `_.memoize.Cache`.
       * _.memoize.Cache = WeakMap;
       */
      function memoize(func, resolver) {
        if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$2);
        }
        var memoized = function memoized() {
          var args = arguments,
            key = resolver ? resolver.apply(this, args) : args[0],
            cache = memoized.cache;
          if (cache.has(key)) {
            return cache.get(key);
          }
          var result = func.apply(this, args);
          memoized.cache = cache.set(key, result) || cache;
          return result;
        };
        memoized.cache = new (memoize.Cache || MapCache)();
        return memoized;
      }

      // Expose `MapCache`.
      memoize.Cache = MapCache;

      /** Used as the maximum memoize cache size. */
      var MAX_MEMOIZE_SIZE = 500;

      /**
       * A specialized version of `_.memoize` which clears the memoized function's
       * cache when it exceeds `MAX_MEMOIZE_SIZE`.
       *
       * @private
       * @param {Function} func The function to have its output memoized.
       * @returns {Function} Returns the new memoized function.
       */
      function memoizeCapped(func) {
        var result = memoize(func, function (key) {
          if (cache.size === MAX_MEMOIZE_SIZE) {
            cache.clear();
          }
          return key;
        });
        var cache = result.cache;
        return result;
      }

      /** Used to match property names within property paths. */
      var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

      /** Used to match backslashes in property paths. */
      var reEscapeChar = /\\(\\)?/g;

      /**
       * Converts `string` to a property path array.
       *
       * @private
       * @param {string} string The string to convert.
       * @returns {Array} Returns the property path array.
       */
      var stringToPath = memoizeCapped(function (string) {
        var result = [];
        if (string.charCodeAt(0) === 46 /* . */) {
          result.push('');
        }
        string.replace(rePropName, function (match, number, quote, subString) {
          result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
        });
        return result;
      });

      /**
       * Converts `value` to a string. An empty string is returned for `null`
       * and `undefined` values. The sign of `-0` is preserved.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {string} Returns the converted string.
       * @example
       *
       * _.toString(null);
       * // => ''
       *
       * _.toString(-0);
       * // => '-0'
       *
       * _.toString([1, 2, 3]);
       * // => '1,2,3'
       */
      function toString(value) {
        return value == null ? '' : baseToString(value);
      }

      /**
       * Casts `value` to a path array if it's not one.
       *
       * @private
       * @param {*} value The value to inspect.
       * @param {Object} [object] The object to query keys on.
       * @returns {Array} Returns the cast property path array.
       */
      function castPath(value, object) {
        if (isArray$1(value)) {
          return value;
        }
        return isKey(value, object) ? [value] : stringToPath(toString(value));
      }

      /** Used as references for various `Number` constants. */
      var INFINITY$2 = 1 / 0;

      /**
       * Converts `value` to a string key if it's not a string or symbol.
       *
       * @private
       * @param {*} value The value to inspect.
       * @returns {string|symbol} Returns the key.
       */
      function toKey(value) {
        if (typeof value == 'string' || isSymbol(value)) {
          return value;
        }
        var result = value + '';
        return result == '0' && 1 / value == -INFINITY$2 ? '-0' : result;
      }

      /**
       * The base implementation of `_.get` without support for default values.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array|string} path The path of the property to get.
       * @returns {*} Returns the resolved value.
       */
      function baseGet(object, path) {
        path = castPath(path, object);
        var index = 0,
          length = path.length;
        while (object != null && index < length) {
          object = object[toKey(path[index++])];
        }
        return index && index == length ? object : undefined;
      }

      /**
       * Gets the value at `path` of `object`. If the resolved value is
       * `undefined`, the `defaultValue` is returned in its place.
       *
       * @static
       * @memberOf _
       * @since 3.7.0
       * @category Object
       * @param {Object} object The object to query.
       * @param {Array|string} path The path of the property to get.
       * @param {*} [defaultValue] The value returned for `undefined` resolved values.
       * @returns {*} Returns the resolved value.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 3 } }] };
       *
       * _.get(object, 'a[0].b.c');
       * // => 3
       *
       * _.get(object, ['a', '0', 'b', 'c']);
       * // => 3
       *
       * _.get(object, 'a.b.c', 'default');
       * // => 'default'
       */
      function get(object, path, defaultValue) {
        var result = object == null ? undefined : baseGet(object, path);
        return result === undefined ? defaultValue : result;
      }

      /**
       * The base implementation of `_.at` without support for individual paths.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {string[]} paths The property paths to pick.
       * @returns {Array} Returns the picked elements.
       */
      function baseAt(object, paths) {
        var index = -1,
          length = paths.length,
          result = Array(length),
          skip = object == null;
        while (++index < length) {
          result[index] = skip ? undefined : get(object, paths[index]);
        }
        return result;
      }

      /**
       * Appends the elements of `values` to `array`.
       *
       * @private
       * @param {Array} array The array to modify.
       * @param {Array} values The values to append.
       * @returns {Array} Returns `array`.
       */
      function arrayPush(array, values) {
        var index = -1,
          length = values.length,
          offset = array.length;
        while (++index < length) {
          array[offset + index] = values[index];
        }
        return array;
      }

      /** Built-in value references. */
      var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined;

      /**
       * Checks if `value` is a flattenable `arguments` object or array.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
       */
      function isFlattenable(value) {
        return isArray$1(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
      }

      /**
       * The base implementation of `_.flatten` with support for restricting flattening.
       *
       * @private
       * @param {Array} array The array to flatten.
       * @param {number} depth The maximum recursion depth.
       * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
       * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
       * @param {Array} [result=[]] The initial result value.
       * @returns {Array} Returns the new flattened array.
       */
      function baseFlatten(array, depth, predicate, isStrict, result) {
        var index = -1,
          length = array.length;
        predicate || (predicate = isFlattenable);
        result || (result = []);
        while (++index < length) {
          var value = array[index];
          if (depth > 0 && predicate(value)) {
            if (depth > 1) {
              // Recursively flatten arrays (susceptible to call stack limits).
              baseFlatten(value, depth - 1, predicate, isStrict, result);
            } else {
              arrayPush(result, value);
            }
          } else if (!isStrict) {
            result[result.length] = value;
          }
        }
        return result;
      }

      /**
       * Flattens `array` a single level deep.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to flatten.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * _.flatten([1, [2, [3, [4]], 5]]);
       * // => [1, 2, [3, [4]], 5]
       */
      function flatten(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseFlatten(array, 1) : [];
      }

      /**
       * A specialized version of `baseRest` which flattens the rest array.
       *
       * @private
       * @param {Function} func The function to apply a rest parameter to.
       * @returns {Function} Returns the new function.
       */
      function flatRest(func) {
        return setToString(overRest(func, undefined, flatten), func + '');
      }

      /**
       * Creates an array of values corresponding to `paths` of `object`.
       *
       * @static
       * @memberOf _
       * @since 1.0.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {...(string|string[])} [paths] The property paths to pick.
       * @returns {Array} Returns the picked values.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
       *
       * _.at(object, ['a[0].b.c', 'a[1]']);
       * // => [3, 4]
       */
      var at = flatRest(baseAt);

      /** Built-in value references. */
      var getPrototype = overArg(Object.getPrototypeOf, Object);

      /** `Object#toString` result references. */
      var objectTag$1 = '[object Object]';

      /** Used for built-in method references. */
      var funcProto$2 = Function.prototype,
        objectProto$e = Object.prototype;

      /** Used to resolve the decompiled source of functions. */
      var funcToString$2 = funcProto$2.toString;

      /** Used to check objects for own properties. */
      var hasOwnProperty$c = objectProto$e.hasOwnProperty;

      /** Used to infer the `Object` constructor. */
      var objectCtorString = funcToString$2.call(Object);

      /**
       * Checks if `value` is a plain object, that is, an object created by the
       * `Object` constructor or one with a `[[Prototype]]` of `null`.
       *
       * @static
       * @memberOf _
       * @since 0.8.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       * }
       *
       * _.isPlainObject(new Foo);
       * // => false
       *
       * _.isPlainObject([1, 2, 3]);
       * // => false
       *
       * _.isPlainObject({ 'x': 0, 'y': 0 });
       * // => true
       *
       * _.isPlainObject(Object.create(null));
       * // => true
       */
      function isPlainObject(value) {
        if (!isObjectLike(value) || baseGetTag(value) != objectTag$1) {
          return false;
        }
        var proto = getPrototype(value);
        if (proto === null) {
          return true;
        }
        var Ctor = hasOwnProperty$c.call(proto, 'constructor') && proto.constructor;
        return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString;
      }

      /** `Object#toString` result references. */
      var domExcTag = '[object DOMException]',
        errorTag$1 = '[object Error]';

      /**
       * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
       * `SyntaxError`, `TypeError`, or `URIError` object.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
       * @example
       *
       * _.isError(new Error);
       * // => true
       *
       * _.isError(Error);
       * // => false
       */
      function isError(value) {
        if (!isObjectLike(value)) {
          return false;
        }
        var tag = baseGetTag(value);
        return tag == errorTag$1 || tag == domExcTag || typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value);
      }

      /**
       * Attempts to invoke `func`, returning either the result or the caught error
       * object. Any additional arguments are provided to `func` when it's invoked.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Util
       * @param {Function} func The function to attempt.
       * @param {...*} [args] The arguments to invoke `func` with.
       * @returns {*} Returns the `func` result or error object.
       * @example
       *
       * // Avoid throwing errors for invalid selectors.
       * var elements = _.attempt(function(selector) {
       *   return document.querySelectorAll(selector);
       * }, '>_>');
       *
       * if (_.isError(elements)) {
       *   elements = [];
       * }
       */
      var attempt = baseRest(function (func, args) {
        try {
          return apply(func, undefined, args);
        } catch (e) {
          return isError(e) ? e : new Error(e);
        }
      });

      /** Error message constants. */
      var FUNC_ERROR_TEXT$3 = 'Expected a function';

      /**
       * Creates a function that invokes `func`, with the `this` binding and arguments
       * of the created function, while it's called less than `n` times. Subsequent
       * calls to the created function return the result of the last `func` invocation.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Function
       * @param {number} n The number of calls at which `func` is no longer invoked.
       * @param {Function} func The function to restrict.
       * @returns {Function} Returns the new restricted function.
       * @example
       *
       * jQuery(element).on('click', _.before(5, addContactToList));
       * // => Allows adding up to 4 contacts to the list.
       */
      function before(n, func) {
        var result;
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$3);
        }
        n = toInteger(n);
        return function () {
          if (--n > 0) {
            result = func.apply(this, arguments);
          }
          if (n <= 1) {
            func = undefined;
          }
          return result;
        };
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$7 = 1,
        WRAP_PARTIAL_FLAG$3 = 32;

      /**
       * Creates a function that invokes `func` with the `this` binding of `thisArg`
       * and `partials` prepended to the arguments it receives.
       *
       * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
       * may be used as a placeholder for partially applied arguments.
       *
       * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
       * property of bound functions.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to bind.
       * @param {*} thisArg The `this` binding of `func`.
       * @param {...*} [partials] The arguments to be partially applied.
       * @returns {Function} Returns the new bound function.
       * @example
       *
       * function greet(greeting, punctuation) {
       *   return greeting + ' ' + this.user + punctuation;
       * }
       *
       * var object = { 'user': 'fred' };
       *
       * var bound = _.bind(greet, object, 'hi');
       * bound('!');
       * // => 'hi fred!'
       *
       * // Bound with placeholders.
       * var bound = _.bind(greet, object, _, '!');
       * bound('hi');
       * // => 'hi fred!'
       */
      var bind = baseRest(function (func, thisArg, partials) {
        var bitmask = WRAP_BIND_FLAG$7;
        if (partials.length) {
          var holders = replaceHolders(partials, getHolder(bind));
          bitmask |= WRAP_PARTIAL_FLAG$3;
        }
        return createWrap(func, bitmask, thisArg, partials, holders);
      });

      // Assign default placeholders.
      bind.placeholder = {};

      /**
       * Binds methods of an object to the object itself, overwriting the existing
       * method.
       *
       * **Note:** This method doesn't set the "length" property of bound functions.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {Object} object The object to bind and assign the bound methods to.
       * @param {...(string|string[])} methodNames The object method names to bind.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var view = {
       *   'label': 'docs',
       *   'click': function() {
       *     console.log('clicked ' + this.label);
       *   }
       * };
       *
       * _.bindAll(view, ['click']);
       * jQuery(element).on('click', view.click);
       * // => Logs 'clicked docs' when clicked.
       */
      var bindAll = flatRest(function (object, methodNames) {
        arrayEach(methodNames, function (key) {
          key = toKey(key);
          baseAssignValue(object, key, bind(object[key], object));
        });
        return object;
      });

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_FLAG$8 = 1,
        WRAP_BIND_KEY_FLAG$5 = 2,
        WRAP_PARTIAL_FLAG$4 = 32;

      /**
       * Creates a function that invokes the method at `object[key]` with `partials`
       * prepended to the arguments it receives.
       *
       * This method differs from `_.bind` by allowing bound functions to reference
       * methods that may be redefined or don't yet exist. See
       * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
       * for more details.
       *
       * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
       * builds, may be used as a placeholder for partially applied arguments.
       *
       * @static
       * @memberOf _
       * @since 0.10.0
       * @category Function
       * @param {Object} object The object to invoke the method on.
       * @param {string} key The key of the method.
       * @param {...*} [partials] The arguments to be partially applied.
       * @returns {Function} Returns the new bound function.
       * @example
       *
       * var object = {
       *   'user': 'fred',
       *   'greet': function(greeting, punctuation) {
       *     return greeting + ' ' + this.user + punctuation;
       *   }
       * };
       *
       * var bound = _.bindKey(object, 'greet', 'hi');
       * bound('!');
       * // => 'hi fred!'
       *
       * object.greet = function(greeting, punctuation) {
       *   return greeting + 'ya ' + this.user + punctuation;
       * };
       *
       * bound('!');
       * // => 'hiya fred!'
       *
       * // Bound with placeholders.
       * var bound = _.bindKey(object, 'greet', _, '!');
       * bound('hi');
       * // => 'hiya fred!'
       */
      var bindKey = baseRest(function (object, key, partials) {
        var bitmask = WRAP_BIND_FLAG$8 | WRAP_BIND_KEY_FLAG$5;
        if (partials.length) {
          var holders = replaceHolders(partials, getHolder(bindKey));
          bitmask |= WRAP_PARTIAL_FLAG$4;
        }
        return createWrap(key, bitmask, object, partials, holders);
      });

      // Assign default placeholders.
      bindKey.placeholder = {};

      /**
       * The base implementation of `_.slice` without an iteratee call guard.
       *
       * @private
       * @param {Array} array The array to slice.
       * @param {number} [start=0] The start position.
       * @param {number} [end=array.length] The end position.
       * @returns {Array} Returns the slice of `array`.
       */
      function baseSlice(array, start, end) {
        var index = -1,
          length = array.length;
        if (start < 0) {
          start = -start > length ? 0 : length + start;
        }
        end = end > length ? length : end;
        if (end < 0) {
          end += length;
        }
        length = start > end ? 0 : end - start >>> 0;
        start >>>= 0;
        var result = Array(length);
        while (++index < length) {
          result[index] = array[index + start];
        }
        return result;
      }

      /**
       * Casts `array` to a slice if it's needed.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {number} start The start position.
       * @param {number} [end=array.length] The end position.
       * @returns {Array} Returns the cast slice.
       */
      function castSlice(array, start, end) {
        var length = array.length;
        end = end === undefined ? length : end;
        return !start && end >= length ? array : baseSlice(array, start, end);
      }

      /** Used to compose unicode character classes. */
      var rsAstralRange = "\\ud800-\\udfff",
        rsComboMarksRange = "\\u0300-\\u036f",
        reComboHalfMarksRange = "\\ufe20-\\ufe2f",
        rsComboSymbolsRange = "\\u20d0-\\u20ff",
        rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
        rsVarRange = "\\ufe0e\\ufe0f";

      /** Used to compose unicode capture groups. */
      var rsZWJ = "\\u200d";

      /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
      var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');

      /**
       * Checks if `string` contains Unicode symbols.
       *
       * @private
       * @param {string} string The string to inspect.
       * @returns {boolean} Returns `true` if a symbol is found, else `false`.
       */
      function hasUnicode(string) {
        return reHasUnicode.test(string);
      }

      /**
       * Converts an ASCII `string` to an array.
       *
       * @private
       * @param {string} string The string to convert.
       * @returns {Array} Returns the converted array.
       */
      function asciiToArray(string) {
        return string.split('');
      }

      /** Used to compose unicode character classes. */
      var rsAstralRange$1 = "\\ud800-\\udfff",
        rsComboMarksRange$1 = "\\u0300-\\u036f",
        reComboHalfMarksRange$1 = "\\ufe20-\\ufe2f",
        rsComboSymbolsRange$1 = "\\u20d0-\\u20ff",
        rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,
        rsVarRange$1 = "\\ufe0e\\ufe0f";

      /** Used to compose unicode capture groups. */
      var rsAstral = '[' + rsAstralRange$1 + ']',
        rsCombo = '[' + rsComboRange$1 + ']',
        rsFitz = "\\ud83c[\\udffb-\\udfff]",
        rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
        rsNonAstral = '[^' + rsAstralRange$1 + ']',
        rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}",
        rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]",
        rsZWJ$1 = "\\u200d";

      /** Used to compose unicode regexes. */
      var reOptMod = rsModifier + '?',
        rsOptVar = '[' + rsVarRange$1 + ']?',
        rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
        rsSeq = rsOptVar + reOptMod + rsOptJoin,
        rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';

      /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
      var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');

      /**
       * Converts a Unicode `string` to an array.
       *
       * @private
       * @param {string} string The string to convert.
       * @returns {Array} Returns the converted array.
       */
      function unicodeToArray(string) {
        return string.match(reUnicode) || [];
      }

      /**
       * Converts `string` to an array.
       *
       * @private
       * @param {string} string The string to convert.
       * @returns {Array} Returns the converted array.
       */
      function stringToArray(string) {
        return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
      }

      /**
       * Creates a function like `_.lowerFirst`.
       *
       * @private
       * @param {string} methodName The name of the `String` case method to use.
       * @returns {Function} Returns the new case function.
       */
      function createCaseFirst(methodName) {
        return function (string) {
          string = toString(string);
          var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined;
          var chr = strSymbols ? strSymbols[0] : string.charAt(0);
          var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1);
          return chr[methodName]() + trailing;
        };
      }

      /**
       * Converts the first character of `string` to upper case.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the converted string.
       * @example
       *
       * _.upperFirst('fred');
       * // => 'Fred'
       *
       * _.upperFirst('FRED');
       * // => 'FRED'
       */
      var upperFirst = createCaseFirst('toUpperCase');

      /**
       * Converts the first character of `string` to upper case and the remaining
       * to lower case.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to capitalize.
       * @returns {string} Returns the capitalized string.
       * @example
       *
       * _.capitalize('FRED');
       * // => 'Fred'
       */
      function capitalize(string) {
        return upperFirst(toString(string).toLowerCase());
      }

      /**
       * A specialized version of `_.reduce` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @param {*} [accumulator] The initial value.
       * @param {boolean} [initAccum] Specify using the first element of `array` as
       *  the initial value.
       * @returns {*} Returns the accumulated value.
       */
      function arrayReduce(array, iteratee, accumulator, initAccum) {
        var index = -1,
          length = array == null ? 0 : array.length;
        if (initAccum && length) {
          accumulator = array[++index];
        }
        while (++index < length) {
          accumulator = iteratee(accumulator, array[index], index, array);
        }
        return accumulator;
      }

      /**
       * The base implementation of `_.propertyOf` without support for deep paths.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Function} Returns the new accessor function.
       */
      function basePropertyOf(object) {
        return function (key) {
          return object == null ? undefined : object[key];
        };
      }

      /** Used to map Latin Unicode letters to basic Latin letters. */
      var deburredLetters = {
        // Latin-1 Supplement block.
        '\xc0': 'A',
        '\xc1': 'A',
        '\xc2': 'A',
        '\xc3': 'A',
        '\xc4': 'A',
        '\xc5': 'A',
        '\xe0': 'a',
        '\xe1': 'a',
        '\xe2': 'a',
        '\xe3': 'a',
        '\xe4': 'a',
        '\xe5': 'a',
        '\xc7': 'C',
        '\xe7': 'c',
        '\xd0': 'D',
        '\xf0': 'd',
        '\xc8': 'E',
        '\xc9': 'E',
        '\xca': 'E',
        '\xcb': 'E',
        '\xe8': 'e',
        '\xe9': 'e',
        '\xea': 'e',
        '\xeb': 'e',
        '\xcc': 'I',
        '\xcd': 'I',
        '\xce': 'I',
        '\xcf': 'I',
        '\xec': 'i',
        '\xed': 'i',
        '\xee': 'i',
        '\xef': 'i',
        '\xd1': 'N',
        '\xf1': 'n',
        '\xd2': 'O',
        '\xd3': 'O',
        '\xd4': 'O',
        '\xd5': 'O',
        '\xd6': 'O',
        '\xd8': 'O',
        '\xf2': 'o',
        '\xf3': 'o',
        '\xf4': 'o',
        '\xf5': 'o',
        '\xf6': 'o',
        '\xf8': 'o',
        '\xd9': 'U',
        '\xda': 'U',
        '\xdb': 'U',
        '\xdc': 'U',
        '\xf9': 'u',
        '\xfa': 'u',
        '\xfb': 'u',
        '\xfc': 'u',
        '\xdd': 'Y',
        '\xfd': 'y',
        '\xff': 'y',
        '\xc6': 'Ae',
        '\xe6': 'ae',
        '\xde': 'Th',
        '\xfe': 'th',
        '\xdf': 'ss',
        // Latin Extended-A block.
        "\u0100": 'A',
        "\u0102": 'A',
        "\u0104": 'A',
        "\u0101": 'a',
        "\u0103": 'a',
        "\u0105": 'a',
        "\u0106": 'C',
        "\u0108": 'C',
        "\u010A": 'C',
        "\u010C": 'C',
        "\u0107": 'c',
        "\u0109": 'c',
        "\u010B": 'c',
        "\u010D": 'c',
        "\u010E": 'D',
        "\u0110": 'D',
        "\u010F": 'd',
        "\u0111": 'd',
        "\u0112": 'E',
        "\u0114": 'E',
        "\u0116": 'E',
        "\u0118": 'E',
        "\u011A": 'E',
        "\u0113": 'e',
        "\u0115": 'e',
        "\u0117": 'e',
        "\u0119": 'e',
        "\u011B": 'e',
        "\u011C": 'G',
        "\u011E": 'G',
        "\u0120": 'G',
        "\u0122": 'G',
        "\u011D": 'g',
        "\u011F": 'g',
        "\u0121": 'g',
        "\u0123": 'g',
        "\u0124": 'H',
        "\u0126": 'H',
        "\u0125": 'h',
        "\u0127": 'h',
        "\u0128": 'I',
        "\u012A": 'I',
        "\u012C": 'I',
        "\u012E": 'I',
        "\u0130": 'I',
        "\u0129": 'i',
        "\u012B": 'i',
        "\u012D": 'i',
        "\u012F": 'i',
        "\u0131": 'i',
        "\u0134": 'J',
        "\u0135": 'j',
        "\u0136": 'K',
        "\u0137": 'k',
        "\u0138": 'k',
        "\u0139": 'L',
        "\u013B": 'L',
        "\u013D": 'L',
        "\u013F": 'L',
        "\u0141": 'L',
        "\u013A": 'l',
        "\u013C": 'l',
        "\u013E": 'l',
        "\u0140": 'l',
        "\u0142": 'l',
        "\u0143": 'N',
        "\u0145": 'N',
        "\u0147": 'N',
        "\u014A": 'N',
        "\u0144": 'n',
        "\u0146": 'n',
        "\u0148": 'n',
        "\u014B": 'n',
        "\u014C": 'O',
        "\u014E": 'O',
        "\u0150": 'O',
        "\u014D": 'o',
        "\u014F": 'o',
        "\u0151": 'o',
        "\u0154": 'R',
        "\u0156": 'R',
        "\u0158": 'R',
        "\u0155": 'r',
        "\u0157": 'r',
        "\u0159": 'r',
        "\u015A": 'S',
        "\u015C": 'S',
        "\u015E": 'S',
        "\u0160": 'S',
        "\u015B": 's',
        "\u015D": 's',
        "\u015F": 's',
        "\u0161": 's',
        "\u0162": 'T',
        "\u0164": 'T',
        "\u0166": 'T',
        "\u0163": 't',
        "\u0165": 't',
        "\u0167": 't',
        "\u0168": 'U',
        "\u016A": 'U',
        "\u016C": 'U',
        "\u016E": 'U',
        "\u0170": 'U',
        "\u0172": 'U',
        "\u0169": 'u',
        "\u016B": 'u',
        "\u016D": 'u',
        "\u016F": 'u',
        "\u0171": 'u',
        "\u0173": 'u',
        "\u0174": 'W',
        "\u0175": 'w',
        "\u0176": 'Y',
        "\u0177": 'y',
        "\u0178": 'Y',
        "\u0179": 'Z',
        "\u017B": 'Z',
        "\u017D": 'Z',
        "\u017A": 'z',
        "\u017C": 'z',
        "\u017E": 'z',
        "\u0132": 'IJ',
        "\u0133": 'ij',
        "\u0152": 'Oe',
        "\u0153": 'oe',
        "\u0149": "'n",
        "\u017F": 's'
      };

      /**
       * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
       * letters to basic Latin letters.
       *
       * @private
       * @param {string} letter The matched letter to deburr.
       * @returns {string} Returns the deburred letter.
       */
      var deburrLetter = basePropertyOf(deburredLetters);

      /** Used to match Latin Unicode letters (excluding mathematical operators). */
      var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;

      /** Used to compose unicode character classes. */
      var rsComboMarksRange$2 = "\\u0300-\\u036f",
        reComboHalfMarksRange$2 = "\\ufe20-\\ufe2f",
        rsComboSymbolsRange$2 = "\\u20d0-\\u20ff",
        rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2;

      /** Used to compose unicode capture groups. */
      var rsCombo$1 = '[' + rsComboRange$2 + ']';

      /**
       * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
       * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
       */
      var reComboMark = RegExp(rsCombo$1, 'g');

      /**
       * Deburrs `string` by converting
       * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
       * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
       * letters to basic Latin letters and removing
       * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to deburr.
       * @returns {string} Returns the deburred string.
       * @example
       *
       * _.deburr('déjà vu');
       * // => 'deja vu'
       */
      function deburr(string) {
        string = toString(string);
        return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
      }

      /** Used to match words composed of alphanumeric characters. */
      var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;

      /**
       * Splits an ASCII `string` into an array of its words.
       *
       * @private
       * @param {string} The string to inspect.
       * @returns {Array} Returns the words of `string`.
       */
      function asciiWords(string) {
        return string.match(reAsciiWord) || [];
      }

      /** Used to detect strings that need a more robust regexp to match words. */
      var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;

      /**
       * Checks if `string` contains a word composed of Unicode symbols.
       *
       * @private
       * @param {string} string The string to inspect.
       * @returns {boolean} Returns `true` if a word is found, else `false`.
       */
      function hasUnicodeWord(string) {
        return reHasUnicodeWord.test(string);
      }

      /** Used to compose unicode character classes. */
      var rsAstralRange$2 = "\\ud800-\\udfff",
        rsComboMarksRange$3 = "\\u0300-\\u036f",
        reComboHalfMarksRange$3 = "\\ufe20-\\ufe2f",
        rsComboSymbolsRange$3 = "\\u20d0-\\u20ff",
        rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3,
        rsDingbatRange = "\\u2700-\\u27bf",
        rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
        rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
        rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
        rsPunctuationRange = "\\u2000-\\u206f",
        rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",
        rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
        rsVarRange$2 = "\\ufe0e\\ufe0f",
        rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;

      /** Used to compose unicode capture groups. */
      var rsApos = "['\u2019]",
        rsBreak = '[' + rsBreakRange + ']',
        rsCombo$2 = '[' + rsComboRange$3 + ']',
        rsDigits = '\\d+',
        rsDingbat = '[' + rsDingbatRange + ']',
        rsLower = '[' + rsLowerRange + ']',
        rsMisc = '[^' + rsAstralRange$2 + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
        rsFitz$1 = "\\ud83c[\\udffb-\\udfff]",
        rsModifier$1 = '(?:' + rsCombo$2 + '|' + rsFitz$1 + ')',
        rsNonAstral$1 = '[^' + rsAstralRange$2 + ']',
        rsRegional$1 = "(?:\\ud83c[\\udde6-\\uddff]){2}",
        rsSurrPair$1 = "[\\ud800-\\udbff][\\udc00-\\udfff]",
        rsUpper = '[' + rsUpperRange + ']',
        rsZWJ$2 = "\\u200d";

      /** Used to compose unicode regexes. */
      var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
        rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
        rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
        rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
        reOptMod$1 = rsModifier$1 + '?',
        rsOptVar$1 = '[' + rsVarRange$2 + ']?',
        rsOptJoin$1 = '(?:' + rsZWJ$2 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*',
        rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
        rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
        rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1,
        rsEmoji = '(?:' + [rsDingbat, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsSeq$1;

      /** Used to match complex or compound words. */
      var reUnicodeWord = RegExp([rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji].join('|'), 'g');

      /**
       * Splits a Unicode `string` into an array of its words.
       *
       * @private
       * @param {string} The string to inspect.
       * @returns {Array} Returns the words of `string`.
       */
      function unicodeWords(string) {
        return string.match(reUnicodeWord) || [];
      }

      /**
       * Splits `string` into an array of its words.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to inspect.
       * @param {RegExp|string} [pattern] The pattern to match words.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the words of `string`.
       * @example
       *
       * _.words('fred, barney, & pebbles');
       * // => ['fred', 'barney', 'pebbles']
       *
       * _.words('fred, barney, & pebbles', /[^, ]+/g);
       * // => ['fred', 'barney', '&', 'pebbles']
       */
      function words(string, pattern, guard) {
        string = toString(string);
        pattern = guard ? undefined : pattern;
        if (pattern === undefined) {
          return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
        }
        return string.match(pattern) || [];
      }

      /** Used to compose unicode capture groups. */
      var rsApos$1 = "['\u2019]";

      /** Used to match apostrophes. */
      var reApos = RegExp(rsApos$1, 'g');

      /**
       * Creates a function like `_.camelCase`.
       *
       * @private
       * @param {Function} callback The function to combine each word.
       * @returns {Function} Returns the new compounder function.
       */
      function createCompounder(callback) {
        return function (string) {
          return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
        };
      }

      /**
       * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the camel cased string.
       * @example
       *
       * _.camelCase('Foo Bar');
       * // => 'fooBar'
       *
       * _.camelCase('--foo-bar--');
       * // => 'fooBar'
       *
       * _.camelCase('__FOO_BAR__');
       * // => 'fooBar'
       */
      var camelCase = createCompounder(function (result, word, index) {
        word = word.toLowerCase();
        return result + (index ? capitalize(word) : word);
      });

      /**
       * Casts `value` as an array if it's not one.
       *
       * @static
       * @memberOf _
       * @since 4.4.0
       * @category Lang
       * @param {*} value The value to inspect.
       * @returns {Array} Returns the cast array.
       * @example
       *
       * _.castArray(1);
       * // => [1]
       *
       * _.castArray({ 'a': 1 });
       * // => [{ 'a': 1 }]
       *
       * _.castArray('abc');
       * // => ['abc']
       *
       * _.castArray(null);
       * // => [null]
       *
       * _.castArray(undefined);
       * // => [undefined]
       *
       * _.castArray();
       * // => []
       *
       * var array = [1, 2, 3];
       * console.log(_.castArray(array) === array);
       * // => true
       */
      function castArray() {
        if (!arguments.length) {
          return [];
        }
        var value = arguments[0];
        return isArray$1(value) ? value : [value];
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeIsFinite = root.isFinite,
        nativeMin$2 = Math.min;

      /**
       * Creates a function like `_.round`.
       *
       * @private
       * @param {string} methodName The name of the `Math` method to use when rounding.
       * @returns {Function} Returns the new round function.
       */
      function createRound(methodName) {
        var func = Math[methodName];
        return function (number, precision) {
          number = toNumber(number);
          precision = precision == null ? 0 : nativeMin$2(toInteger(precision), 292);
          if (precision && nativeIsFinite(number)) {
            // Shift with exponential notation to avoid floating-point issues.
            // See [MDN](https://mdn.io/round#Examples) for more details.
            var pair = (toString(number) + 'e').split('e'),
              value = func(pair[0] + 'e' + (+pair[1] + precision));
            pair = (toString(value) + 'e').split('e');
            return +(pair[0] + 'e' + (+pair[1] - precision));
          }
          return func(number);
        };
      }

      /**
       * Computes `number` rounded up to `precision`.
       *
       * @static
       * @memberOf _
       * @since 3.10.0
       * @category Math
       * @param {number} number The number to round up.
       * @param {number} [precision=0] The precision to round up to.
       * @returns {number} Returns the rounded up number.
       * @example
       *
       * _.ceil(4.006);
       * // => 5
       *
       * _.ceil(6.004, 2);
       * // => 6.01
       *
       * _.ceil(6040, -2);
       * // => 6100
       */
      var ceil = createRound('ceil');

      /**
       * Creates a `lodash` wrapper instance that wraps `value` with explicit method
       * chain sequences enabled. The result of such sequences must be unwrapped
       * with `_#value`.
       *
       * @static
       * @memberOf _
       * @since 1.3.0
       * @category Seq
       * @param {*} value The value to wrap.
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'age': 36 },
       *   { 'user': 'fred',    'age': 40 },
       *   { 'user': 'pebbles', 'age': 1 }
       * ];
       *
       * var youngest = _
       *   .chain(users)
       *   .sortBy('age')
       *   .map(function(o) {
       *     return o.user + ' is ' + o.age;
       *   })
       *   .head()
       *   .value();
       * // => 'pebbles is 1'
       */
      function chain(value) {
        var result = lodash(value);
        result.__chain__ = true;
        return result;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeCeil = Math.ceil,
        nativeMax$4 = Math.max;

      /**
       * Creates an array of elements split into groups the length of `size`.
       * If `array` can't be split evenly, the final chunk will be the remaining
       * elements.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to process.
       * @param {number} [size=1] The length of each chunk
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the new array of chunks.
       * @example
       *
       * _.chunk(['a', 'b', 'c', 'd'], 2);
       * // => [['a', 'b'], ['c', 'd']]
       *
       * _.chunk(['a', 'b', 'c', 'd'], 3);
       * // => [['a', 'b', 'c'], ['d']]
       */
      function chunk(array, size, guard) {
        if (guard ? isIterateeCall(array, size, guard) : size === undefined) {
          size = 1;
        } else {
          size = nativeMax$4(toInteger(size), 0);
        }
        var length = array == null ? 0 : array.length;
        if (!length || size < 1) {
          return [];
        }
        var index = 0,
          resIndex = 0,
          result = Array(nativeCeil(length / size));
        while (index < length) {
          result[resIndex++] = baseSlice(array, index, index += size);
        }
        return result;
      }

      /**
       * The base implementation of `_.clamp` which doesn't coerce arguments.
       *
       * @private
       * @param {number} number The number to clamp.
       * @param {number} [lower] The lower bound.
       * @param {number} upper The upper bound.
       * @returns {number} Returns the clamped number.
       */
      function baseClamp(number, lower, upper) {
        if (number === number) {
          if (upper !== undefined) {
            number = number <= upper ? number : upper;
          }
          if (lower !== undefined) {
            number = number >= lower ? number : lower;
          }
        }
        return number;
      }

      /**
       * Clamps `number` within the inclusive `lower` and `upper` bounds.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Number
       * @param {number} number The number to clamp.
       * @param {number} [lower] The lower bound.
       * @param {number} upper The upper bound.
       * @returns {number} Returns the clamped number.
       * @example
       *
       * _.clamp(-10, -5, 5);
       * // => -5
       *
       * _.clamp(10, -5, 5);
       * // => 5
       */
      function clamp(number, lower, upper) {
        if (upper === undefined) {
          upper = lower;
          lower = undefined;
        }
        if (upper !== undefined) {
          upper = toNumber(upper);
          upper = upper === upper ? upper : 0;
        }
        if (lower !== undefined) {
          lower = toNumber(lower);
          lower = lower === lower ? lower : 0;
        }
        return baseClamp(toNumber(number), lower, upper);
      }

      /**
       * Removes all key-value entries from the stack.
       *
       * @private
       * @name clear
       * @memberOf Stack
       */
      function stackClear() {
        this.__data__ = new ListCache();
        this.size = 0;
      }

      /**
       * Removes `key` and its value from the stack.
       *
       * @private
       * @name delete
       * @memberOf Stack
       * @param {string} key The key of the value to remove.
       * @returns {boolean} Returns `true` if the entry was removed, else `false`.
       */
      function stackDelete(key) {
        var data = this.__data__,
          result = data['delete'](key);
        this.size = data.size;
        return result;
      }

      /**
       * Gets the stack value for `key`.
       *
       * @private
       * @name get
       * @memberOf Stack
       * @param {string} key The key of the value to get.
       * @returns {*} Returns the entry value.
       */
      function stackGet(key) {
        return this.__data__.get(key);
      }

      /**
       * Checks if a stack value for `key` exists.
       *
       * @private
       * @name has
       * @memberOf Stack
       * @param {string} key The key of the entry to check.
       * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
       */
      function stackHas(key) {
        return this.__data__.has(key);
      }

      /** Used as the size to enable large array optimizations. */
      var LARGE_ARRAY_SIZE = 200;

      /**
       * Sets the stack `key` to `value`.
       *
       * @private
       * @name set
       * @memberOf Stack
       * @param {string} key The key of the value to set.
       * @param {*} value The value to set.
       * @returns {Object} Returns the stack cache instance.
       */
      function stackSet(key, value) {
        var data = this.__data__;
        if (data instanceof ListCache) {
          var pairs = data.__data__;
          if (!Map$1 || pairs.length < LARGE_ARRAY_SIZE - 1) {
            pairs.push([key, value]);
            this.size = ++data.size;
            return this;
          }
          data = this.__data__ = new MapCache(pairs);
        }
        data.set(key, value);
        this.size = data.size;
        return this;
      }

      /**
       * Creates a stack cache object to store key-value pairs.
       *
       * @private
       * @constructor
       * @param {Array} [entries] The key-value pairs to cache.
       */
      function Stack(entries) {
        var data = this.__data__ = new ListCache(entries);
        this.size = data.size;
      }

      // Add methods to `Stack`.
      Stack.prototype.clear = stackClear;
      Stack.prototype['delete'] = stackDelete;
      Stack.prototype.get = stackGet;
      Stack.prototype.has = stackHas;
      Stack.prototype.set = stackSet;

      /**
       * The base implementation of `_.assign` without support for multiple sources
       * or `customizer` functions.
       *
       * @private
       * @param {Object} object The destination object.
       * @param {Object} source The source object.
       * @returns {Object} Returns `object`.
       */
      function baseAssign(object, source) {
        return object && copyObject(source, keys(source), object);
      }

      /**
       * The base implementation of `_.assignIn` without support for multiple sources
       * or `customizer` functions.
       *
       * @private
       * @param {Object} object The destination object.
       * @param {Object} source The source object.
       * @returns {Object} Returns `object`.
       */
      function baseAssignIn(object, source) {
        return object && copyObject(source, keysIn(source), object);
      }

      /** Detect free variable `exports`. */
      var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;

      /** Detect free variable `module`. */
      var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;

      /** Detect the popular CommonJS extension `module.exports`. */
      var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;

      /** Built-in value references. */
      var Buffer$1 = moduleExports$2 ? root.Buffer : undefined,
        allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined;

      /**
       * Creates a clone of  `buffer`.
       *
       * @private
       * @param {Buffer} buffer The buffer to clone.
       * @param {boolean} [isDeep] Specify a deep clone.
       * @returns {Buffer} Returns the cloned buffer.
       */
      function cloneBuffer(buffer, isDeep) {
        if (isDeep) {
          return buffer.slice();
        }
        var length = buffer.length,
          result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
        buffer.copy(result);
        return result;
      }

      /**
       * A specialized version of `_.filter` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {Array} Returns the new filtered array.
       */
      function arrayFilter(array, predicate) {
        var index = -1,
          length = array == null ? 0 : array.length,
          resIndex = 0,
          result = [];
        while (++index < length) {
          var value = array[index];
          if (predicate(value, index, array)) {
            result[resIndex++] = value;
          }
        }
        return result;
      }

      /**
       * This method returns a new empty array.
       *
       * @static
       * @memberOf _
       * @since 4.13.0
       * @category Util
       * @returns {Array} Returns the new empty array.
       * @example
       *
       * var arrays = _.times(2, _.stubArray);
       *
       * console.log(arrays);
       * // => [[], []]
       *
       * console.log(arrays[0] === arrays[1]);
       * // => false
       */
      function stubArray() {
        return [];
      }

      /** Used for built-in method references. */
      var objectProto$f = Object.prototype;

      /** Built-in value references. */
      var propertyIsEnumerable$1 = objectProto$f.propertyIsEnumerable;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeGetSymbols = Object.getOwnPropertySymbols;

      /**
       * Creates an array of the own enumerable symbols of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of symbols.
       */
      var getSymbols = !nativeGetSymbols ? stubArray : function (object) {
        if (object == null) {
          return [];
        }
        object = Object(object);
        return arrayFilter(nativeGetSymbols(object), function (symbol) {
          return propertyIsEnumerable$1.call(object, symbol);
        });
      };

      /**
       * Copies own symbols of `source` to `object`.
       *
       * @private
       * @param {Object} source The object to copy symbols from.
       * @param {Object} [object={}] The object to copy symbols to.
       * @returns {Object} Returns `object`.
       */
      function copySymbols(source, object) {
        return copyObject(source, getSymbols(source), object);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeGetSymbols$1 = Object.getOwnPropertySymbols;

      /**
       * Creates an array of the own and inherited enumerable symbols of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of symbols.
       */
      var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function (object) {
        var result = [];
        while (object) {
          arrayPush(result, getSymbols(object));
          object = getPrototype(object);
        }
        return result;
      };

      /**
       * Copies own and inherited symbols of `source` to `object`.
       *
       * @private
       * @param {Object} source The object to copy symbols from.
       * @param {Object} [object={}] The object to copy symbols to.
       * @returns {Object} Returns `object`.
       */
      function copySymbolsIn(source, object) {
        return copyObject(source, getSymbolsIn(source), object);
      }

      /**
       * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
       * `keysFunc` and `symbolsFunc` to get the enumerable property names and
       * symbols of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Function} keysFunc The function to get the keys of `object`.
       * @param {Function} symbolsFunc The function to get the symbols of `object`.
       * @returns {Array} Returns the array of property names and symbols.
       */
      function baseGetAllKeys(object, keysFunc, symbolsFunc) {
        var result = keysFunc(object);
        return isArray$1(object) ? result : arrayPush(result, symbolsFunc(object));
      }

      /**
       * Creates an array of own enumerable property names and symbols of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names and symbols.
       */
      function getAllKeys(object) {
        return baseGetAllKeys(object, keys, getSymbols);
      }

      /**
       * Creates an array of own and inherited enumerable property names and
       * symbols of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property names and symbols.
       */
      function getAllKeysIn(object) {
        return baseGetAllKeys(object, keysIn, getSymbolsIn);
      }

      /* Built-in method references that are verified to be native. */
      var DataView = getNative(root, 'DataView');

      /* Built-in method references that are verified to be native. */
      var Promise$1 = getNative(root, 'Promise');

      /* Built-in method references that are verified to be native. */
      var Set$1 = getNative(root, 'Set');

      /** `Object#toString` result references. */
      var mapTag$1 = '[object Map]',
        objectTag$2 = '[object Object]',
        promiseTag = '[object Promise]',
        setTag$1 = '[object Set]',
        weakMapTag$1 = '[object WeakMap]';
      var dataViewTag$1 = '[object DataView]';

      /** Used to detect maps, sets, and weakmaps. */
      var dataViewCtorString = toSource(DataView),
        mapCtorString = toSource(Map$1),
        promiseCtorString = toSource(Promise$1),
        setCtorString = toSource(Set$1),
        weakMapCtorString = toSource(WeakMap$1);

      /**
       * Gets the `toStringTag` of `value`.
       *
       * @private
       * @param {*} value The value to query.
       * @returns {string} Returns the `toStringTag`.
       */
      var getTag = baseGetTag;

      // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
      if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1 || Map$1 && getTag(new Map$1()) != mapTag$1 || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set$1 && getTag(new Set$1()) != setTag$1 || WeakMap$1 && getTag(new WeakMap$1()) != weakMapTag$1) {
        getTag = function getTag(value) {
          var result = baseGetTag(value),
            Ctor = result == objectTag$2 ? value.constructor : undefined,
            ctorString = Ctor ? toSource(Ctor) : '';
          if (ctorString) {
            switch (ctorString) {
              case dataViewCtorString:
                return dataViewTag$1;
              case mapCtorString:
                return mapTag$1;
              case promiseCtorString:
                return promiseTag;
              case setCtorString:
                return setTag$1;
              case weakMapCtorString:
                return weakMapTag$1;
            }
          }
          return result;
        };
      }
      var getTag$1 = getTag;

      /** Used for built-in method references. */
      var objectProto$g = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$d = objectProto$g.hasOwnProperty;

      /**
       * Initializes an array clone.
       *
       * @private
       * @param {Array} array The array to clone.
       * @returns {Array} Returns the initialized clone.
       */
      function initCloneArray(array) {
        var length = array.length,
          result = new array.constructor(length);

        // Add properties assigned by `RegExp#exec`.
        if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) {
          result.index = array.index;
          result.input = array.input;
        }
        return result;
      }

      /** Built-in value references. */
      var Uint8Array$1 = root.Uint8Array;

      /**
       * Creates a clone of `arrayBuffer`.
       *
       * @private
       * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
       * @returns {ArrayBuffer} Returns the cloned array buffer.
       */
      function cloneArrayBuffer(arrayBuffer) {
        var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
        new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer));
        return result;
      }

      /**
       * Creates a clone of `dataView`.
       *
       * @private
       * @param {Object} dataView The data view to clone.
       * @param {boolean} [isDeep] Specify a deep clone.
       * @returns {Object} Returns the cloned data view.
       */
      function cloneDataView(dataView, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
        return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
      }

      /** Used to match `RegExp` flags from their coerced string values. */
      var reFlags = /\w*$/;

      /**
       * Creates a clone of `regexp`.
       *
       * @private
       * @param {Object} regexp The regexp to clone.
       * @returns {Object} Returns the cloned regexp.
       */
      function cloneRegExp(regexp) {
        var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
        result.lastIndex = regexp.lastIndex;
        return result;
      }

      /** Used to convert symbols to primitives and strings. */
      var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined,
        symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;

      /**
       * Creates a clone of the `symbol` object.
       *
       * @private
       * @param {Object} symbol The symbol object to clone.
       * @returns {Object} Returns the cloned symbol object.
       */
      function cloneSymbol(symbol) {
        return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
      }

      /**
       * Creates a clone of `typedArray`.
       *
       * @private
       * @param {Object} typedArray The typed array to clone.
       * @param {boolean} [isDeep] Specify a deep clone.
       * @returns {Object} Returns the cloned typed array.
       */
      function cloneTypedArray(typedArray, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
        return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
      }

      /** `Object#toString` result references. */
      var boolTag$1 = '[object Boolean]',
        dateTag$1 = '[object Date]',
        mapTag$2 = '[object Map]',
        numberTag$1 = '[object Number]',
        regexpTag$1 = '[object RegExp]',
        setTag$2 = '[object Set]',
        stringTag$1 = '[object String]',
        symbolTag$1 = '[object Symbol]';
      var arrayBufferTag$1 = '[object ArrayBuffer]',
        dataViewTag$2 = '[object DataView]',
        float32Tag$1 = '[object Float32Array]',
        float64Tag$1 = '[object Float64Array]',
        int8Tag$1 = '[object Int8Array]',
        int16Tag$1 = '[object Int16Array]',
        int32Tag$1 = '[object Int32Array]',
        uint8Tag$1 = '[object Uint8Array]',
        uint8ClampedTag$1 = '[object Uint8ClampedArray]',
        uint16Tag$1 = '[object Uint16Array]',
        uint32Tag$1 = '[object Uint32Array]';

      /**
       * Initializes an object clone based on its `toStringTag`.
       *
       * **Note:** This function only supports cloning values with tags of
       * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
       *
       * @private
       * @param {Object} object The object to clone.
       * @param {string} tag The `toStringTag` of the object to clone.
       * @param {boolean} [isDeep] Specify a deep clone.
       * @returns {Object} Returns the initialized clone.
       */
      function initCloneByTag(object, tag, isDeep) {
        var Ctor = object.constructor;
        switch (tag) {
          case arrayBufferTag$1:
            return cloneArrayBuffer(object);
          case boolTag$1:
          case dateTag$1:
            return new Ctor(+object);
          case dataViewTag$2:
            return cloneDataView(object, isDeep);
          case float32Tag$1:
          case float64Tag$1:
          case int8Tag$1:
          case int16Tag$1:
          case int32Tag$1:
          case uint8Tag$1:
          case uint8ClampedTag$1:
          case uint16Tag$1:
          case uint32Tag$1:
            return cloneTypedArray(object, isDeep);
          case mapTag$2:
            return new Ctor();
          case numberTag$1:
          case stringTag$1:
            return new Ctor(object);
          case regexpTag$1:
            return cloneRegExp(object);
          case setTag$2:
            return new Ctor();
          case symbolTag$1:
            return cloneSymbol(object);
        }
      }

      /**
       * Initializes an object clone.
       *
       * @private
       * @param {Object} object The object to clone.
       * @returns {Object} Returns the initialized clone.
       */
      function initCloneObject(object) {
        return typeof object.constructor == 'function' && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
      }

      /** `Object#toString` result references. */
      var mapTag$3 = '[object Map]';

      /**
       * The base implementation of `_.isMap` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a map, else `false`.
       */
      function baseIsMap(value) {
        return isObjectLike(value) && getTag$1(value) == mapTag$3;
      }

      /* Node.js helper references. */
      var nodeIsMap = nodeUtil && nodeUtil.isMap;

      /**
       * Checks if `value` is classified as a `Map` object.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a map, else `false`.
       * @example
       *
       * _.isMap(new Map);
       * // => true
       *
       * _.isMap(new WeakMap);
       * // => false
       */
      var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;

      /** `Object#toString` result references. */
      var setTag$3 = '[object Set]';

      /**
       * The base implementation of `_.isSet` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a set, else `false`.
       */
      function baseIsSet(value) {
        return isObjectLike(value) && getTag$1(value) == setTag$3;
      }

      /* Node.js helper references. */
      var nodeIsSet = nodeUtil && nodeUtil.isSet;

      /**
       * Checks if `value` is classified as a `Set` object.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a set, else `false`.
       * @example
       *
       * _.isSet(new Set);
       * // => true
       *
       * _.isSet(new WeakSet);
       * // => false
       */
      var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG = 1,
        CLONE_FLAT_FLAG = 2,
        CLONE_SYMBOLS_FLAG = 4;

      /** `Object#toString` result references. */
      var argsTag$2 = '[object Arguments]',
        arrayTag$1 = '[object Array]',
        boolTag$2 = '[object Boolean]',
        dateTag$2 = '[object Date]',
        errorTag$2 = '[object Error]',
        funcTag$2 = '[object Function]',
        genTag$1 = '[object GeneratorFunction]',
        mapTag$4 = '[object Map]',
        numberTag$2 = '[object Number]',
        objectTag$3 = '[object Object]',
        regexpTag$2 = '[object RegExp]',
        setTag$4 = '[object Set]',
        stringTag$2 = '[object String]',
        symbolTag$2 = '[object Symbol]',
        weakMapTag$2 = '[object WeakMap]';
      var arrayBufferTag$2 = '[object ArrayBuffer]',
        dataViewTag$3 = '[object DataView]',
        float32Tag$2 = '[object Float32Array]',
        float64Tag$2 = '[object Float64Array]',
        int8Tag$2 = '[object Int8Array]',
        int16Tag$2 = '[object Int16Array]',
        int32Tag$2 = '[object Int32Array]',
        uint8Tag$2 = '[object Uint8Array]',
        uint8ClampedTag$2 = '[object Uint8ClampedArray]',
        uint16Tag$2 = '[object Uint16Array]',
        uint32Tag$2 = '[object Uint32Array]';

      /** Used to identify `toStringTag` values supported by `_.clone`. */
      var cloneableTags = {};
      cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$3] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$2] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
      cloneableTags[errorTag$2] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false;

      /**
       * The base implementation of `_.clone` and `_.cloneDeep` which tracks
       * traversed objects.
       *
       * @private
       * @param {*} value The value to clone.
       * @param {boolean} bitmask The bitmask flags.
       *  1 - Deep clone
       *  2 - Flatten inherited properties
       *  4 - Clone symbols
       * @param {Function} [customizer] The function to customize cloning.
       * @param {string} [key] The key of `value`.
       * @param {Object} [object] The parent object of `value`.
       * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
       * @returns {*} Returns the cloned value.
       */
      function baseClone(value, bitmask, customizer, key, object, stack) {
        var result,
          isDeep = bitmask & CLONE_DEEP_FLAG,
          isFlat = bitmask & CLONE_FLAT_FLAG,
          isFull = bitmask & CLONE_SYMBOLS_FLAG;
        if (customizer) {
          result = object ? customizer(value, key, object, stack) : customizer(value);
        }
        if (result !== undefined) {
          return result;
        }
        if (!isObject(value)) {
          return value;
        }
        var isArr = isArray$1(value);
        if (isArr) {
          result = initCloneArray(value);
          if (!isDeep) {
            return copyArray(value, result);
          }
        } else {
          var tag = getTag$1(value),
            isFunc = tag == funcTag$2 || tag == genTag$1;
          if (isBuffer(value)) {
            return cloneBuffer(value, isDeep);
          }
          if (tag == objectTag$3 || tag == argsTag$2 || isFunc && !object) {
            result = isFlat || isFunc ? {} : initCloneObject(value);
            if (!isDeep) {
              return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value));
            }
          } else {
            if (!cloneableTags[tag]) {
              return object ? value : {};
            }
            result = initCloneByTag(value, tag, isDeep);
          }
        }
        // Check for circular references and return its corresponding clone.
        stack || (stack = new Stack());
        var stacked = stack.get(value);
        if (stacked) {
          return stacked;
        }
        stack.set(value, result);
        if (isSet(value)) {
          value.forEach(function (subValue) {
            result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
          });
        } else if (isMap(value)) {
          value.forEach(function (subValue, key) {
            result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
          });
        }
        var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
        var props = isArr ? undefined : keysFunc(value);
        arrayEach(props || value, function (subValue, key) {
          if (props) {
            key = subValue;
            subValue = value[key];
          }
          // Recursively populate clone (susceptible to call stack limits).
          assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
        });
        return result;
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_SYMBOLS_FLAG$1 = 4;

      /**
       * Creates a shallow clone of `value`.
       *
       * **Note:** This method is loosely based on the
       * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
       * and supports cloning arrays, array buffers, booleans, date objects, maps,
       * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
       * arrays. The own enumerable properties of `arguments` objects are cloned
       * as plain objects. An empty object is returned for uncloneable values such
       * as error objects, functions, DOM nodes, and WeakMaps.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to clone.
       * @returns {*} Returns the cloned value.
       * @see _.cloneDeep
       * @example
       *
       * var objects = [{ 'a': 1 }, { 'b': 2 }];
       *
       * var shallow = _.clone(objects);
       * console.log(shallow[0] === objects[0]);
       * // => true
       */
      function clone(value) {
        return baseClone(value, CLONE_SYMBOLS_FLAG$1);
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$1 = 1,
        CLONE_SYMBOLS_FLAG$2 = 4;

      /**
       * This method is like `_.clone` except that it recursively clones `value`.
       *
       * @static
       * @memberOf _
       * @since 1.0.0
       * @category Lang
       * @param {*} value The value to recursively clone.
       * @returns {*} Returns the deep cloned value.
       * @see _.clone
       * @example
       *
       * var objects = [{ 'a': 1 }, { 'b': 2 }];
       *
       * var deep = _.cloneDeep(objects);
       * console.log(deep[0] === objects[0]);
       * // => false
       */
      function cloneDeep(value) {
        return baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$2);
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$2 = 1,
        CLONE_SYMBOLS_FLAG$3 = 4;

      /**
       * This method is like `_.cloneWith` except that it recursively clones `value`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to recursively clone.
       * @param {Function} [customizer] The function to customize cloning.
       * @returns {*} Returns the deep cloned value.
       * @see _.cloneWith
       * @example
       *
       * function customizer(value) {
       *   if (_.isElement(value)) {
       *     return value.cloneNode(true);
       *   }
       * }
       *
       * var el = _.cloneDeepWith(document.body, customizer);
       *
       * console.log(el === document.body);
       * // => false
       * console.log(el.nodeName);
       * // => 'BODY'
       * console.log(el.childNodes.length);
       * // => 20
       */
      function cloneDeepWith(value, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        return baseClone(value, CLONE_DEEP_FLAG$2 | CLONE_SYMBOLS_FLAG$3, customizer);
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_SYMBOLS_FLAG$4 = 4;

      /**
       * This method is like `_.clone` except that it accepts `customizer` which
       * is invoked to produce the cloned value. If `customizer` returns `undefined`,
       * cloning is handled by the method instead. The `customizer` is invoked with
       * up to four arguments; (value [, index|key, object, stack]).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to clone.
       * @param {Function} [customizer] The function to customize cloning.
       * @returns {*} Returns the cloned value.
       * @see _.cloneDeepWith
       * @example
       *
       * function customizer(value) {
       *   if (_.isElement(value)) {
       *     return value.cloneNode(false);
       *   }
       * }
       *
       * var el = _.cloneWith(document.body, customizer);
       *
       * console.log(el === document.body);
       * // => false
       * console.log(el.nodeName);
       * // => 'BODY'
       * console.log(el.childNodes.length);
       * // => 0
       */
      function cloneWith(value, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        return baseClone(value, CLONE_SYMBOLS_FLAG$4, customizer);
      }

      /**
       * Executes the chain sequence and returns the wrapped result.
       *
       * @name commit
       * @memberOf _
       * @since 3.2.0
       * @category Seq
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * var array = [1, 2];
       * var wrapped = _(array).push(3);
       *
       * console.log(array);
       * // => [1, 2]
       *
       * wrapped = wrapped.commit();
       * console.log(array);
       * // => [1, 2, 3]
       *
       * wrapped.last();
       * // => 3
       *
       * console.log(array);
       * // => [1, 2, 3]
       */
      function wrapperCommit() {
        return new LodashWrapper(this.value(), this.__chain__);
      }

      /**
       * Creates an array with all falsey values removed. The values `false`, `null`,
       * `0`, `""`, `undefined`, and `NaN` are falsey.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to compact.
       * @returns {Array} Returns the new array of filtered values.
       * @example
       *
       * _.compact([0, 1, false, 2, '', 3]);
       * // => [1, 2, 3]
       */
      function compact(array) {
        var index = -1,
          length = array == null ? 0 : array.length,
          resIndex = 0,
          result = [];
        while (++index < length) {
          var value = array[index];
          if (value) {
            result[resIndex++] = value;
          }
        }
        return result;
      }

      /**
       * Creates a new array concatenating `array` with any additional arrays
       * and/or values.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to concatenate.
       * @param {...*} [values] The values to concatenate.
       * @returns {Array} Returns the new concatenated array.
       * @example
       *
       * var array = [1];
       * var other = _.concat(array, 2, [3], [[4]]);
       *
       * console.log(other);
       * // => [1, 2, 3, [4]]
       *
       * console.log(array);
       * // => [1]
       */
      function concat() {
        var length = arguments.length;
        if (!length) {
          return [];
        }
        var args = Array(length - 1),
          array = arguments[0],
          index = length;
        while (index--) {
          args[index - 1] = arguments[index];
        }
        return arrayPush(isArray$1(array) ? copyArray(array) : [array], baseFlatten(args, 1));
      }

      /** Used to stand-in for `undefined` hash values. */
      var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';

      /**
       * Adds `value` to the array cache.
       *
       * @private
       * @name add
       * @memberOf SetCache
       * @alias push
       * @param {*} value The value to cache.
       * @returns {Object} Returns the cache instance.
       */
      function setCacheAdd(value) {
        this.__data__.set(value, HASH_UNDEFINED$2);
        return this;
      }

      /**
       * Checks if `value` is in the array cache.
       *
       * @private
       * @name has
       * @memberOf SetCache
       * @param {*} value The value to search for.
       * @returns {number} Returns `true` if `value` is found, else `false`.
       */
      function setCacheHas(value) {
        return this.__data__.has(value);
      }

      /**
       *
       * Creates an array cache object to store unique values.
       *
       * @private
       * @constructor
       * @param {Array} [values] The values to cache.
       */
      function SetCache(values) {
        var index = -1,
          length = values == null ? 0 : values.length;
        this.__data__ = new MapCache();
        while (++index < length) {
          this.add(values[index]);
        }
      }

      // Add methods to `SetCache`.
      SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
      SetCache.prototype.has = setCacheHas;

      /**
       * A specialized version of `_.some` for arrays without support for iteratee
       * shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {boolean} Returns `true` if any element passes the predicate check,
       *  else `false`.
       */
      function arraySome(array, predicate) {
        var index = -1,
          length = array == null ? 0 : array.length;
        while (++index < length) {
          if (predicate(array[index], index, array)) {
            return true;
          }
        }
        return false;
      }

      /**
       * Checks if a `cache` value for `key` exists.
       *
       * @private
       * @param {Object} cache The cache to query.
       * @param {string} key The key of the entry to check.
       * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
       */
      function cacheHas(cache, key) {
        return cache.has(key);
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG = 1,
        COMPARE_UNORDERED_FLAG = 2;

      /**
       * A specialized version of `baseIsEqualDeep` for arrays with support for
       * partial deep comparisons.
       *
       * @private
       * @param {Array} array The array to compare.
       * @param {Array} other The other array to compare.
       * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
       * @param {Function} customizer The function to customize comparisons.
       * @param {Function} equalFunc The function to determine equivalents of values.
       * @param {Object} stack Tracks traversed `array` and `other` objects.
       * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
       */
      function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
        var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
          arrLength = array.length,
          othLength = other.length;
        if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
          return false;
        }
        // Check that cyclic values are equal.
        var arrStacked = stack.get(array);
        var othStacked = stack.get(other);
        if (arrStacked && othStacked) {
          return arrStacked == other && othStacked == array;
        }
        var index = -1,
          result = true,
          seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined;
        stack.set(array, other);
        stack.set(other, array);

        // Ignore non-index properties.
        while (++index < arrLength) {
          var arrValue = array[index],
            othValue = other[index];
          if (customizer) {
            var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
          }
          if (compared !== undefined) {
            if (compared) {
              continue;
            }
            result = false;
            break;
          }
          // Recursively compare arrays (susceptible to call stack limits).
          if (seen) {
            if (!arraySome(other, function (othValue, othIndex) {
              if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
                return seen.push(othIndex);
              }
            })) {
              result = false;
              break;
            }
          } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
            result = false;
            break;
          }
        }
        stack['delete'](array);
        stack['delete'](other);
        return result;
      }

      /**
       * Converts `map` to its key-value pairs.
       *
       * @private
       * @param {Object} map The map to convert.
       * @returns {Array} Returns the key-value pairs.
       */
      function mapToArray(map) {
        var index = -1,
          result = Array(map.size);
        map.forEach(function (value, key) {
          result[++index] = [key, value];
        });
        return result;
      }

      /**
       * Converts `set` to an array of its values.
       *
       * @private
       * @param {Object} set The set to convert.
       * @returns {Array} Returns the values.
       */
      function setToArray(set) {
        var index = -1,
          result = Array(set.size);
        set.forEach(function (value) {
          result[++index] = value;
        });
        return result;
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG$1 = 1,
        COMPARE_UNORDERED_FLAG$1 = 2;

      /** `Object#toString` result references. */
      var boolTag$3 = '[object Boolean]',
        dateTag$3 = '[object Date]',
        errorTag$3 = '[object Error]',
        mapTag$5 = '[object Map]',
        numberTag$3 = '[object Number]',
        regexpTag$3 = '[object RegExp]',
        setTag$5 = '[object Set]',
        stringTag$3 = '[object String]',
        symbolTag$3 = '[object Symbol]';
      var arrayBufferTag$3 = '[object ArrayBuffer]',
        dataViewTag$4 = '[object DataView]';

      /** Used to convert symbols to primitives and strings. */
      var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined,
        symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;

      /**
       * A specialized version of `baseIsEqualDeep` for comparing objects of
       * the same `toStringTag`.
       *
       * **Note:** This function only supports comparing values with tags of
       * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
       *
       * @private
       * @param {Object} object The object to compare.
       * @param {Object} other The other object to compare.
       * @param {string} tag The `toStringTag` of the objects to compare.
       * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
       * @param {Function} customizer The function to customize comparisons.
       * @param {Function} equalFunc The function to determine equivalents of values.
       * @param {Object} stack Tracks traversed `object` and `other` objects.
       * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
       */
      function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
        switch (tag) {
          case dataViewTag$4:
            if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
              return false;
            }
            object = object.buffer;
            other = other.buffer;
          case arrayBufferTag$3:
            if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) {
              return false;
            }
            return true;
          case boolTag$3:
          case dateTag$3:
          case numberTag$3:
            // Coerce booleans to `1` or `0` and dates to milliseconds.
            // Invalid dates are coerced to `NaN`.
            return eq(+object, +other);
          case errorTag$3:
            return object.name == other.name && object.message == other.message;
          case regexpTag$3:
          case stringTag$3:
            // Coerce regexes to strings and treat strings, primitives and objects,
            // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
            // for more details.
            return object == other + '';
          case mapTag$5:
            var convert = mapToArray;
          case setTag$5:
            var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
            convert || (convert = setToArray);
            if (object.size != other.size && !isPartial) {
              return false;
            }
            // Assume cyclic values are equal.
            var stacked = stack.get(object);
            if (stacked) {
              return stacked == other;
            }
            bitmask |= COMPARE_UNORDERED_FLAG$1;

            // Recursively compare objects (susceptible to call stack limits).
            stack.set(object, other);
            var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
            stack['delete'](object);
            return result;
          case symbolTag$3:
            if (symbolValueOf$1) {
              return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);
            }
        }
        return false;
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG$2 = 1;

      /** Used for built-in method references. */
      var objectProto$h = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$e = objectProto$h.hasOwnProperty;

      /**
       * A specialized version of `baseIsEqualDeep` for objects with support for
       * partial deep comparisons.
       *
       * @private
       * @param {Object} object The object to compare.
       * @param {Object} other The other object to compare.
       * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
       * @param {Function} customizer The function to customize comparisons.
       * @param {Function} equalFunc The function to determine equivalents of values.
       * @param {Object} stack Tracks traversed `object` and `other` objects.
       * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
       */
      function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
        var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
          objProps = getAllKeys(object),
          objLength = objProps.length,
          othProps = getAllKeys(other),
          othLength = othProps.length;
        if (objLength != othLength && !isPartial) {
          return false;
        }
        var index = objLength;
        while (index--) {
          var key = objProps[index];
          if (!(isPartial ? key in other : hasOwnProperty$e.call(other, key))) {
            return false;
          }
        }
        // Check that cyclic values are equal.
        var objStacked = stack.get(object);
        var othStacked = stack.get(other);
        if (objStacked && othStacked) {
          return objStacked == other && othStacked == object;
        }
        var result = true;
        stack.set(object, other);
        stack.set(other, object);
        var skipCtor = isPartial;
        while (++index < objLength) {
          key = objProps[index];
          var objValue = object[key],
            othValue = other[key];
          if (customizer) {
            var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
          }
          // Recursively compare objects (susceptible to call stack limits).
          if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
            result = false;
            break;
          }
          skipCtor || (skipCtor = key == 'constructor');
        }
        if (result && !skipCtor) {
          var objCtor = object.constructor,
            othCtor = other.constructor;

          // Non `Object` object instances with different constructors are not equal.
          if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
            result = false;
          }
        }
        stack['delete'](object);
        stack['delete'](other);
        return result;
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG$3 = 1;

      /** `Object#toString` result references. */
      var argsTag$3 = '[object Arguments]',
        arrayTag$2 = '[object Array]',
        objectTag$4 = '[object Object]';

      /** Used for built-in method references. */
      var objectProto$i = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$f = objectProto$i.hasOwnProperty;

      /**
       * A specialized version of `baseIsEqual` for arrays and objects which performs
       * deep comparisons and tracks traversed objects enabling objects with circular
       * references to be compared.
       *
       * @private
       * @param {Object} object The object to compare.
       * @param {Object} other The other object to compare.
       * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
       * @param {Function} customizer The function to customize comparisons.
       * @param {Function} equalFunc The function to determine equivalents of values.
       * @param {Object} [stack] Tracks traversed `object` and `other` objects.
       * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
       */
      function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
        var objIsArr = isArray$1(object),
          othIsArr = isArray$1(other),
          objTag = objIsArr ? arrayTag$2 : getTag$1(object),
          othTag = othIsArr ? arrayTag$2 : getTag$1(other);
        objTag = objTag == argsTag$3 ? objectTag$4 : objTag;
        othTag = othTag == argsTag$3 ? objectTag$4 : othTag;
        var objIsObj = objTag == objectTag$4,
          othIsObj = othTag == objectTag$4,
          isSameTag = objTag == othTag;
        if (isSameTag && isBuffer(object)) {
          if (!isBuffer(other)) {
            return false;
          }
          objIsArr = true;
          objIsObj = false;
        }
        if (isSameTag && !objIsObj) {
          stack || (stack = new Stack());
          return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
        }
        if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
          var objIsWrapped = objIsObj && hasOwnProperty$f.call(object, '__wrapped__'),
            othIsWrapped = othIsObj && hasOwnProperty$f.call(other, '__wrapped__');
          if (objIsWrapped || othIsWrapped) {
            var objUnwrapped = objIsWrapped ? object.value() : object,
              othUnwrapped = othIsWrapped ? other.value() : other;
            stack || (stack = new Stack());
            return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
          }
        }
        if (!isSameTag) {
          return false;
        }
        stack || (stack = new Stack());
        return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
      }

      /**
       * The base implementation of `_.isEqual` which supports partial comparisons
       * and tracks traversed objects.
       *
       * @private
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @param {boolean} bitmask The bitmask flags.
       *  1 - Unordered comparison
       *  2 - Partial comparison
       * @param {Function} [customizer] The function to customize comparisons.
       * @param {Object} [stack] Tracks traversed `value` and `other` objects.
       * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
       */
      function baseIsEqual(value, other, bitmask, customizer, stack) {
        if (value === other) {
          return true;
        }
        if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
          return value !== value && other !== other;
        }
        return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG$4 = 1,
        COMPARE_UNORDERED_FLAG$2 = 2;

      /**
       * The base implementation of `_.isMatch` without support for iteratee shorthands.
       *
       * @private
       * @param {Object} object The object to inspect.
       * @param {Object} source The object of property values to match.
       * @param {Array} matchData The property names, values, and compare flags to match.
       * @param {Function} [customizer] The function to customize comparisons.
       * @returns {boolean} Returns `true` if `object` is a match, else `false`.
       */
      function baseIsMatch(object, source, matchData, customizer) {
        var index = matchData.length,
          length = index,
          noCustomizer = !customizer;
        if (object == null) {
          return !length;
        }
        object = Object(object);
        while (index--) {
          var data = matchData[index];
          if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
            return false;
          }
        }
        while (++index < length) {
          data = matchData[index];
          var key = data[0],
            objValue = object[key],
            srcValue = data[1];
          if (noCustomizer && data[2]) {
            if (objValue === undefined && !(key in object)) {
              return false;
            }
          } else {
            var stack = new Stack();
            if (customizer) {
              var result = customizer(objValue, srcValue, key, object, source, stack);
            }
            if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
              return false;
            }
          }
        }
        return true;
      }

      /**
       * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` if suitable for strict
       *  equality comparisons, else `false`.
       */
      function isStrictComparable(value) {
        return value === value && !isObject(value);
      }

      /**
       * Gets the property names, values, and compare flags of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @returns {Array} Returns the match data of `object`.
       */
      function getMatchData(object) {
        var result = keys(object),
          length = result.length;
        while (length--) {
          var key = result[length],
            value = object[key];
          result[length] = [key, value, isStrictComparable(value)];
        }
        return result;
      }

      /**
       * A specialized version of `matchesProperty` for source values suitable
       * for strict equality comparisons, i.e. `===`.
       *
       * @private
       * @param {string} key The key of the property to get.
       * @param {*} srcValue The value to match.
       * @returns {Function} Returns the new spec function.
       */
      function matchesStrictComparable(key, srcValue) {
        return function (object) {
          if (object == null) {
            return false;
          }
          return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
        };
      }

      /**
       * The base implementation of `_.matches` which doesn't clone `source`.
       *
       * @private
       * @param {Object} source The object of property values to match.
       * @returns {Function} Returns the new spec function.
       */
      function baseMatches(source) {
        var matchData = getMatchData(source);
        if (matchData.length == 1 && matchData[0][2]) {
          return matchesStrictComparable(matchData[0][0], matchData[0][1]);
        }
        return function (object) {
          return object === source || baseIsMatch(object, source, matchData);
        };
      }

      /**
       * The base implementation of `_.hasIn` without support for deep paths.
       *
       * @private
       * @param {Object} [object] The object to query.
       * @param {Array|string} key The key to check.
       * @returns {boolean} Returns `true` if `key` exists, else `false`.
       */
      function baseHasIn(object, key) {
        return object != null && key in Object(object);
      }

      /**
       * Checks if `path` exists on `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array|string} path The path to check.
       * @param {Function} hasFunc The function to check properties.
       * @returns {boolean} Returns `true` if `path` exists, else `false`.
       */
      function hasPath(object, path, hasFunc) {
        path = castPath(path, object);
        var index = -1,
          length = path.length,
          result = false;
        while (++index < length) {
          var key = toKey(path[index]);
          if (!(result = object != null && hasFunc(object, key))) {
            break;
          }
          object = object[key];
        }
        if (result || ++index != length) {
          return result;
        }
        length = object == null ? 0 : object.length;
        return !!length && isLength(length) && isIndex(key, length) && (isArray$1(object) || isArguments(object));
      }

      /**
       * Checks if `path` is a direct or inherited property of `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The object to query.
       * @param {Array|string} path The path to check.
       * @returns {boolean} Returns `true` if `path` exists, else `false`.
       * @example
       *
       * var object = _.create({ 'a': _.create({ 'b': 2 }) });
       *
       * _.hasIn(object, 'a');
       * // => true
       *
       * _.hasIn(object, 'a.b');
       * // => true
       *
       * _.hasIn(object, ['a', 'b']);
       * // => true
       *
       * _.hasIn(object, 'b');
       * // => false
       */
      function hasIn(object, path) {
        return object != null && hasPath(object, path, baseHasIn);
      }

      /** Used to compose bitmasks for value comparisons. */
      var COMPARE_PARTIAL_FLAG$5 = 1,
        COMPARE_UNORDERED_FLAG$3 = 2;

      /**
       * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
       *
       * @private
       * @param {string} path The path of the property to get.
       * @param {*} srcValue The value to match.
       * @returns {Function} Returns the new spec function.
       */
      function baseMatchesProperty(path, srcValue) {
        if (isKey(path) && isStrictComparable(srcValue)) {
          return matchesStrictComparable(toKey(path), srcValue);
        }
        return function (object) {
          var objValue = get(object, path);
          return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
        };
      }

      /**
       * The base implementation of `_.property` without support for deep paths.
       *
       * @private
       * @param {string} key The key of the property to get.
       * @returns {Function} Returns the new accessor function.
       */
      function baseProperty(key) {
        return function (object) {
          return object == null ? undefined : object[key];
        };
      }

      /**
       * A specialized version of `baseProperty` which supports deep paths.
       *
       * @private
       * @param {Array|string} path The path of the property to get.
       * @returns {Function} Returns the new accessor function.
       */
      function basePropertyDeep(path) {
        return function (object) {
          return baseGet(object, path);
        };
      }

      /**
       * Creates a function that returns the value at `path` of a given object.
       *
       * @static
       * @memberOf _
       * @since 2.4.0
       * @category Util
       * @param {Array|string} path The path of the property to get.
       * @returns {Function} Returns the new accessor function.
       * @example
       *
       * var objects = [
       *   { 'a': { 'b': 2 } },
       *   { 'a': { 'b': 1 } }
       * ];
       *
       * _.map(objects, _.property('a.b'));
       * // => [2, 1]
       *
       * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
       * // => [1, 2]
       */
      function property(path) {
        return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
      }

      /**
       * The base implementation of `_.iteratee`.
       *
       * @private
       * @param {*} [value=_.identity] The value to convert to an iteratee.
       * @returns {Function} Returns the iteratee.
       */
      function baseIteratee(value) {
        // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
        // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
        if (typeof value == 'function') {
          return value;
        }
        if (value == null) {
          return identity;
        }
        if (typeof value == 'object') {
          return isArray$1(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
        }
        return property(value);
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT$4 = 'Expected a function';

      /**
       * Creates a function that iterates over `pairs` and invokes the corresponding
       * function of the first predicate to return truthy. The predicate-function
       * pairs are invoked with the `this` binding and arguments of the created
       * function.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {Array} pairs The predicate-function pairs.
       * @returns {Function} Returns the new composite function.
       * @example
       *
       * var func = _.cond([
       *   [_.matches({ 'a': 1 }),           _.constant('matches A')],
       *   [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
       *   [_.stubTrue,                      _.constant('no match')]
       * ]);
       *
       * func({ 'a': 1, 'b': 2 });
       * // => 'matches A'
       *
       * func({ 'a': 0, 'b': 1 });
       * // => 'matches B'
       *
       * func({ 'a': '1', 'b': '2' });
       * // => 'no match'
       */
      function cond(pairs) {
        var length = pairs == null ? 0 : pairs.length,
          toIteratee = baseIteratee;
        pairs = !length ? [] : arrayMap(pairs, function (pair) {
          if (typeof pair[1] != 'function') {
            throw new TypeError(FUNC_ERROR_TEXT$4);
          }
          return [toIteratee(pair[0]), pair[1]];
        });
        return baseRest(function (args) {
          var index = -1;
          while (++index < length) {
            var pair = pairs[index];
            if (apply(pair[0], this, args)) {
              return apply(pair[1], this, args);
            }
          }
        });
      }

      /**
       * The base implementation of `_.conformsTo` which accepts `props` to check.
       *
       * @private
       * @param {Object} object The object to inspect.
       * @param {Object} source The object of property predicates to conform to.
       * @returns {boolean} Returns `true` if `object` conforms, else `false`.
       */
      function baseConformsTo(object, source, props) {
        var length = props.length;
        if (object == null) {
          return !length;
        }
        object = Object(object);
        while (length--) {
          var key = props[length],
            predicate = source[key],
            value = object[key];
          if (value === undefined && !(key in object) || !predicate(value)) {
            return false;
          }
        }
        return true;
      }

      /**
       * The base implementation of `_.conforms` which doesn't clone `source`.
       *
       * @private
       * @param {Object} source The object of property predicates to conform to.
       * @returns {Function} Returns the new spec function.
       */
      function baseConforms(source) {
        var props = keys(source);
        return function (object) {
          return baseConformsTo(object, source, props);
        };
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$3 = 1;

      /**
       * Creates a function that invokes the predicate properties of `source` with
       * the corresponding property values of a given object, returning `true` if
       * all predicates return truthy, else `false`.
       *
       * **Note:** The created function is equivalent to `_.conformsTo` with
       * `source` partially applied.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {Object} source The object of property predicates to conform to.
       * @returns {Function} Returns the new spec function.
       * @example
       *
       * var objects = [
       *   { 'a': 2, 'b': 1 },
       *   { 'a': 1, 'b': 2 }
       * ];
       *
       * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
       * // => [{ 'a': 1, 'b': 2 }]
       */
      function conforms(source) {
        return baseConforms(baseClone(source, CLONE_DEEP_FLAG$3));
      }

      /**
       * Checks if `object` conforms to `source` by invoking the predicate
       * properties of `source` with the corresponding property values of `object`.
       *
       * **Note:** This method is equivalent to `_.conforms` when `source` is
       * partially applied.
       *
       * @static
       * @memberOf _
       * @since 4.14.0
       * @category Lang
       * @param {Object} object The object to inspect.
       * @param {Object} source The object of property predicates to conform to.
       * @returns {boolean} Returns `true` if `object` conforms, else `false`.
       * @example
       *
       * var object = { 'a': 1, 'b': 2 };
       *
       * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
       * // => true
       *
       * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
       * // => false
       */
      function conformsTo(object, source) {
        return source == null || baseConformsTo(object, source, keys(source));
      }

      /**
       * A specialized version of `baseAggregator` for arrays.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} setter The function to set `accumulator` values.
       * @param {Function} iteratee The iteratee to transform keys.
       * @param {Object} accumulator The initial aggregated object.
       * @returns {Function} Returns `accumulator`.
       */
      function arrayAggregator(array, setter, iteratee, accumulator) {
        var index = -1,
          length = array == null ? 0 : array.length;
        while (++index < length) {
          var value = array[index];
          setter(accumulator, value, iteratee(value), array);
        }
        return accumulator;
      }

      /**
       * Creates a base function for methods like `_.forIn` and `_.forOwn`.
       *
       * @private
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Function} Returns the new base function.
       */
      function createBaseFor(fromRight) {
        return function (object, iteratee, keysFunc) {
          var index = -1,
            iterable = Object(object),
            props = keysFunc(object),
            length = props.length;
          while (length--) {
            var key = props[fromRight ? length : ++index];
            if (iteratee(iterable[key], key, iterable) === false) {
              break;
            }
          }
          return object;
        };
      }

      /**
       * The base implementation of `baseForOwn` which iterates over `object`
       * properties returned by `keysFunc` and invokes `iteratee` for each property.
       * Iteratee functions may exit iteration early by explicitly returning `false`.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @param {Function} keysFunc The function to get the keys of `object`.
       * @returns {Object} Returns `object`.
       */
      var baseFor = createBaseFor();

      /**
       * The base implementation of `_.forOwn` without support for iteratee shorthands.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Object} Returns `object`.
       */
      function baseForOwn(object, iteratee) {
        return object && baseFor(object, iteratee, keys);
      }

      /**
       * Creates a `baseEach` or `baseEachRight` function.
       *
       * @private
       * @param {Function} eachFunc The function to iterate over a collection.
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Function} Returns the new base function.
       */
      function createBaseEach(eachFunc, fromRight) {
        return function (collection, iteratee) {
          if (collection == null) {
            return collection;
          }
          if (!isArrayLike(collection)) {
            return eachFunc(collection, iteratee);
          }
          var length = collection.length,
            index = fromRight ? length : -1,
            iterable = Object(collection);
          while (fromRight ? index-- : ++index < length) {
            if (iteratee(iterable[index], index, iterable) === false) {
              break;
            }
          }
          return collection;
        };
      }

      /**
       * The base implementation of `_.forEach` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array|Object} Returns `collection`.
       */
      var baseEach = createBaseEach(baseForOwn);

      /**
       * Aggregates elements of `collection` on `accumulator` with keys transformed
       * by `iteratee` and values set by `setter`.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} setter The function to set `accumulator` values.
       * @param {Function} iteratee The iteratee to transform keys.
       * @param {Object} accumulator The initial aggregated object.
       * @returns {Function} Returns `accumulator`.
       */
      function baseAggregator(collection, setter, iteratee, accumulator) {
        baseEach(collection, function (value, key, collection) {
          setter(accumulator, value, iteratee(value), collection);
        });
        return accumulator;
      }

      /**
       * Creates a function like `_.groupBy`.
       *
       * @private
       * @param {Function} setter The function to set accumulator values.
       * @param {Function} [initializer] The accumulator object initializer.
       * @returns {Function} Returns the new aggregator function.
       */
      function createAggregator(setter, initializer) {
        return function (collection, iteratee) {
          var func = isArray$1(collection) ? arrayAggregator : baseAggregator,
            accumulator = initializer ? initializer() : {};
          return func(collection, setter, baseIteratee(iteratee), accumulator);
        };
      }

      /** Used for built-in method references. */
      var objectProto$j = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$g = objectProto$j.hasOwnProperty;

      /**
       * Creates an object composed of keys generated from the results of running
       * each element of `collection` thru `iteratee`. The corresponding value of
       * each key is the number of times the key was returned by `iteratee`. The
       * iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 0.5.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
       * @returns {Object} Returns the composed aggregate object.
       * @example
       *
       * _.countBy([6.1, 4.2, 6.3], Math.floor);
       * // => { '4': 1, '6': 2 }
       *
       * // The `_.property` iteratee shorthand.
       * _.countBy(['one', 'two', 'three'], 'length');
       * // => { '3': 2, '5': 1 }
       */
      var countBy = createAggregator(function (result, value, key) {
        if (hasOwnProperty$g.call(result, key)) {
          ++result[key];
        } else {
          baseAssignValue(result, key, 1);
        }
      });

      /**
       * Creates an object that inherits from the `prototype` object. If a
       * `properties` object is given, its own enumerable string keyed properties
       * are assigned to the created object.
       *
       * @static
       * @memberOf _
       * @since 2.3.0
       * @category Object
       * @param {Object} prototype The object to inherit from.
       * @param {Object} [properties] The properties to assign to the object.
       * @returns {Object} Returns the new object.
       * @example
       *
       * function Shape() {
       *   this.x = 0;
       *   this.y = 0;
       * }
       *
       * function Circle() {
       *   Shape.call(this);
       * }
       *
       * Circle.prototype = _.create(Shape.prototype, {
       *   'constructor': Circle
       * });
       *
       * var circle = new Circle;
       * circle instanceof Circle;
       * // => true
       *
       * circle instanceof Shape;
       * // => true
       */
      function create(prototype, properties) {
        var result = baseCreate(prototype);
        return properties == null ? result : baseAssign(result, properties);
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_CURRY_FLAG$5 = 8;

      /**
       * Creates a function that accepts arguments of `func` and either invokes
       * `func` returning its result, if at least `arity` number of arguments have
       * been provided, or returns a function that accepts the remaining `func`
       * arguments, and so on. The arity of `func` may be specified if `func.length`
       * is not sufficient.
       *
       * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
       * may be used as a placeholder for provided arguments.
       *
       * **Note:** This method doesn't set the "length" property of curried functions.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Function
       * @param {Function} func The function to curry.
       * @param {number} [arity=func.length] The arity of `func`.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Function} Returns the new curried function.
       * @example
       *
       * var abc = function(a, b, c) {
       *   return [a, b, c];
       * };
       *
       * var curried = _.curry(abc);
       *
       * curried(1)(2)(3);
       * // => [1, 2, 3]
       *
       * curried(1, 2)(3);
       * // => [1, 2, 3]
       *
       * curried(1, 2, 3);
       * // => [1, 2, 3]
       *
       * // Curried with placeholders.
       * curried(1)(_, 3)(2);
       * // => [1, 2, 3]
       */
      function curry(func, arity, guard) {
        arity = guard ? undefined : arity;
        var result = createWrap(func, WRAP_CURRY_FLAG$5, undefined, undefined, undefined, undefined, undefined, arity);
        result.placeholder = curry.placeholder;
        return result;
      }

      // Assign default placeholders.
      curry.placeholder = {};

      /** Used to compose bitmasks for function metadata. */
      var WRAP_CURRY_RIGHT_FLAG$3 = 16;

      /**
       * This method is like `_.curry` except that arguments are applied to `func`
       * in the manner of `_.partialRight` instead of `_.partial`.
       *
       * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
       * builds, may be used as a placeholder for provided arguments.
       *
       * **Note:** This method doesn't set the "length" property of curried functions.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Function
       * @param {Function} func The function to curry.
       * @param {number} [arity=func.length] The arity of `func`.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Function} Returns the new curried function.
       * @example
       *
       * var abc = function(a, b, c) {
       *   return [a, b, c];
       * };
       *
       * var curried = _.curryRight(abc);
       *
       * curried(3)(2)(1);
       * // => [1, 2, 3]
       *
       * curried(2, 3)(1);
       * // => [1, 2, 3]
       *
       * curried(1, 2, 3);
       * // => [1, 2, 3]
       *
       * // Curried with placeholders.
       * curried(3)(1, _)(2);
       * // => [1, 2, 3]
       */
      function curryRight(func, arity, guard) {
        arity = guard ? undefined : arity;
        var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG$3, undefined, undefined, undefined, undefined, undefined, arity);
        result.placeholder = curryRight.placeholder;
        return result;
      }

      // Assign default placeholders.
      curryRight.placeholder = {};

      /**
       * Gets the timestamp of the number of milliseconds that have elapsed since
       * the Unix epoch (1 January 1970 00:00:00 UTC).
       *
       * @static
       * @memberOf _
       * @since 2.4.0
       * @category Date
       * @returns {number} Returns the timestamp.
       * @example
       *
       * _.defer(function(stamp) {
       *   console.log(_.now() - stamp);
       * }, _.now());
       * // => Logs the number of milliseconds it took for the deferred invocation.
       */
      var now = function now() {
        return root.Date.now();
      };

      /** Error message constants. */
      var FUNC_ERROR_TEXT$5 = 'Expected a function';

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$5 = Math.max,
        nativeMin$3 = Math.min;

      /**
       * Creates a debounced function that delays invoking `func` until after `wait`
       * milliseconds have elapsed since the last time the debounced function was
       * invoked. The debounced function comes with a `cancel` method to cancel
       * delayed `func` invocations and a `flush` method to immediately invoke them.
       * Provide `options` to indicate whether `func` should be invoked on the
       * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
       * with the last arguments provided to the debounced function. Subsequent
       * calls to the debounced function return the result of the last `func`
       * invocation.
       *
       * **Note:** If `leading` and `trailing` options are `true`, `func` is
       * invoked on the trailing edge of the timeout only if the debounced function
       * is invoked more than once during the `wait` timeout.
       *
       * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
       * until to the next tick, similar to `setTimeout` with a timeout of `0`.
       *
       * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
       * for details over the differences between `_.debounce` and `_.throttle`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to debounce.
       * @param {number} [wait=0] The number of milliseconds to delay.
       * @param {Object} [options={}] The options object.
       * @param {boolean} [options.leading=false]
       *  Specify invoking on the leading edge of the timeout.
       * @param {number} [options.maxWait]
       *  The maximum time `func` is allowed to be delayed before it's invoked.
       * @param {boolean} [options.trailing=true]
       *  Specify invoking on the trailing edge of the timeout.
       * @returns {Function} Returns the new debounced function.
       * @example
       *
       * // Avoid costly calculations while the window size is in flux.
       * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
       *
       * // Invoke `sendMail` when clicked, debouncing subsequent calls.
       * jQuery(element).on('click', _.debounce(sendMail, 300, {
       *   'leading': true,
       *   'trailing': false
       * }));
       *
       * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
       * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
       * var source = new EventSource('/stream');
       * jQuery(source).on('message', debounced);
       *
       * // Cancel the trailing debounced invocation.
       * jQuery(window).on('popstate', debounced.cancel);
       */
      function debounce(func, wait, options) {
        var lastArgs,
          lastThis,
          maxWait,
          result,
          timerId,
          lastCallTime,
          lastInvokeTime = 0,
          leading = false,
          maxing = false,
          trailing = true;
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$5);
        }
        wait = toNumber(wait) || 0;
        if (isObject(options)) {
          leading = !!options.leading;
          maxing = 'maxWait' in options;
          maxWait = maxing ? nativeMax$5(toNumber(options.maxWait) || 0, wait) : maxWait;
          trailing = 'trailing' in options ? !!options.trailing : trailing;
        }
        function invokeFunc(time) {
          var args = lastArgs,
            thisArg = lastThis;
          lastArgs = lastThis = undefined;
          lastInvokeTime = time;
          result = func.apply(thisArg, args);
          return result;
        }
        function leadingEdge(time) {
          // Reset any `maxWait` timer.
          lastInvokeTime = time;
          // Start the timer for the trailing edge.
          timerId = setTimeout(timerExpired, wait);
          // Invoke the leading edge.
          return leading ? invokeFunc(time) : result;
        }
        function remainingWait(time) {
          var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime,
            timeWaiting = wait - timeSinceLastCall;
          return maxing ? nativeMin$3(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
        }
        function shouldInvoke(time) {
          var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime;

          // Either this is the first call, activity has stopped and we're at the
          // trailing edge, the system time has gone backwards and we're treating
          // it as the trailing edge, or we've hit the `maxWait` limit.
          return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
        }
        function timerExpired() {
          var time = now();
          if (shouldInvoke(time)) {
            return trailingEdge(time);
          }
          // Restart the timer.
          timerId = setTimeout(timerExpired, remainingWait(time));
        }
        function trailingEdge(time) {
          timerId = undefined;

          // Only invoke if we have `lastArgs` which means `func` has been
          // debounced at least once.
          if (trailing && lastArgs) {
            return invokeFunc(time);
          }
          lastArgs = lastThis = undefined;
          return result;
        }
        function cancel() {
          if (timerId !== undefined) {
            clearTimeout(timerId);
          }
          lastInvokeTime = 0;
          lastArgs = lastCallTime = lastThis = timerId = undefined;
        }
        function flush() {
          return timerId === undefined ? result : trailingEdge(now());
        }
        function debounced() {
          var time = now(),
            isInvoking = shouldInvoke(time);
          lastArgs = arguments;
          lastThis = this;
          lastCallTime = time;
          if (isInvoking) {
            if (timerId === undefined) {
              return leadingEdge(lastCallTime);
            }
            if (maxing) {
              // Handle invocations in a tight loop.
              clearTimeout(timerId);
              timerId = setTimeout(timerExpired, wait);
              return invokeFunc(lastCallTime);
            }
          }
          if (timerId === undefined) {
            timerId = setTimeout(timerExpired, wait);
          }
          return result;
        }
        debounced.cancel = cancel;
        debounced.flush = flush;
        return debounced;
      }

      /**
       * Checks `value` to determine whether a default value should be returned in
       * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
       * or `undefined`.
       *
       * @static
       * @memberOf _
       * @since 4.14.0
       * @category Util
       * @param {*} value The value to check.
       * @param {*} defaultValue The default value.
       * @returns {*} Returns the resolved value.
       * @example
       *
       * _.defaultTo(1, 10);
       * // => 1
       *
       * _.defaultTo(undefined, 10);
       * // => 10
       */
      function defaultTo(value, defaultValue) {
        return value == null || value !== value ? defaultValue : value;
      }

      /** Used for built-in method references. */
      var objectProto$k = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$h = objectProto$k.hasOwnProperty;

      /**
       * Assigns own and inherited enumerable string keyed properties of source
       * objects to the destination object for all destination properties that
       * resolve to `undefined`. Source objects are applied from left to right.
       * Once a property is set, additional values of the same property are ignored.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} [sources] The source objects.
       * @returns {Object} Returns `object`.
       * @see _.defaultsDeep
       * @example
       *
       * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
       * // => { 'a': 1, 'b': 2 }
       */
      var defaults = baseRest(function (object, sources) {
        object = Object(object);
        var index = -1;
        var length = sources.length;
        var guard = length > 2 ? sources[2] : undefined;
        if (guard && isIterateeCall(sources[0], sources[1], guard)) {
          length = 1;
        }
        while (++index < length) {
          var source = sources[index];
          var props = keysIn(source);
          var propsIndex = -1;
          var propsLength = props.length;
          while (++propsIndex < propsLength) {
            var key = props[propsIndex];
            var value = object[key];
            if (value === undefined || eq(value, objectProto$k[key]) && !hasOwnProperty$h.call(object, key)) {
              object[key] = source[key];
            }
          }
        }
        return object;
      });

      /**
       * This function is like `assignValue` except that it doesn't assign
       * `undefined` values.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {string} key The key of the property to assign.
       * @param {*} value The value to assign.
       */
      function assignMergeValue(object, key, value) {
        if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) {
          baseAssignValue(object, key, value);
        }
      }

      /**
       * This method is like `_.isArrayLike` except that it also checks if `value`
       * is an object.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an array-like object,
       *  else `false`.
       * @example
       *
       * _.isArrayLikeObject([1, 2, 3]);
       * // => true
       *
       * _.isArrayLikeObject(document.body.children);
       * // => true
       *
       * _.isArrayLikeObject('abc');
       * // => false
       *
       * _.isArrayLikeObject(_.noop);
       * // => false
       */
      function isArrayLikeObject(value) {
        return isObjectLike(value) && isArrayLike(value);
      }

      /**
       * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
       *
       * @private
       * @param {Object} object The object to query.
       * @param {string} key The key of the property to get.
       * @returns {*} Returns the property value.
       */
      function safeGet(object, key) {
        if (key === 'constructor' && typeof object[key] === 'function') {
          return;
        }
        if (key == '__proto__') {
          return;
        }
        return object[key];
      }

      /**
       * Converts `value` to a plain object flattening inherited enumerable string
       * keyed properties of `value` to own properties of the plain object.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {Object} Returns the converted plain object.
       * @example
       *
       * function Foo() {
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.assign({ 'a': 1 }, new Foo);
       * // => { 'a': 1, 'b': 2 }
       *
       * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
       * // => { 'a': 1, 'b': 2, 'c': 3 }
       */
      function toPlainObject(value) {
        return copyObject(value, keysIn(value));
      }

      /**
       * A specialized version of `baseMerge` for arrays and objects which performs
       * deep merges and tracks traversed objects enabling objects with circular
       * references to be merged.
       *
       * @private
       * @param {Object} object The destination object.
       * @param {Object} source The source object.
       * @param {string} key The key of the value to merge.
       * @param {number} srcIndex The index of `source`.
       * @param {Function} mergeFunc The function to merge values.
       * @param {Function} [customizer] The function to customize assigned values.
       * @param {Object} [stack] Tracks traversed source values and their merged
       *  counterparts.
       */
      function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
        var objValue = safeGet(object, key),
          srcValue = safeGet(source, key),
          stacked = stack.get(srcValue);
        if (stacked) {
          assignMergeValue(object, key, stacked);
          return;
        }
        var newValue = customizer ? customizer(objValue, srcValue, key + '', object, source, stack) : undefined;
        var isCommon = newValue === undefined;
        if (isCommon) {
          var isArr = isArray$1(srcValue),
            isBuff = !isArr && isBuffer(srcValue),
            isTyped = !isArr && !isBuff && isTypedArray(srcValue);
          newValue = srcValue;
          if (isArr || isBuff || isTyped) {
            if (isArray$1(objValue)) {
              newValue = objValue;
            } else if (isArrayLikeObject(objValue)) {
              newValue = copyArray(objValue);
            } else if (isBuff) {
              isCommon = false;
              newValue = cloneBuffer(srcValue, true);
            } else if (isTyped) {
              isCommon = false;
              newValue = cloneTypedArray(srcValue, true);
            } else {
              newValue = [];
            }
          } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
            newValue = objValue;
            if (isArguments(objValue)) {
              newValue = toPlainObject(objValue);
            } else if (!isObject(objValue) || isFunction(objValue)) {
              newValue = initCloneObject(srcValue);
            }
          } else {
            isCommon = false;
          }
        }
        if (isCommon) {
          // Recursively merge objects and arrays (susceptible to call stack limits).
          stack.set(srcValue, newValue);
          mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
          stack['delete'](srcValue);
        }
        assignMergeValue(object, key, newValue);
      }

      /**
       * The base implementation of `_.merge` without support for multiple sources.
       *
       * @private
       * @param {Object} object The destination object.
       * @param {Object} source The source object.
       * @param {number} srcIndex The index of `source`.
       * @param {Function} [customizer] The function to customize merged values.
       * @param {Object} [stack] Tracks traversed source values and their merged
       *  counterparts.
       */
      function baseMerge(object, source, srcIndex, customizer, stack) {
        if (object === source) {
          return;
        }
        baseFor(source, function (srcValue, key) {
          stack || (stack = new Stack());
          if (isObject(srcValue)) {
            baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
          } else {
            var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + '', object, source, stack) : undefined;
            if (newValue === undefined) {
              newValue = srcValue;
            }
            assignMergeValue(object, key, newValue);
          }
        }, keysIn);
      }

      /**
       * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
       * objects into destination objects that are passed thru.
       *
       * @private
       * @param {*} objValue The destination value.
       * @param {*} srcValue The source value.
       * @param {string} key The key of the property to merge.
       * @param {Object} object The parent object of `objValue`.
       * @param {Object} source The parent object of `srcValue`.
       * @param {Object} [stack] Tracks traversed source values and their merged
       *  counterparts.
       * @returns {*} Returns the value to assign.
       */
      function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
        if (isObject(objValue) && isObject(srcValue)) {
          // Recursively merge objects and arrays (susceptible to call stack limits).
          stack.set(srcValue, objValue);
          baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
          stack['delete'](srcValue);
        }
        return objValue;
      }

      /**
       * This method is like `_.merge` except that it accepts `customizer` which
       * is invoked to produce the merged values of the destination and source
       * properties. If `customizer` returns `undefined`, merging is handled by the
       * method instead. The `customizer` is invoked with six arguments:
       * (objValue, srcValue, key, object, source, stack).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} sources The source objects.
       * @param {Function} customizer The function to customize assigned values.
       * @returns {Object} Returns `object`.
       * @example
       *
       * function customizer(objValue, srcValue) {
       *   if (_.isArray(objValue)) {
       *     return objValue.concat(srcValue);
       *   }
       * }
       *
       * var object = { 'a': [1], 'b': [2] };
       * var other = { 'a': [3], 'b': [4] };
       *
       * _.mergeWith(object, other, customizer);
       * // => { 'a': [1, 3], 'b': [2, 4] }
       */
      var mergeWith = createAssigner(function (object, source, srcIndex, customizer) {
        baseMerge(object, source, srcIndex, customizer);
      });

      /**
       * This method is like `_.defaults` except that it recursively assigns
       * default properties.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 3.10.0
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} [sources] The source objects.
       * @returns {Object} Returns `object`.
       * @see _.defaults
       * @example
       *
       * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
       * // => { 'a': { 'b': 2, 'c': 3 } }
       */
      var defaultsDeep = baseRest(function (args) {
        args.push(undefined, customDefaultsMerge);
        return apply(mergeWith, undefined, args);
      });

      /** Error message constants. */
      var FUNC_ERROR_TEXT$6 = 'Expected a function';

      /**
       * The base implementation of `_.delay` and `_.defer` which accepts `args`
       * to provide to `func`.
       *
       * @private
       * @param {Function} func The function to delay.
       * @param {number} wait The number of milliseconds to delay invocation.
       * @param {Array} args The arguments to provide to `func`.
       * @returns {number|Object} Returns the timer id or timeout object.
       */
      function baseDelay(func, wait, args) {
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$6);
        }
        return setTimeout(function () {
          func.apply(undefined, args);
        }, wait);
      }

      /**
       * Defers invoking the `func` until the current call stack has cleared. Any
       * additional arguments are provided to `func` when it's invoked.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to defer.
       * @param {...*} [args] The arguments to invoke `func` with.
       * @returns {number} Returns the timer id.
       * @example
       *
       * _.defer(function(text) {
       *   console.log(text);
       * }, 'deferred');
       * // => Logs 'deferred' after one millisecond.
       */
      var defer = baseRest(function (func, args) {
        return baseDelay(func, 1, args);
      });

      /**
       * Invokes `func` after `wait` milliseconds. Any additional arguments are
       * provided to `func` when it's invoked.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to delay.
       * @param {number} wait The number of milliseconds to delay invocation.
       * @param {...*} [args] The arguments to invoke `func` with.
       * @returns {number} Returns the timer id.
       * @example
       *
       * _.delay(function(text) {
       *   console.log(text);
       * }, 1000, 'later');
       * // => Logs 'later' after one second.
       */
      var delay = baseRest(function (func, wait, args) {
        return baseDelay(func, toNumber(wait) || 0, args);
      });

      /**
       * This function is like `arrayIncludes` except that it accepts a comparator.
       *
       * @private
       * @param {Array} [array] The array to inspect.
       * @param {*} target The value to search for.
       * @param {Function} comparator The comparator invoked per element.
       * @returns {boolean} Returns `true` if `target` is found, else `false`.
       */
      function arrayIncludesWith(array, value, comparator) {
        var index = -1,
          length = array == null ? 0 : array.length;
        while (++index < length) {
          if (comparator(value, array[index])) {
            return true;
          }
        }
        return false;
      }

      /** Used as the size to enable large array optimizations. */
      var LARGE_ARRAY_SIZE$1 = 200;

      /**
       * The base implementation of methods like `_.difference` without support
       * for excluding multiple arrays or iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {Array} values The values to exclude.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of filtered values.
       */
      function baseDifference(array, values, iteratee, comparator) {
        var index = -1,
          includes = arrayIncludes,
          isCommon = true,
          length = array.length,
          result = [],
          valuesLength = values.length;
        if (!length) {
          return result;
        }
        if (iteratee) {
          values = arrayMap(values, baseUnary(iteratee));
        }
        if (comparator) {
          includes = arrayIncludesWith;
          isCommon = false;
        } else if (values.length >= LARGE_ARRAY_SIZE$1) {
          includes = cacheHas;
          isCommon = false;
          values = new SetCache(values);
        }
        outer: while (++index < length) {
          var value = array[index],
            computed = iteratee == null ? value : iteratee(value);
          value = comparator || value !== 0 ? value : 0;
          if (isCommon && computed === computed) {
            var valuesIndex = valuesLength;
            while (valuesIndex--) {
              if (values[valuesIndex] === computed) {
                continue outer;
              }
            }
            result.push(value);
          } else if (!includes(values, computed, comparator)) {
            result.push(value);
          }
        }
        return result;
      }

      /**
       * Creates an array of `array` values not included in the other given arrays
       * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons. The order and references of result values are
       * determined by the first array.
       *
       * **Note:** Unlike `_.pullAll`, this method returns a new array.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {...Array} [values] The values to exclude.
       * @returns {Array} Returns the new array of filtered values.
       * @see _.without, _.xor
       * @example
       *
       * _.difference([2, 1], [2, 3]);
       * // => [1]
       */
      var difference = baseRest(function (array, values) {
        return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : [];
      });

      /**
       * Gets the last element of `array`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to query.
       * @returns {*} Returns the last element of `array`.
       * @example
       *
       * _.last([1, 2, 3]);
       * // => 3
       */
      function last(array) {
        var length = array == null ? 0 : array.length;
        return length ? array[length - 1] : undefined;
      }

      /**
       * This method is like `_.difference` except that it accepts `iteratee` which
       * is invoked for each element of `array` and `values` to generate the criterion
       * by which they're compared. The order and references of result values are
       * determined by the first array. The iteratee is invoked with one argument:
       * (value).
       *
       * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {...Array} [values] The values to exclude.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns the new array of filtered values.
       * @example
       *
       * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
       * // => [1.2]
       *
       * // The `_.property` iteratee shorthand.
       * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
       * // => [{ 'x': 2 }]
       */
      var differenceBy = baseRest(function (array, values) {
        var iteratee = last(values);
        if (isArrayLikeObject(iteratee)) {
          iteratee = undefined;
        }
        return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee)) : [];
      });

      /**
       * This method is like `_.difference` except that it accepts `comparator`
       * which is invoked to compare elements of `array` to `values`. The order and
       * references of result values are determined by the first array. The comparator
       * is invoked with two arguments: (arrVal, othVal).
       *
       * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {...Array} [values] The values to exclude.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of filtered values.
       * @example
       *
       * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
       *
       * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
       * // => [{ 'x': 2, 'y': 1 }]
       */
      var differenceWith = baseRest(function (array, values) {
        var comparator = last(values);
        if (isArrayLikeObject(comparator)) {
          comparator = undefined;
        }
        return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : [];
      });

      /**
       * Divide two numbers.
       *
       * @static
       * @memberOf _
       * @since 4.7.0
       * @category Math
       * @param {number} dividend The first number in a division.
       * @param {number} divisor The second number in a division.
       * @returns {number} Returns the quotient.
       * @example
       *
       * _.divide(6, 4);
       * // => 1.5
       */
      var divide = createMathOperation(function (dividend, divisor) {
        return dividend / divisor;
      }, 1);

      /**
       * Creates a slice of `array` with `n` elements dropped from the beginning.
       *
       * @static
       * @memberOf _
       * @since 0.5.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {number} [n=1] The number of elements to drop.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.drop([1, 2, 3]);
       * // => [2, 3]
       *
       * _.drop([1, 2, 3], 2);
       * // => [3]
       *
       * _.drop([1, 2, 3], 5);
       * // => []
       *
       * _.drop([1, 2, 3], 0);
       * // => [1, 2, 3]
       */
      function drop(array, n, guard) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        n = guard || n === undefined ? 1 : toInteger(n);
        return baseSlice(array, n < 0 ? 0 : n, length);
      }

      /**
       * Creates a slice of `array` with `n` elements dropped from the end.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {number} [n=1] The number of elements to drop.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.dropRight([1, 2, 3]);
       * // => [1, 2]
       *
       * _.dropRight([1, 2, 3], 2);
       * // => [1]
       *
       * _.dropRight([1, 2, 3], 5);
       * // => []
       *
       * _.dropRight([1, 2, 3], 0);
       * // => [1, 2, 3]
       */
      function dropRight(array, n, guard) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        n = guard || n === undefined ? 1 : toInteger(n);
        n = length - n;
        return baseSlice(array, 0, n < 0 ? 0 : n);
      }

      /**
       * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
       * without support for iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to query.
       * @param {Function} predicate The function invoked per iteration.
       * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Array} Returns the slice of `array`.
       */
      function baseWhile(array, predicate, isDrop, fromRight) {
        var length = array.length,
          index = fromRight ? length : -1;
        while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
        return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index);
      }

      /**
       * Creates a slice of `array` excluding elements dropped from the end.
       * Elements are dropped until `predicate` returns falsey. The predicate is
       * invoked with three arguments: (value, index, array).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': true },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': false }
       * ];
       *
       * _.dropRightWhile(users, function(o) { return !o.active; });
       * // => objects for ['barney']
       *
       * // The `_.matches` iteratee shorthand.
       * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
       * // => objects for ['barney', 'fred']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.dropRightWhile(users, ['active', false]);
       * // => objects for ['barney']
       *
       * // The `_.property` iteratee shorthand.
       * _.dropRightWhile(users, 'active');
       * // => objects for ['barney', 'fred', 'pebbles']
       */
      function dropRightWhile(array, predicate) {
        return array && array.length ? baseWhile(array, baseIteratee(predicate), true, true) : [];
      }

      /**
       * Creates a slice of `array` excluding elements dropped from the beginning.
       * Elements are dropped until `predicate` returns falsey. The predicate is
       * invoked with three arguments: (value, index, array).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': false },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': true }
       * ];
       *
       * _.dropWhile(users, function(o) { return !o.active; });
       * // => objects for ['pebbles']
       *
       * // The `_.matches` iteratee shorthand.
       * _.dropWhile(users, { 'user': 'barney', 'active': false });
       * // => objects for ['fred', 'pebbles']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.dropWhile(users, ['active', false]);
       * // => objects for ['pebbles']
       *
       * // The `_.property` iteratee shorthand.
       * _.dropWhile(users, 'active');
       * // => objects for ['barney', 'fred', 'pebbles']
       */
      function dropWhile(array, predicate) {
        return array && array.length ? baseWhile(array, baseIteratee(predicate), true) : [];
      }

      /**
       * Casts `value` to `identity` if it's not a function.
       *
       * @private
       * @param {*} value The value to inspect.
       * @returns {Function} Returns cast function.
       */
      function castFunction(value) {
        return typeof value == 'function' ? value : identity;
      }

      /**
       * Iterates over elements of `collection` and invokes `iteratee` for each element.
       * The iteratee is invoked with three arguments: (value, index|key, collection).
       * Iteratee functions may exit iteration early by explicitly returning `false`.
       *
       * **Note:** As with other "Collections" methods, objects with a "length"
       * property are iterated like arrays. To avoid this behavior use `_.forIn`
       * or `_.forOwn` for object iteration.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @alias each
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array|Object} Returns `collection`.
       * @see _.forEachRight
       * @example
       *
       * _.forEach([1, 2], function(value) {
       *   console.log(value);
       * });
       * // => Logs `1` then `2`.
       *
       * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
       *   console.log(key);
       * });
       * // => Logs 'a' then 'b' (iteration order is not guaranteed).
       */
      function forEach(collection, iteratee) {
        var func = isArray$1(collection) ? arrayEach : baseEach;
        return func(collection, castFunction(iteratee));
      }

      /**
       * A specialized version of `_.forEachRight` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array} Returns `array`.
       */
      function arrayEachRight(array, iteratee) {
        var length = array == null ? 0 : array.length;
        while (length--) {
          if (iteratee(array[length], length, array) === false) {
            break;
          }
        }
        return array;
      }

      /**
       * This function is like `baseFor` except that it iterates over properties
       * in the opposite order.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @param {Function} keysFunc The function to get the keys of `object`.
       * @returns {Object} Returns `object`.
       */
      var baseForRight = createBaseFor(true);

      /**
       * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Object} Returns `object`.
       */
      function baseForOwnRight(object, iteratee) {
        return object && baseForRight(object, iteratee, keys);
      }

      /**
       * The base implementation of `_.forEachRight` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array|Object} Returns `collection`.
       */
      var baseEachRight = createBaseEach(baseForOwnRight, true);

      /**
       * This method is like `_.forEach` except that it iterates over elements of
       * `collection` from right to left.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @alias eachRight
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array|Object} Returns `collection`.
       * @see _.forEach
       * @example
       *
       * _.forEachRight([1, 2], function(value) {
       *   console.log(value);
       * });
       * // => Logs `2` then `1`.
       */
      function forEachRight(collection, iteratee) {
        var func = isArray$1(collection) ? arrayEachRight : baseEachRight;
        return func(collection, castFunction(iteratee));
      }

      /**
       * Checks if `string` ends with the given target string.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to inspect.
       * @param {string} [target] The string to search for.
       * @param {number} [position=string.length] The position to search up to.
       * @returns {boolean} Returns `true` if `string` ends with `target`,
       *  else `false`.
       * @example
       *
       * _.endsWith('abc', 'c');
       * // => true
       *
       * _.endsWith('abc', 'b');
       * // => false
       *
       * _.endsWith('abc', 'b', 2);
       * // => true
       */
      function endsWith(string, target, position) {
        string = toString(string);
        target = baseToString(target);
        var length = string.length;
        position = position === undefined ? length : baseClamp(toInteger(position), 0, length);
        var end = position;
        position -= target.length;
        return position >= 0 && string.slice(position, end) == target;
      }

      /**
       * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
       * of key-value pairs for `object` corresponding to the property names of `props`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array} props The property names to get values for.
       * @returns {Object} Returns the key-value pairs.
       */
      function baseToPairs(object, props) {
        return arrayMap(props, function (key) {
          return [key, object[key]];
        });
      }

      /**
       * Converts `set` to its value-value pairs.
       *
       * @private
       * @param {Object} set The set to convert.
       * @returns {Array} Returns the value-value pairs.
       */
      function setToPairs(set) {
        var index = -1,
          result = Array(set.size);
        set.forEach(function (value) {
          result[++index] = [value, value];
        });
        return result;
      }

      /** `Object#toString` result references. */
      var mapTag$6 = '[object Map]',
        setTag$6 = '[object Set]';

      /**
       * Creates a `_.toPairs` or `_.toPairsIn` function.
       *
       * @private
       * @param {Function} keysFunc The function to get the keys of a given object.
       * @returns {Function} Returns the new pairs function.
       */
      function createToPairs(keysFunc) {
        return function (object) {
          var tag = getTag$1(object);
          if (tag == mapTag$6) {
            return mapToArray(object);
          }
          if (tag == setTag$6) {
            return setToPairs(object);
          }
          return baseToPairs(object, keysFunc(object));
        };
      }

      /**
       * Creates an array of own enumerable string keyed-value pairs for `object`
       * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
       * entries are returned.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @alias entries
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the key-value pairs.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.toPairs(new Foo);
       * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
       */
      var toPairs = createToPairs(keys);

      /**
       * Creates an array of own and inherited enumerable string keyed-value pairs
       * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
       * or set, its entries are returned.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @alias entriesIn
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the key-value pairs.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.toPairsIn(new Foo);
       * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
       */
      var toPairsIn = createToPairs(keysIn);

      /** Used to map characters to HTML entities. */
      var htmlEscapes = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
      };

      /**
       * Used by `_.escape` to convert characters to HTML entities.
       *
       * @private
       * @param {string} chr The matched character to escape.
       * @returns {string} Returns the escaped character.
       */
      var escapeHtmlChar = basePropertyOf(htmlEscapes);

      /** Used to match HTML entities and HTML characters. */
      var reUnescapedHtml = /[&<>"']/g,
        reHasUnescapedHtml = RegExp(reUnescapedHtml.source);

      /**
       * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
       * corresponding HTML entities.
       *
       * **Note:** No other characters are escaped. To escape additional
       * characters use a third-party library like [_he_](https://mths.be/he).
       *
       * Though the ">" character is escaped for symmetry, characters like
       * ">" and "/" don't need escaping in HTML and have no special meaning
       * unless they're part of a tag or unquoted attribute value. See
       * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
       * (under "semi-related fun fact") for more details.
       *
       * When working with HTML you should always
       * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
       * XSS vectors.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category String
       * @param {string} [string=''] The string to escape.
       * @returns {string} Returns the escaped string.
       * @example
       *
       * _.escape('fred, barney, & pebbles');
       * // => 'fred, barney, &amp; pebbles'
       */
      function escape(string) {
        string = toString(string);
        return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
      }

      /**
       * Used to match `RegExp`
       * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
       */
      var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g,
        reHasRegExpChar = RegExp(reRegExpChar$1.source);

      /**
       * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
       * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to escape.
       * @returns {string} Returns the escaped string.
       * @example
       *
       * _.escapeRegExp('[lodash](https://lodash.com/)');
       * // => '\[lodash\]\(https://lodash\.com/\)'
       */
      function escapeRegExp(string) {
        string = toString(string);
        return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar$1, '\\$&') : string;
      }

      /**
       * A specialized version of `_.every` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {boolean} Returns `true` if all elements pass the predicate check,
       *  else `false`.
       */
      function arrayEvery(array, predicate) {
        var index = -1,
          length = array == null ? 0 : array.length;
        while (++index < length) {
          if (!predicate(array[index], index, array)) {
            return false;
          }
        }
        return true;
      }

      /**
       * The base implementation of `_.every` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {boolean} Returns `true` if all elements pass the predicate check,
       *  else `false`
       */
      function baseEvery(collection, predicate) {
        var result = true;
        baseEach(collection, function (value, index, collection) {
          result = !!predicate(value, index, collection);
          return result;
        });
        return result;
      }

      /**
       * Checks if `predicate` returns truthy for **all** elements of `collection`.
       * Iteration is stopped once `predicate` returns falsey. The predicate is
       * invoked with three arguments: (value, index|key, collection).
       *
       * **Note:** This method returns `true` for
       * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
       * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
       * elements of empty collections.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {boolean} Returns `true` if all elements pass the predicate check,
       *  else `false`.
       * @example
       *
       * _.every([true, 1, null, 'yes'], Boolean);
       * // => false
       *
       * var users = [
       *   { 'user': 'barney', 'age': 36, 'active': false },
       *   { 'user': 'fred',   'age': 40, 'active': false }
       * ];
       *
       * // The `_.matches` iteratee shorthand.
       * _.every(users, { 'user': 'barney', 'active': false });
       * // => false
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.every(users, ['active', false]);
       * // => true
       *
       * // The `_.property` iteratee shorthand.
       * _.every(users, 'active');
       * // => false
       */
      function every(collection, predicate, guard) {
        var func = isArray$1(collection) ? arrayEvery : baseEvery;
        if (guard && isIterateeCall(collection, predicate, guard)) {
          predicate = undefined;
        }
        return func(collection, baseIteratee(predicate));
      }

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$1 = 4294967295;

      /**
       * Converts `value` to an integer suitable for use as the length of an
       * array-like object.
       *
       * **Note:** This method is based on
       * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {number} Returns the converted integer.
       * @example
       *
       * _.toLength(3.2);
       * // => 3
       *
       * _.toLength(Number.MIN_VALUE);
       * // => 0
       *
       * _.toLength(Infinity);
       * // => 4294967295
       *
       * _.toLength('3.2');
       * // => 3
       */
      function toLength(value) {
        return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH$1) : 0;
      }

      /**
       * The base implementation of `_.fill` without an iteratee call guard.
       *
       * @private
       * @param {Array} array The array to fill.
       * @param {*} value The value to fill `array` with.
       * @param {number} [start=0] The start position.
       * @param {number} [end=array.length] The end position.
       * @returns {Array} Returns `array`.
       */
      function baseFill(array, value, start, end) {
        var length = array.length;
        start = toInteger(start);
        if (start < 0) {
          start = -start > length ? 0 : length + start;
        }
        end = end === undefined || end > length ? length : toInteger(end);
        if (end < 0) {
          end += length;
        }
        end = start > end ? 0 : toLength(end);
        while (start < end) {
          array[start++] = value;
        }
        return array;
      }

      /**
       * Fills elements of `array` with `value` from `start` up to, but not
       * including, `end`.
       *
       * **Note:** This method mutates `array`.
       *
       * @static
       * @memberOf _
       * @since 3.2.0
       * @category Array
       * @param {Array} array The array to fill.
       * @param {*} value The value to fill `array` with.
       * @param {number} [start=0] The start position.
       * @param {number} [end=array.length] The end position.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = [1, 2, 3];
       *
       * _.fill(array, 'a');
       * console.log(array);
       * // => ['a', 'a', 'a']
       *
       * _.fill(Array(3), 2);
       * // => [2, 2, 2]
       *
       * _.fill([4, 6, 8, 10], '*', 1, 3);
       * // => [4, '*', '*', 10]
       */
      function fill(array, value, start, end) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
          start = 0;
          end = length;
        }
        return baseFill(array, value, start, end);
      }

      /**
       * The base implementation of `_.filter` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {Array} Returns the new filtered array.
       */
      function baseFilter(collection, predicate) {
        var result = [];
        baseEach(collection, function (value, index, collection) {
          if (predicate(value, index, collection)) {
            result.push(value);
          }
        });
        return result;
      }

      /**
       * Iterates over elements of `collection`, returning an array of all elements
       * `predicate` returns truthy for. The predicate is invoked with three
       * arguments: (value, index|key, collection).
       *
       * **Note:** Unlike `_.remove`, this method returns a new array.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new filtered array.
       * @see _.reject
       * @example
       *
       * var users = [
       *   { 'user': 'barney', 'age': 36, 'active': true },
       *   { 'user': 'fred',   'age': 40, 'active': false }
       * ];
       *
       * _.filter(users, function(o) { return !o.active; });
       * // => objects for ['fred']
       *
       * // The `_.matches` iteratee shorthand.
       * _.filter(users, { 'age': 36, 'active': true });
       * // => objects for ['barney']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.filter(users, ['active', false]);
       * // => objects for ['fred']
       *
       * // The `_.property` iteratee shorthand.
       * _.filter(users, 'active');
       * // => objects for ['barney']
       *
       * // Combining several predicates using `_.overEvery` or `_.overSome`.
       * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
       * // => objects for ['fred', 'barney']
       */
      function filter(collection, predicate) {
        var func = isArray$1(collection) ? arrayFilter : baseFilter;
        return func(collection, baseIteratee(predicate));
      }

      /**
       * Creates a `_.find` or `_.findLast` function.
       *
       * @private
       * @param {Function} findIndexFunc The function to find the collection index.
       * @returns {Function} Returns the new find function.
       */
      function createFind(findIndexFunc) {
        return function (collection, predicate, fromIndex) {
          var iterable = Object(collection);
          if (!isArrayLike(collection)) {
            var iteratee = baseIteratee(predicate);
            collection = keys(collection);
            predicate = function predicate(key) {
              return iteratee(iterable[key], key, iterable);
            };
          }
          var index = findIndexFunc(collection, predicate, fromIndex);
          return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
        };
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$6 = Math.max;

      /**
       * This method is like `_.find` except that it returns the index of the first
       * element `predicate` returns truthy for instead of the element itself.
       *
       * @static
       * @memberOf _
       * @since 1.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param {number} [fromIndex=0] The index to search from.
       * @returns {number} Returns the index of the found element, else `-1`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': false },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': true }
       * ];
       *
       * _.findIndex(users, function(o) { return o.user == 'barney'; });
       * // => 0
       *
       * // The `_.matches` iteratee shorthand.
       * _.findIndex(users, { 'user': 'fred', 'active': false });
       * // => 1
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.findIndex(users, ['active', false]);
       * // => 0
       *
       * // The `_.property` iteratee shorthand.
       * _.findIndex(users, 'active');
       * // => 2
       */
      function findIndex(array, predicate, fromIndex) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return -1;
        }
        var index = fromIndex == null ? 0 : toInteger(fromIndex);
        if (index < 0) {
          index = nativeMax$6(length + index, 0);
        }
        return baseFindIndex(array, baseIteratee(predicate), index);
      }

      /**
       * Iterates over elements of `collection`, returning the first element
       * `predicate` returns truthy for. The predicate is invoked with three
       * arguments: (value, index|key, collection).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param {number} [fromIndex=0] The index to search from.
       * @returns {*} Returns the matched element, else `undefined`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'age': 36, 'active': true },
       *   { 'user': 'fred',    'age': 40, 'active': false },
       *   { 'user': 'pebbles', 'age': 1,  'active': true }
       * ];
       *
       * _.find(users, function(o) { return o.age < 40; });
       * // => object for 'barney'
       *
       * // The `_.matches` iteratee shorthand.
       * _.find(users, { 'age': 1, 'active': true });
       * // => object for 'pebbles'
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.find(users, ['active', false]);
       * // => object for 'fred'
       *
       * // The `_.property` iteratee shorthand.
       * _.find(users, 'active');
       * // => object for 'barney'
       */
      var find = createFind(findIndex);

      /**
       * The base implementation of methods like `_.findKey` and `_.findLastKey`,
       * without support for iteratee shorthands, which iterates over `collection`
       * using `eachFunc`.
       *
       * @private
       * @param {Array|Object} collection The collection to inspect.
       * @param {Function} predicate The function invoked per iteration.
       * @param {Function} eachFunc The function to iterate over `collection`.
       * @returns {*} Returns the found element or its key, else `undefined`.
       */
      function baseFindKey(collection, predicate, eachFunc) {
        var result;
        eachFunc(collection, function (value, key, collection) {
          if (predicate(value, key, collection)) {
            result = key;
            return false;
          }
        });
        return result;
      }

      /**
       * This method is like `_.find` except that it returns the key of the first
       * element `predicate` returns truthy for instead of the element itself.
       *
       * @static
       * @memberOf _
       * @since 1.1.0
       * @category Object
       * @param {Object} object The object to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {string|undefined} Returns the key of the matched element,
       *  else `undefined`.
       * @example
       *
       * var users = {
       *   'barney':  { 'age': 36, 'active': true },
       *   'fred':    { 'age': 40, 'active': false },
       *   'pebbles': { 'age': 1,  'active': true }
       * };
       *
       * _.findKey(users, function(o) { return o.age < 40; });
       * // => 'barney' (iteration order is not guaranteed)
       *
       * // The `_.matches` iteratee shorthand.
       * _.findKey(users, { 'age': 1, 'active': true });
       * // => 'pebbles'
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.findKey(users, ['active', false]);
       * // => 'fred'
       *
       * // The `_.property` iteratee shorthand.
       * _.findKey(users, 'active');
       * // => 'barney'
       */
      function findKey(object, predicate) {
        return baseFindKey(object, baseIteratee(predicate), baseForOwn);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$7 = Math.max,
        nativeMin$4 = Math.min;

      /**
       * This method is like `_.findIndex` except that it iterates over elements
       * of `collection` from right to left.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param {number} [fromIndex=array.length-1] The index to search from.
       * @returns {number} Returns the index of the found element, else `-1`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': true },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': false }
       * ];
       *
       * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
       * // => 2
       *
       * // The `_.matches` iteratee shorthand.
       * _.findLastIndex(users, { 'user': 'barney', 'active': true });
       * // => 0
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.findLastIndex(users, ['active', false]);
       * // => 2
       *
       * // The `_.property` iteratee shorthand.
       * _.findLastIndex(users, 'active');
       * // => 0
       */
      function findLastIndex(array, predicate, fromIndex) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return -1;
        }
        var index = length - 1;
        if (fromIndex !== undefined) {
          index = toInteger(fromIndex);
          index = fromIndex < 0 ? nativeMax$7(length + index, 0) : nativeMin$4(index, length - 1);
        }
        return baseFindIndex(array, baseIteratee(predicate), index, true);
      }

      /**
       * This method is like `_.find` except that it iterates over elements of
       * `collection` from right to left.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param {number} [fromIndex=collection.length-1] The index to search from.
       * @returns {*} Returns the matched element, else `undefined`.
       * @example
       *
       * _.findLast([1, 2, 3, 4], function(n) {
       *   return n % 2 == 1;
       * });
       * // => 3
       */
      var findLast = createFind(findLastIndex);

      /**
       * This method is like `_.findKey` except that it iterates over elements of
       * a collection in the opposite order.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Object
       * @param {Object} object The object to inspect.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {string|undefined} Returns the key of the matched element,
       *  else `undefined`.
       * @example
       *
       * var users = {
       *   'barney':  { 'age': 36, 'active': true },
       *   'fred':    { 'age': 40, 'active': false },
       *   'pebbles': { 'age': 1,  'active': true }
       * };
       *
       * _.findLastKey(users, function(o) { return o.age < 40; });
       * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
       *
       * // The `_.matches` iteratee shorthand.
       * _.findLastKey(users, { 'age': 36, 'active': true });
       * // => 'barney'
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.findLastKey(users, ['active', false]);
       * // => 'fred'
       *
       * // The `_.property` iteratee shorthand.
       * _.findLastKey(users, 'active');
       * // => 'pebbles'
       */
      function findLastKey(object, predicate) {
        return baseFindKey(object, baseIteratee(predicate), baseForOwnRight);
      }

      /**
       * Gets the first element of `array`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @alias first
       * @category Array
       * @param {Array} array The array to query.
       * @returns {*} Returns the first element of `array`.
       * @example
       *
       * _.head([1, 2, 3]);
       * // => 1
       *
       * _.head([]);
       * // => undefined
       */
      function head(array) {
        return array && array.length ? array[0] : undefined;
      }

      /**
       * The base implementation of `_.map` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {Array} Returns the new mapped array.
       */
      function baseMap(collection, iteratee) {
        var index = -1,
          result = isArrayLike(collection) ? Array(collection.length) : [];
        baseEach(collection, function (value, key, collection) {
          result[++index] = iteratee(value, key, collection);
        });
        return result;
      }

      /**
       * Creates an array of values by running each element in `collection` thru
       * `iteratee`. The iteratee is invoked with three arguments:
       * (value, index|key, collection).
       *
       * Many lodash methods are guarded to work as iteratees for methods like
       * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
       *
       * The guarded methods are:
       * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
       * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
       * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
       * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new mapped array.
       * @example
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * _.map([4, 8], square);
       * // => [16, 64]
       *
       * _.map({ 'a': 4, 'b': 8 }, square);
       * // => [16, 64] (iteration order is not guaranteed)
       *
       * var users = [
       *   { 'user': 'barney' },
       *   { 'user': 'fred' }
       * ];
       *
       * // The `_.property` iteratee shorthand.
       * _.map(users, 'user');
       * // => ['barney', 'fred']
       */
      function map(collection, iteratee) {
        var func = isArray$1(collection) ? arrayMap : baseMap;
        return func(collection, baseIteratee(iteratee));
      }

      /**
       * Creates a flattened array of values by running each element in `collection`
       * thru `iteratee` and flattening the mapped results. The iteratee is invoked
       * with three arguments: (value, index|key, collection).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * function duplicate(n) {
       *   return [n, n];
       * }
       *
       * _.flatMap([1, 2], duplicate);
       * // => [1, 1, 2, 2]
       */
      function flatMap(collection, iteratee) {
        return baseFlatten(map(collection, iteratee), 1);
      }

      /** Used as references for various `Number` constants. */
      var INFINITY$3 = 1 / 0;

      /**
       * This method is like `_.flatMap` except that it recursively flattens the
       * mapped results.
       *
       * @static
       * @memberOf _
       * @since 4.7.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * function duplicate(n) {
       *   return [[[n, n]]];
       * }
       *
       * _.flatMapDeep([1, 2], duplicate);
       * // => [1, 1, 2, 2]
       */
      function flatMapDeep(collection, iteratee) {
        return baseFlatten(map(collection, iteratee), INFINITY$3);
      }

      /**
       * This method is like `_.flatMap` except that it recursively flattens the
       * mapped results up to `depth` times.
       *
       * @static
       * @memberOf _
       * @since 4.7.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @param {number} [depth=1] The maximum recursion depth.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * function duplicate(n) {
       *   return [[[n, n]]];
       * }
       *
       * _.flatMapDepth([1, 2], duplicate, 2);
       * // => [[1, 1], [2, 2]]
       */
      function flatMapDepth(collection, iteratee, depth) {
        depth = depth === undefined ? 1 : toInteger(depth);
        return baseFlatten(map(collection, iteratee), depth);
      }

      /** Used as references for various `Number` constants. */
      var INFINITY$4 = 1 / 0;

      /**
       * Recursively flattens `array`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to flatten.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * _.flattenDeep([1, [2, [3, [4]], 5]]);
       * // => [1, 2, 3, 4, 5]
       */
      function flattenDeep(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseFlatten(array, INFINITY$4) : [];
      }

      /**
       * Recursively flatten `array` up to `depth` times.
       *
       * @static
       * @memberOf _
       * @since 4.4.0
       * @category Array
       * @param {Array} array The array to flatten.
       * @param {number} [depth=1] The maximum recursion depth.
       * @returns {Array} Returns the new flattened array.
       * @example
       *
       * var array = [1, [2, [3, [4]], 5]];
       *
       * _.flattenDepth(array, 1);
       * // => [1, 2, [3, [4]], 5]
       *
       * _.flattenDepth(array, 2);
       * // => [1, 2, 3, [4], 5]
       */
      function flattenDepth(array, depth) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        depth = depth === undefined ? 1 : toInteger(depth);
        return baseFlatten(array, depth);
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_FLIP_FLAG$2 = 512;

      /**
       * Creates a function that invokes `func` with arguments reversed.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Function
       * @param {Function} func The function to flip arguments for.
       * @returns {Function} Returns the new flipped function.
       * @example
       *
       * var flipped = _.flip(function() {
       *   return _.toArray(arguments);
       * });
       *
       * flipped('a', 'b', 'c', 'd');
       * // => ['d', 'c', 'b', 'a']
       */
      function flip(func) {
        return createWrap(func, WRAP_FLIP_FLAG$2);
      }

      /**
       * Computes `number` rounded down to `precision`.
       *
       * @static
       * @memberOf _
       * @since 3.10.0
       * @category Math
       * @param {number} number The number to round down.
       * @param {number} [precision=0] The precision to round down to.
       * @returns {number} Returns the rounded down number.
       * @example
       *
       * _.floor(4.006);
       * // => 4
       *
       * _.floor(0.046, 2);
       * // => 0.04
       *
       * _.floor(4060, -2);
       * // => 4000
       */
      var floor = createRound('floor');

      /** Error message constants. */
      var FUNC_ERROR_TEXT$7 = 'Expected a function';

      /** Used to compose bitmasks for function metadata. */
      var WRAP_CURRY_FLAG$6 = 8,
        WRAP_PARTIAL_FLAG$5 = 32,
        WRAP_ARY_FLAG$4 = 128,
        WRAP_REARG_FLAG$2 = 256;

      /**
       * Creates a `_.flow` or `_.flowRight` function.
       *
       * @private
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Function} Returns the new flow function.
       */
      function createFlow(fromRight) {
        return flatRest(function (funcs) {
          var length = funcs.length,
            index = length,
            prereq = LodashWrapper.prototype.thru;
          if (fromRight) {
            funcs.reverse();
          }
          while (index--) {
            var func = funcs[index];
            if (typeof func != 'function') {
              throw new TypeError(FUNC_ERROR_TEXT$7);
            }
            if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
              var wrapper = new LodashWrapper([], true);
            }
          }
          index = wrapper ? index : length;
          while (++index < length) {
            func = funcs[index];
            var funcName = getFuncName(func),
              data = funcName == 'wrapper' ? getData(func) : undefined;
            if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG$4 | WRAP_CURRY_FLAG$6 | WRAP_PARTIAL_FLAG$5 | WRAP_REARG_FLAG$2) && !data[4].length && data[9] == 1) {
              wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
            } else {
              wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
            }
          }
          return function () {
            var args = arguments,
              value = args[0];
            if (wrapper && args.length == 1 && isArray$1(value)) {
              return wrapper.plant(value).value();
            }
            var index = 0,
              result = length ? funcs[index].apply(this, args) : value;
            while (++index < length) {
              result = funcs[index].call(this, result);
            }
            return result;
          };
        });
      }

      /**
       * Creates a function that returns the result of invoking the given functions
       * with the `this` binding of the created function, where each successive
       * invocation is supplied the return value of the previous.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Util
       * @param {...(Function|Function[])} [funcs] The functions to invoke.
       * @returns {Function} Returns the new composite function.
       * @see _.flowRight
       * @example
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * var addSquare = _.flow([_.add, square]);
       * addSquare(1, 2);
       * // => 9
       */
      var flow = createFlow();

      /**
       * This method is like `_.flow` except that it creates a function that
       * invokes the given functions from right to left.
       *
       * @static
       * @since 3.0.0
       * @memberOf _
       * @category Util
       * @param {...(Function|Function[])} [funcs] The functions to invoke.
       * @returns {Function} Returns the new composite function.
       * @see _.flow
       * @example
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * var addSquare = _.flowRight([square, _.add]);
       * addSquare(1, 2);
       * // => 9
       */
      var flowRight = createFlow(true);

      /**
       * Iterates over own and inherited enumerable string keyed properties of an
       * object and invokes `iteratee` for each property. The iteratee is invoked
       * with three arguments: (value, key, object). Iteratee functions may exit
       * iteration early by explicitly returning `false`.
       *
       * @static
       * @memberOf _
       * @since 0.3.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns `object`.
       * @see _.forInRight
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.forIn(new Foo, function(value, key) {
       *   console.log(key);
       * });
       * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
       */
      function forIn(object, iteratee) {
        return object == null ? object : baseFor(object, castFunction(iteratee), keysIn);
      }

      /**
       * This method is like `_.forIn` except that it iterates over properties of
       * `object` in the opposite order.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns `object`.
       * @see _.forIn
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.forInRight(new Foo, function(value, key) {
       *   console.log(key);
       * });
       * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
       */
      function forInRight(object, iteratee) {
        return object == null ? object : baseForRight(object, castFunction(iteratee), keysIn);
      }

      /**
       * Iterates over own enumerable string keyed properties of an object and
       * invokes `iteratee` for each property. The iteratee is invoked with three
       * arguments: (value, key, object). Iteratee functions may exit iteration
       * early by explicitly returning `false`.
       *
       * @static
       * @memberOf _
       * @since 0.3.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns `object`.
       * @see _.forOwnRight
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.forOwn(new Foo, function(value, key) {
       *   console.log(key);
       * });
       * // => Logs 'a' then 'b' (iteration order is not guaranteed).
       */
      function forOwn(object, iteratee) {
        return object && baseForOwn(object, castFunction(iteratee));
      }

      /**
       * This method is like `_.forOwn` except that it iterates over properties of
       * `object` in the opposite order.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns `object`.
       * @see _.forOwn
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.forOwnRight(new Foo, function(value, key) {
       *   console.log(key);
       * });
       * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
       */
      function forOwnRight(object, iteratee) {
        return object && baseForOwnRight(object, castFunction(iteratee));
      }

      /**
       * The inverse of `_.toPairs`; this method returns an object composed
       * from key-value `pairs`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} pairs The key-value pairs.
       * @returns {Object} Returns the new object.
       * @example
       *
       * _.fromPairs([['a', 1], ['b', 2]]);
       * // => { 'a': 1, 'b': 2 }
       */
      function fromPairs(pairs) {
        var index = -1,
          length = pairs == null ? 0 : pairs.length,
          result = {};
        while (++index < length) {
          var pair = pairs[index];
          result[pair[0]] = pair[1];
        }
        return result;
      }

      /**
       * The base implementation of `_.functions` which creates an array of
       * `object` function property names filtered from `props`.
       *
       * @private
       * @param {Object} object The object to inspect.
       * @param {Array} props The property names to filter.
       * @returns {Array} Returns the function names.
       */
      function baseFunctions(object, props) {
        return arrayFilter(props, function (key) {
          return isFunction(object[key]);
        });
      }

      /**
       * Creates an array of function property names from own enumerable properties
       * of `object`.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The object to inspect.
       * @returns {Array} Returns the function names.
       * @see _.functionsIn
       * @example
       *
       * function Foo() {
       *   this.a = _.constant('a');
       *   this.b = _.constant('b');
       * }
       *
       * Foo.prototype.c = _.constant('c');
       *
       * _.functions(new Foo);
       * // => ['a', 'b']
       */
      function functions(object) {
        return object == null ? [] : baseFunctions(object, keys(object));
      }

      /**
       * Creates an array of function property names from own and inherited
       * enumerable properties of `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The object to inspect.
       * @returns {Array} Returns the function names.
       * @see _.functions
       * @example
       *
       * function Foo() {
       *   this.a = _.constant('a');
       *   this.b = _.constant('b');
       * }
       *
       * Foo.prototype.c = _.constant('c');
       *
       * _.functionsIn(new Foo);
       * // => ['a', 'b', 'c']
       */
      function functionsIn(object) {
        return object == null ? [] : baseFunctions(object, keysIn(object));
      }

      /** Used for built-in method references. */
      var objectProto$l = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$i = objectProto$l.hasOwnProperty;

      /**
       * Creates an object composed of keys generated from the results of running
       * each element of `collection` thru `iteratee`. The order of grouped values
       * is determined by the order they occur in `collection`. The corresponding
       * value of each key is an array of elements responsible for generating the
       * key. The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
       * @returns {Object} Returns the composed aggregate object.
       * @example
       *
       * _.groupBy([6.1, 4.2, 6.3], Math.floor);
       * // => { '4': [4.2], '6': [6.1, 6.3] }
       *
       * // The `_.property` iteratee shorthand.
       * _.groupBy(['one', 'two', 'three'], 'length');
       * // => { '3': ['one', 'two'], '5': ['three'] }
       */
      var groupBy = createAggregator(function (result, value, key) {
        if (hasOwnProperty$i.call(result, key)) {
          result[key].push(value);
        } else {
          baseAssignValue(result, key, [value]);
        }
      });

      /**
       * The base implementation of `_.gt` which doesn't coerce arguments.
       *
       * @private
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is greater than `other`,
       *  else `false`.
       */
      function baseGt(value, other) {
        return value > other;
      }

      /**
       * Creates a function that performs a relational operation on two values.
       *
       * @private
       * @param {Function} operator The function to perform the operation.
       * @returns {Function} Returns the new relational operation function.
       */
      function createRelationalOperation(operator) {
        return function (value, other) {
          if (!(typeof value == 'string' && typeof other == 'string')) {
            value = toNumber(value);
            other = toNumber(other);
          }
          return operator(value, other);
        };
      }

      /**
       * Checks if `value` is greater than `other`.
       *
       * @static
       * @memberOf _
       * @since 3.9.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is greater than `other`,
       *  else `false`.
       * @see _.lt
       * @example
       *
       * _.gt(3, 1);
       * // => true
       *
       * _.gt(3, 3);
       * // => false
       *
       * _.gt(1, 3);
       * // => false
       */
      var gt = createRelationalOperation(baseGt);

      /**
       * Checks if `value` is greater than or equal to `other`.
       *
       * @static
       * @memberOf _
       * @since 3.9.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is greater than or equal to
       *  `other`, else `false`.
       * @see _.lte
       * @example
       *
       * _.gte(3, 1);
       * // => true
       *
       * _.gte(3, 3);
       * // => true
       *
       * _.gte(1, 3);
       * // => false
       */
      var gte = createRelationalOperation(function (value, other) {
        return value >= other;
      });

      /** Used for built-in method references. */
      var objectProto$m = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$j = objectProto$m.hasOwnProperty;

      /**
       * The base implementation of `_.has` without support for deep paths.
       *
       * @private
       * @param {Object} [object] The object to query.
       * @param {Array|string} key The key to check.
       * @returns {boolean} Returns `true` if `key` exists, else `false`.
       */
      function baseHas(object, key) {
        return object != null && hasOwnProperty$j.call(object, key);
      }

      /**
       * Checks if `path` is a direct property of `object`.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The object to query.
       * @param {Array|string} path The path to check.
       * @returns {boolean} Returns `true` if `path` exists, else `false`.
       * @example
       *
       * var object = { 'a': { 'b': 2 } };
       * var other = _.create({ 'a': _.create({ 'b': 2 }) });
       *
       * _.has(object, 'a');
       * // => true
       *
       * _.has(object, 'a.b');
       * // => true
       *
       * _.has(object, ['a', 'b']);
       * // => true
       *
       * _.has(other, 'a');
       * // => false
       */
      function has(object, path) {
        return object != null && hasPath(object, path, baseHas);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$8 = Math.max,
        nativeMin$5 = Math.min;

      /**
       * The base implementation of `_.inRange` which doesn't coerce arguments.
       *
       * @private
       * @param {number} number The number to check.
       * @param {number} start The start of the range.
       * @param {number} end The end of the range.
       * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
       */
      function baseInRange(number, start, end) {
        return number >= nativeMin$5(start, end) && number < nativeMax$8(start, end);
      }

      /**
       * Checks if `n` is between `start` and up to, but not including, `end`. If
       * `end` is not specified, it's set to `start` with `start` then set to `0`.
       * If `start` is greater than `end` the params are swapped to support
       * negative ranges.
       *
       * @static
       * @memberOf _
       * @since 3.3.0
       * @category Number
       * @param {number} number The number to check.
       * @param {number} [start=0] The start of the range.
       * @param {number} end The end of the range.
       * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
       * @see _.range, _.rangeRight
       * @example
       *
       * _.inRange(3, 2, 4);
       * // => true
       *
       * _.inRange(4, 8);
       * // => true
       *
       * _.inRange(4, 2);
       * // => false
       *
       * _.inRange(2, 2);
       * // => false
       *
       * _.inRange(1.2, 2);
       * // => true
       *
       * _.inRange(5.2, 4);
       * // => false
       *
       * _.inRange(-3, -2, -6);
       * // => true
       */
      function inRange(number, start, end) {
        start = toFinite(start);
        if (end === undefined) {
          end = start;
          start = 0;
        } else {
          end = toFinite(end);
        }
        number = toNumber(number);
        return baseInRange(number, start, end);
      }

      /** `Object#toString` result references. */
      var stringTag$4 = '[object String]';

      /**
       * Checks if `value` is classified as a `String` primitive or object.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a string, else `false`.
       * @example
       *
       * _.isString('abc');
       * // => true
       *
       * _.isString(1);
       * // => false
       */
      function isString(value) {
        return typeof value == 'string' || !isArray$1(value) && isObjectLike(value) && baseGetTag(value) == stringTag$4;
      }

      /**
       * The base implementation of `_.values` and `_.valuesIn` which creates an
       * array of `object` property values corresponding to the property names
       * of `props`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array} props The property names to get values for.
       * @returns {Object} Returns the array of property values.
       */
      function baseValues(object, props) {
        return arrayMap(props, function (key) {
          return object[key];
        });
      }

      /**
       * Creates an array of the own enumerable string keyed property values of `object`.
       *
       * **Note:** Non-object values are coerced to objects.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property values.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.values(new Foo);
       * // => [1, 2] (iteration order is not guaranteed)
       *
       * _.values('hi');
       * // => ['h', 'i']
       */
      function values(object) {
        return object == null ? [] : baseValues(object, keys(object));
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$9 = Math.max;

      /**
       * Checks if `value` is in `collection`. If `collection` is a string, it's
       * checked for a substring of `value`, otherwise
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * is used for equality comparisons. If `fromIndex` is negative, it's used as
       * the offset from the end of `collection`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object|string} collection The collection to inspect.
       * @param {*} value The value to search for.
       * @param {number} [fromIndex=0] The index to search from.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
       * @returns {boolean} Returns `true` if `value` is found, else `false`.
       * @example
       *
       * _.includes([1, 2, 3], 1);
       * // => true
       *
       * _.includes([1, 2, 3], 1, 2);
       * // => false
       *
       * _.includes({ 'a': 1, 'b': 2 }, 1);
       * // => true
       *
       * _.includes('abcd', 'bc');
       * // => true
       */
      function includes(collection, value, fromIndex, guard) {
        collection = isArrayLike(collection) ? collection : values(collection);
        fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
        var length = collection.length;
        if (fromIndex < 0) {
          fromIndex = nativeMax$9(length + fromIndex, 0);
        }
        return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$a = Math.max;

      /**
       * Gets the index at which the first occurrence of `value` is found in `array`
       * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons. If `fromIndex` is negative, it's used as the
       * offset from the end of `array`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} [fromIndex=0] The index to search from.
       * @returns {number} Returns the index of the matched value, else `-1`.
       * @example
       *
       * _.indexOf([1, 2, 1, 2], 2);
       * // => 1
       *
       * // Search from the `fromIndex`.
       * _.indexOf([1, 2, 1, 2], 2, 2);
       * // => 3
       */
      function indexOf(array, value, fromIndex) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return -1;
        }
        var index = fromIndex == null ? 0 : toInteger(fromIndex);
        if (index < 0) {
          index = nativeMax$a(length + index, 0);
        }
        return baseIndexOf(array, value, index);
      }

      /**
       * Gets all but the last element of `array`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to query.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.initial([1, 2, 3]);
       * // => [1, 2]
       */
      function initial(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseSlice(array, 0, -1) : [];
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$6 = Math.min;

      /**
       * The base implementation of methods like `_.intersection`, without support
       * for iteratee shorthands, that accepts an array of arrays to inspect.
       *
       * @private
       * @param {Array} arrays The arrays to inspect.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of shared values.
       */
      function baseIntersection(arrays, iteratee, comparator) {
        var includes = comparator ? arrayIncludesWith : arrayIncludes,
          length = arrays[0].length,
          othLength = arrays.length,
          othIndex = othLength,
          caches = Array(othLength),
          maxLength = Infinity,
          result = [];
        while (othIndex--) {
          var array = arrays[othIndex];
          if (othIndex && iteratee) {
            array = arrayMap(array, baseUnary(iteratee));
          }
          maxLength = nativeMin$6(array.length, maxLength);
          caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined;
        }
        array = arrays[0];
        var index = -1,
          seen = caches[0];
        outer: while (++index < length && result.length < maxLength) {
          var value = array[index],
            computed = iteratee ? iteratee(value) : value;
          value = comparator || value !== 0 ? value : 0;
          if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator))) {
            othIndex = othLength;
            while (--othIndex) {
              var cache = caches[othIndex];
              if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) {
                continue outer;
              }
            }
            if (seen) {
              seen.push(computed);
            }
            result.push(value);
          }
        }
        return result;
      }

      /**
       * Casts `value` to an empty array if it's not an array like object.
       *
       * @private
       * @param {*} value The value to inspect.
       * @returns {Array|Object} Returns the cast array-like object.
       */
      function castArrayLikeObject(value) {
        return isArrayLikeObject(value) ? value : [];
      }

      /**
       * Creates an array of unique values that are included in all given arrays
       * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons. The order and references of result values are
       * determined by the first array.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @returns {Array} Returns the new array of intersecting values.
       * @example
       *
       * _.intersection([2, 1], [2, 3]);
       * // => [2]
       */
      var intersection = baseRest(function (arrays) {
        var mapped = arrayMap(arrays, castArrayLikeObject);
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [];
      });

      /**
       * This method is like `_.intersection` except that it accepts `iteratee`
       * which is invoked for each element of each `arrays` to generate the criterion
       * by which they're compared. The order and references of result values are
       * determined by the first array. The iteratee is invoked with one argument:
       * (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns the new array of intersecting values.
       * @example
       *
       * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
       * // => [2.1]
       *
       * // The `_.property` iteratee shorthand.
       * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
       * // => [{ 'x': 1 }]
       */
      var intersectionBy = baseRest(function (arrays) {
        var iteratee = last(arrays),
          mapped = arrayMap(arrays, castArrayLikeObject);
        if (iteratee === last(mapped)) {
          iteratee = undefined;
        } else {
          mapped.pop();
        }
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, baseIteratee(iteratee)) : [];
      });

      /**
       * This method is like `_.intersection` except that it accepts `comparator`
       * which is invoked to compare elements of `arrays`. The order and references
       * of result values are determined by the first array. The comparator is
       * invoked with two arguments: (arrVal, othVal).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of intersecting values.
       * @example
       *
       * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
       * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
       *
       * _.intersectionWith(objects, others, _.isEqual);
       * // => [{ 'x': 1, 'y': 2 }]
       */
      var intersectionWith = baseRest(function (arrays) {
        var comparator = last(arrays),
          mapped = arrayMap(arrays, castArrayLikeObject);
        comparator = typeof comparator == 'function' ? comparator : undefined;
        if (comparator) {
          mapped.pop();
        }
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : [];
      });

      /**
       * The base implementation of `_.invert` and `_.invertBy` which inverts
       * `object` with values transformed by `iteratee` and set by `setter`.
       *
       * @private
       * @param {Object} object The object to iterate over.
       * @param {Function} setter The function to set `accumulator` values.
       * @param {Function} iteratee The iteratee to transform values.
       * @param {Object} accumulator The initial inverted object.
       * @returns {Function} Returns `accumulator`.
       */
      function baseInverter(object, setter, iteratee, accumulator) {
        baseForOwn(object, function (value, key, object) {
          setter(accumulator, iteratee(value), key, object);
        });
        return accumulator;
      }

      /**
       * Creates a function like `_.invertBy`.
       *
       * @private
       * @param {Function} setter The function to set accumulator values.
       * @param {Function} toIteratee The function to resolve iteratees.
       * @returns {Function} Returns the new inverter function.
       */
      function createInverter(setter, toIteratee) {
        return function (object, iteratee) {
          return baseInverter(object, setter, toIteratee(iteratee), {});
        };
      }

      /** Used for built-in method references. */
      var objectProto$n = Object.prototype;

      /**
       * Used to resolve the
       * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
       * of values.
       */
      var nativeObjectToString$2 = objectProto$n.toString;

      /**
       * Creates an object composed of the inverted keys and values of `object`.
       * If `object` contains duplicate values, subsequent values overwrite
       * property assignments of previous values.
       *
       * @static
       * @memberOf _
       * @since 0.7.0
       * @category Object
       * @param {Object} object The object to invert.
       * @returns {Object} Returns the new inverted object.
       * @example
       *
       * var object = { 'a': 1, 'b': 2, 'c': 1 };
       *
       * _.invert(object);
       * // => { '1': 'c', '2': 'b' }
       */
      var invert = createInverter(function (result, value, key) {
        if (value != null && typeof value.toString != 'function') {
          value = nativeObjectToString$2.call(value);
        }
        result[value] = key;
      }, constant(identity));

      /** Used for built-in method references. */
      var objectProto$o = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$k = objectProto$o.hasOwnProperty;

      /**
       * Used to resolve the
       * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
       * of values.
       */
      var nativeObjectToString$3 = objectProto$o.toString;

      /**
       * This method is like `_.invert` except that the inverted object is generated
       * from the results of running each element of `object` thru `iteratee`. The
       * corresponding inverted value of each inverted key is an array of keys
       * responsible for generating the inverted value. The iteratee is invoked
       * with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.1.0
       * @category Object
       * @param {Object} object The object to invert.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Object} Returns the new inverted object.
       * @example
       *
       * var object = { 'a': 1, 'b': 2, 'c': 1 };
       *
       * _.invertBy(object);
       * // => { '1': ['a', 'c'], '2': ['b'] }
       *
       * _.invertBy(object, function(value) {
       *   return 'group' + value;
       * });
       * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
       */
      var invertBy = createInverter(function (result, value, key) {
        if (value != null && typeof value.toString != 'function') {
          value = nativeObjectToString$3.call(value);
        }
        if (hasOwnProperty$k.call(result, value)) {
          result[value].push(key);
        } else {
          result[value] = [key];
        }
      }, baseIteratee);

      /**
       * Gets the parent value at `path` of `object`.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array} path The path to get the parent value of.
       * @returns {*} Returns the parent value.
       */
      function parent$1(object, path) {
        return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
      }

      /**
       * The base implementation of `_.invoke` without support for individual
       * method arguments.
       *
       * @private
       * @param {Object} object The object to query.
       * @param {Array|string} path The path of the method to invoke.
       * @param {Array} args The arguments to invoke the method with.
       * @returns {*} Returns the result of the invoked method.
       */
      function baseInvoke(object, path, args) {
        path = castPath(path, object);
        object = parent$1(object, path);
        var func = object == null ? object : object[toKey(last(path))];
        return func == null ? undefined : apply(func, object, args);
      }

      /**
       * Invokes the method at `path` of `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The object to query.
       * @param {Array|string} path The path of the method to invoke.
       * @param {...*} [args] The arguments to invoke the method with.
       * @returns {*} Returns the result of the invoked method.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
       *
       * _.invoke(object, 'a[0].b.c.slice', 1, 3);
       * // => [2, 3]
       */
      var invoke = baseRest(baseInvoke);

      /**
       * Invokes the method at `path` of each element in `collection`, returning
       * an array of the results of each invoked method. Any additional arguments
       * are provided to each invoked method. If `path` is a function, it's invoked
       * for, and `this` bound to, each element in `collection`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Array|Function|string} path The path of the method to invoke or
       *  the function invoked per iteration.
       * @param {...*} [args] The arguments to invoke each method with.
       * @returns {Array} Returns the array of results.
       * @example
       *
       * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
       * // => [[1, 5, 7], [1, 2, 3]]
       *
       * _.invokeMap([123, 456], String.prototype.split, '');
       * // => [['1', '2', '3'], ['4', '5', '6']]
       */
      var invokeMap = baseRest(function (collection, path, args) {
        var index = -1,
          isFunc = typeof path == 'function',
          result = isArrayLike(collection) ? Array(collection.length) : [];
        baseEach(collection, function (value) {
          result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
        });
        return result;
      });
      var arrayBufferTag$4 = '[object ArrayBuffer]';

      /**
       * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
       */
      function baseIsArrayBuffer(value) {
        return isObjectLike(value) && baseGetTag(value) == arrayBufferTag$4;
      }

      /* Node.js helper references. */
      var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer;

      /**
       * Checks if `value` is classified as an `ArrayBuffer` object.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
       * @example
       *
       * _.isArrayBuffer(new ArrayBuffer(2));
       * // => true
       *
       * _.isArrayBuffer(new Array(2));
       * // => false
       */
      var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;

      /** `Object#toString` result references. */
      var boolTag$4 = '[object Boolean]';

      /**
       * Checks if `value` is classified as a boolean primitive or object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
       * @example
       *
       * _.isBoolean(false);
       * // => true
       *
       * _.isBoolean(null);
       * // => false
       */
      function isBoolean(value) {
        return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag$4;
      }

      /** `Object#toString` result references. */
      var dateTag$4 = '[object Date]';

      /**
       * The base implementation of `_.isDate` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
       */
      function baseIsDate(value) {
        return isObjectLike(value) && baseGetTag(value) == dateTag$4;
      }

      /* Node.js helper references. */
      var nodeIsDate = nodeUtil && nodeUtil.isDate;

      /**
       * Checks if `value` is classified as a `Date` object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
       * @example
       *
       * _.isDate(new Date);
       * // => true
       *
       * _.isDate('Mon April 23 2012');
       * // => false
       */
      var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;

      /**
       * Checks if `value` is likely a DOM element.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
       * @example
       *
       * _.isElement(document.body);
       * // => true
       *
       * _.isElement('<body>');
       * // => false
       */
      function isElement(value) {
        return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
      }

      /** `Object#toString` result references. */
      var mapTag$7 = '[object Map]',
        setTag$7 = '[object Set]';

      /** Used for built-in method references. */
      var objectProto$p = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$l = objectProto$p.hasOwnProperty;

      /**
       * Checks if `value` is an empty object, collection, map, or set.
       *
       * Objects are considered empty if they have no own enumerable string keyed
       * properties.
       *
       * Array-like values such as `arguments` objects, arrays, buffers, strings, or
       * jQuery-like collections are considered empty if they have a `length` of `0`.
       * Similarly, maps and sets are considered empty if they have a `size` of `0`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is empty, else `false`.
       * @example
       *
       * _.isEmpty(null);
       * // => true
       *
       * _.isEmpty(true);
       * // => true
       *
       * _.isEmpty(1);
       * // => true
       *
       * _.isEmpty([1, 2, 3]);
       * // => false
       *
       * _.isEmpty({ 'a': 1 });
       * // => false
       */
      function isEmpty(value) {
        if (value == null) {
          return true;
        }
        if (isArrayLike(value) && (isArray$1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
          return !value.length;
        }
        var tag = getTag$1(value);
        if (tag == mapTag$7 || tag == setTag$7) {
          return !value.size;
        }
        if (isPrototype(value)) {
          return !baseKeys(value).length;
        }
        for (var key in value) {
          if (hasOwnProperty$l.call(value, key)) {
            return false;
          }
        }
        return true;
      }

      /**
       * Performs a deep comparison between two values to determine if they are
       * equivalent.
       *
       * **Note:** This method supports comparing arrays, array buffers, booleans,
       * date objects, error objects, maps, numbers, `Object` objects, regexes,
       * sets, strings, symbols, and typed arrays. `Object` objects are compared
       * by their own, not inherited, enumerable properties. Functions and DOM
       * nodes are compared by strict equality, i.e. `===`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
       * @example
       *
       * var object = { 'a': 1 };
       * var other = { 'a': 1 };
       *
       * _.isEqual(object, other);
       * // => true
       *
       * object === other;
       * // => false
       */
      function isEqual(value, other) {
        return baseIsEqual(value, other);
      }

      /**
       * This method is like `_.isEqual` except that it accepts `customizer` which
       * is invoked to compare values. If `customizer` returns `undefined`, comparisons
       * are handled by the method instead. The `customizer` is invoked with up to
       * six arguments: (objValue, othValue [, index|key, object, other, stack]).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @param {Function} [customizer] The function to customize comparisons.
       * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
       * @example
       *
       * function isGreeting(value) {
       *   return /^h(?:i|ello)$/.test(value);
       * }
       *
       * function customizer(objValue, othValue) {
       *   if (isGreeting(objValue) && isGreeting(othValue)) {
       *     return true;
       *   }
       * }
       *
       * var array = ['hello', 'goodbye'];
       * var other = ['hi', 'goodbye'];
       *
       * _.isEqualWith(array, other, customizer);
       * // => true
       */
      function isEqualWith(value, other, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        var result = customizer ? customizer(value, other) : undefined;
        return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeIsFinite$1 = root.isFinite;

      /**
       * Checks if `value` is a finite primitive number.
       *
       * **Note:** This method is based on
       * [`Number.isFinite`](https://mdn.io/Number/isFinite).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
       * @example
       *
       * _.isFinite(3);
       * // => true
       *
       * _.isFinite(Number.MIN_VALUE);
       * // => true
       *
       * _.isFinite(Infinity);
       * // => false
       *
       * _.isFinite('3');
       * // => false
       */
      function isFinite$1(value) {
        return typeof value == 'number' && nativeIsFinite$1(value);
      }

      /**
       * Checks if `value` is an integer.
       *
       * **Note:** This method is based on
       * [`Number.isInteger`](https://mdn.io/Number/isInteger).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
       * @example
       *
       * _.isInteger(3);
       * // => true
       *
       * _.isInteger(Number.MIN_VALUE);
       * // => false
       *
       * _.isInteger(Infinity);
       * // => false
       *
       * _.isInteger('3');
       * // => false
       */
      function isInteger(value) {
        return typeof value == 'number' && value == toInteger(value);
      }

      /**
       * Performs a partial deep comparison between `object` and `source` to
       * determine if `object` contains equivalent property values.
       *
       * **Note:** This method is equivalent to `_.matches` when `source` is
       * partially applied.
       *
       * Partial comparisons will match empty array and empty object `source`
       * values against any array or object value, respectively. See `_.isEqual`
       * for a list of supported value comparisons.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Lang
       * @param {Object} object The object to inspect.
       * @param {Object} source The object of property values to match.
       * @returns {boolean} Returns `true` if `object` is a match, else `false`.
       * @example
       *
       * var object = { 'a': 1, 'b': 2 };
       *
       * _.isMatch(object, { 'b': 2 });
       * // => true
       *
       * _.isMatch(object, { 'b': 1 });
       * // => false
       */
      function isMatch(object, source) {
        return object === source || baseIsMatch(object, source, getMatchData(source));
      }

      /**
       * This method is like `_.isMatch` except that it accepts `customizer` which
       * is invoked to compare values. If `customizer` returns `undefined`, comparisons
       * are handled by the method instead. The `customizer` is invoked with five
       * arguments: (objValue, srcValue, index|key, object, source).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {Object} object The object to inspect.
       * @param {Object} source The object of property values to match.
       * @param {Function} [customizer] The function to customize comparisons.
       * @returns {boolean} Returns `true` if `object` is a match, else `false`.
       * @example
       *
       * function isGreeting(value) {
       *   return /^h(?:i|ello)$/.test(value);
       * }
       *
       * function customizer(objValue, srcValue) {
       *   if (isGreeting(objValue) && isGreeting(srcValue)) {
       *     return true;
       *   }
       * }
       *
       * var object = { 'greeting': 'hello' };
       * var source = { 'greeting': 'hi' };
       *
       * _.isMatchWith(object, source, customizer);
       * // => true
       */
      function isMatchWith(object, source, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        return baseIsMatch(object, source, getMatchData(source), customizer);
      }

      /** `Object#toString` result references. */
      var numberTag$4 = '[object Number]';

      /**
       * Checks if `value` is classified as a `Number` primitive or object.
       *
       * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
       * classified as numbers, use the `_.isFinite` method.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a number, else `false`.
       * @example
       *
       * _.isNumber(3);
       * // => true
       *
       * _.isNumber(Number.MIN_VALUE);
       * // => true
       *
       * _.isNumber(Infinity);
       * // => true
       *
       * _.isNumber('3');
       * // => false
       */
      function isNumber(value) {
        return typeof value == 'number' || isObjectLike(value) && baseGetTag(value) == numberTag$4;
      }

      /**
       * Checks if `value` is `NaN`.
       *
       * **Note:** This method is based on
       * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
       * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
       * `undefined` and other non-number values.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
       * @example
       *
       * _.isNaN(NaN);
       * // => true
       *
       * _.isNaN(new Number(NaN));
       * // => true
       *
       * isNaN(undefined);
       * // => true
       *
       * _.isNaN(undefined);
       * // => false
       */
      function isNaN(value) {
        // An `NaN` primitive is the only value that is not equal to itself.
        // Perform the `toStringTag` check first to avoid errors with some
        // ActiveX objects in IE.
        return isNumber(value) && value != +value;
      }

      /**
       * Checks if `func` is capable of being masked.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
       */
      var isMaskable = coreJsData ? isFunction : stubFalse;

      /** Error message constants. */
      var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.';

      /**
       * Checks if `value` is a pristine native function.
       *
       * **Note:** This method can't reliably detect native functions in the presence
       * of the core-js package because core-js circumvents this kind of detection.
       * Despite multiple requests, the core-js maintainer has made it clear: any
       * attempt to fix the detection will be obstructed. As a result, we're left
       * with little choice but to throw an error. Unfortunately, this also affects
       * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
       * which rely on core-js.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a native function,
       *  else `false`.
       * @example
       *
       * _.isNative(Array.prototype.push);
       * // => true
       *
       * _.isNative(_);
       * // => false
       */
      function isNative(value) {
        if (isMaskable(value)) {
          throw new Error(CORE_ERROR_TEXT);
        }
        return baseIsNative(value);
      }

      /**
       * Checks if `value` is `null` or `undefined`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
       * @example
       *
       * _.isNil(null);
       * // => true
       *
       * _.isNil(void 0);
       * // => true
       *
       * _.isNil(NaN);
       * // => false
       */
      function isNil(value) {
        return value == null;
      }

      /**
       * Checks if `value` is `null`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
       * @example
       *
       * _.isNull(null);
       * // => true
       *
       * _.isNull(void 0);
       * // => false
       */
      function isNull(value) {
        return value === null;
      }

      /** `Object#toString` result references. */
      var regexpTag$4 = '[object RegExp]';

      /**
       * The base implementation of `_.isRegExp` without Node.js optimizations.
       *
       * @private
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
       */
      function baseIsRegExp(value) {
        return isObjectLike(value) && baseGetTag(value) == regexpTag$4;
      }

      /* Node.js helper references. */
      var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;

      /**
       * Checks if `value` is classified as a `RegExp` object.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
       * @example
       *
       * _.isRegExp(/abc/);
       * // => true
       *
       * _.isRegExp('/abc/');
       * // => false
       */
      var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER$2 = 9007199254740991;

      /**
       * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
       * double precision number which isn't the result of a rounded unsafe integer.
       *
       * **Note:** This method is based on
       * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
       * @example
       *
       * _.isSafeInteger(3);
       * // => true
       *
       * _.isSafeInteger(Number.MIN_VALUE);
       * // => false
       *
       * _.isSafeInteger(Infinity);
       * // => false
       *
       * _.isSafeInteger('3');
       * // => false
       */
      function isSafeInteger(value) {
        return isInteger(value) && value >= -MAX_SAFE_INTEGER$2 && value <= MAX_SAFE_INTEGER$2;
      }

      /**
       * Checks if `value` is `undefined`.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
       * @example
       *
       * _.isUndefined(void 0);
       * // => true
       *
       * _.isUndefined(null);
       * // => false
       */
      function isUndefined(value) {
        return value === undefined;
      }

      /** `Object#toString` result references. */
      var weakMapTag$3 = '[object WeakMap]';

      /**
       * Checks if `value` is classified as a `WeakMap` object.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
       * @example
       *
       * _.isWeakMap(new WeakMap);
       * // => true
       *
       * _.isWeakMap(new Map);
       * // => false
       */
      function isWeakMap(value) {
        return isObjectLike(value) && getTag$1(value) == weakMapTag$3;
      }

      /** `Object#toString` result references. */
      var weakSetTag = '[object WeakSet]';

      /**
       * Checks if `value` is classified as a `WeakSet` object.
       *
       * @static
       * @memberOf _
       * @since 4.3.0
       * @category Lang
       * @param {*} value The value to check.
       * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
       * @example
       *
       * _.isWeakSet(new WeakSet);
       * // => true
       *
       * _.isWeakSet(new Set);
       * // => false
       */
      function isWeakSet(value) {
        return isObjectLike(value) && baseGetTag(value) == weakSetTag;
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$4 = 1;

      /**
       * Creates a function that invokes `func` with the arguments of the created
       * function. If `func` is a property name, the created function returns the
       * property value for a given element. If `func` is an array or object, the
       * created function returns `true` for elements that contain the equivalent
       * source properties, otherwise it returns `false`.
       *
       * @static
       * @since 4.0.0
       * @memberOf _
       * @category Util
       * @param {*} [func=_.identity] The value to convert to a callback.
       * @returns {Function} Returns the callback.
       * @example
       *
       * var users = [
       *   { 'user': 'barney', 'age': 36, 'active': true },
       *   { 'user': 'fred',   'age': 40, 'active': false }
       * ];
       *
       * // The `_.matches` iteratee shorthand.
       * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
       * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.filter(users, _.iteratee(['user', 'fred']));
       * // => [{ 'user': 'fred', 'age': 40 }]
       *
       * // The `_.property` iteratee shorthand.
       * _.map(users, _.iteratee('user'));
       * // => ['barney', 'fred']
       *
       * // Create custom iteratee shorthands.
       * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
       *   return !_.isRegExp(func) ? iteratee(func) : function(string) {
       *     return func.test(string);
       *   };
       * });
       *
       * _.filter(['abc', 'def'], /ef/);
       * // => ['def']
       */
      function iteratee(func) {
        return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG$4));
      }

      /** Used for built-in method references. */
      var arrayProto$1 = Array.prototype;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeJoin = arrayProto$1.join;

      /**
       * Converts all elements in `array` into a string separated by `separator`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to convert.
       * @param {string} [separator=','] The element separator.
       * @returns {string} Returns the joined string.
       * @example
       *
       * _.join(['a', 'b', 'c'], '~');
       * // => 'a~b~c'
       */
      function join(array, separator) {
        return array == null ? '' : nativeJoin.call(array, separator);
      }

      /**
       * Converts `string` to
       * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the kebab cased string.
       * @example
       *
       * _.kebabCase('Foo Bar');
       * // => 'foo-bar'
       *
       * _.kebabCase('fooBar');
       * // => 'foo-bar'
       *
       * _.kebabCase('__FOO_BAR__');
       * // => 'foo-bar'
       */
      var kebabCase = createCompounder(function (result, word, index) {
        return result + (index ? '-' : '') + word.toLowerCase();
      });

      /**
       * Creates an object composed of keys generated from the results of running
       * each element of `collection` thru `iteratee`. The corresponding value of
       * each key is the last element responsible for generating the key. The
       * iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
       * @returns {Object} Returns the composed aggregate object.
       * @example
       *
       * var array = [
       *   { 'dir': 'left', 'code': 97 },
       *   { 'dir': 'right', 'code': 100 }
       * ];
       *
       * _.keyBy(array, function(o) {
       *   return String.fromCharCode(o.code);
       * });
       * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
       *
       * _.keyBy(array, 'dir');
       * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
       */
      var keyBy = createAggregator(function (result, value, key) {
        baseAssignValue(result, key, value);
      });

      /**
       * A specialized version of `_.lastIndexOf` which performs strict equality
       * comparisons of values, i.e. `===`.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} fromIndex The index to search from.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function strictLastIndexOf(array, value, fromIndex) {
        var index = fromIndex + 1;
        while (index--) {
          if (array[index] === value) {
            return index;
          }
        }
        return index;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$b = Math.max,
        nativeMin$7 = Math.min;

      /**
       * This method is like `_.indexOf` except that it iterates over elements of
       * `array` from right to left.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} [fromIndex=array.length-1] The index to search from.
       * @returns {number} Returns the index of the matched value, else `-1`.
       * @example
       *
       * _.lastIndexOf([1, 2, 1, 2], 2);
       * // => 3
       *
       * // Search from the `fromIndex`.
       * _.lastIndexOf([1, 2, 1, 2], 2, 2);
       * // => 1
       */
      function lastIndexOf(array, value, fromIndex) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return -1;
        }
        var index = length;
        if (fromIndex !== undefined) {
          index = toInteger(fromIndex);
          index = index < 0 ? nativeMax$b(length + index, 0) : nativeMin$7(index, length - 1);
        }
        return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true);
      }

      /**
       * Converts `string`, as space separated words, to lower case.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the lower cased string.
       * @example
       *
       * _.lowerCase('--Foo-Bar--');
       * // => 'foo bar'
       *
       * _.lowerCase('fooBar');
       * // => 'foo bar'
       *
       * _.lowerCase('__FOO_BAR__');
       * // => 'foo bar'
       */
      var lowerCase = createCompounder(function (result, word, index) {
        return result + (index ? ' ' : '') + word.toLowerCase();
      });

      /**
       * Converts the first character of `string` to lower case.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the converted string.
       * @example
       *
       * _.lowerFirst('Fred');
       * // => 'fred'
       *
       * _.lowerFirst('FRED');
       * // => 'fRED'
       */
      var lowerFirst = createCaseFirst('toLowerCase');

      /**
       * The base implementation of `_.lt` which doesn't coerce arguments.
       *
       * @private
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is less than `other`,
       *  else `false`.
       */
      function baseLt(value, other) {
        return value < other;
      }

      /**
       * Checks if `value` is less than `other`.
       *
       * @static
       * @memberOf _
       * @since 3.9.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is less than `other`,
       *  else `false`.
       * @see _.gt
       * @example
       *
       * _.lt(1, 3);
       * // => true
       *
       * _.lt(3, 3);
       * // => false
       *
       * _.lt(3, 1);
       * // => false
       */
      var lt = createRelationalOperation(baseLt);

      /**
       * Checks if `value` is less than or equal to `other`.
       *
       * @static
       * @memberOf _
       * @since 3.9.0
       * @category Lang
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {boolean} Returns `true` if `value` is less than or equal to
       *  `other`, else `false`.
       * @see _.gte
       * @example
       *
       * _.lte(1, 3);
       * // => true
       *
       * _.lte(3, 3);
       * // => true
       *
       * _.lte(3, 1);
       * // => false
       */
      var lte = createRelationalOperation(function (value, other) {
        return value <= other;
      });

      /**
       * The opposite of `_.mapValues`; this method creates an object with the
       * same values as `object` and keys generated by running each own enumerable
       * string keyed property of `object` thru `iteratee`. The iteratee is invoked
       * with three arguments: (value, key, object).
       *
       * @static
       * @memberOf _
       * @since 3.8.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns the new mapped object.
       * @see _.mapValues
       * @example
       *
       * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
       *   return key + value;
       * });
       * // => { 'a1': 1, 'b2': 2 }
       */
      function mapKeys(object, iteratee) {
        var result = {};
        iteratee = baseIteratee(iteratee);
        baseForOwn(object, function (value, key, object) {
          baseAssignValue(result, iteratee(value, key, object), value);
        });
        return result;
      }

      /**
       * Creates an object with the same keys as `object` and values generated
       * by running each own enumerable string keyed property of `object` thru
       * `iteratee`. The iteratee is invoked with three arguments:
       * (value, key, object).
       *
       * @static
       * @memberOf _
       * @since 2.4.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Object} Returns the new mapped object.
       * @see _.mapKeys
       * @example
       *
       * var users = {
       *   'fred':    { 'user': 'fred',    'age': 40 },
       *   'pebbles': { 'user': 'pebbles', 'age': 1 }
       * };
       *
       * _.mapValues(users, function(o) { return o.age; });
       * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
       *
       * // The `_.property` iteratee shorthand.
       * _.mapValues(users, 'age');
       * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
       */
      function mapValues$1(object, iteratee) {
        var result = {};
        iteratee = baseIteratee(iteratee);
        baseForOwn(object, function (value, key, object) {
          baseAssignValue(result, key, iteratee(value, key, object));
        });
        return result;
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$5 = 1;

      /**
       * Creates a function that performs a partial deep comparison between a given
       * object and `source`, returning `true` if the given object has equivalent
       * property values, else `false`.
       *
       * **Note:** The created function is equivalent to `_.isMatch` with `source`
       * partially applied.
       *
       * Partial comparisons will match empty array and empty object `source`
       * values against any array or object value, respectively. See `_.isEqual`
       * for a list of supported value comparisons.
       *
       * **Note:** Multiple values can be checked by combining several matchers
       * using `_.overSome`
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Util
       * @param {Object} source The object of property values to match.
       * @returns {Function} Returns the new spec function.
       * @example
       *
       * var objects = [
       *   { 'a': 1, 'b': 2, 'c': 3 },
       *   { 'a': 4, 'b': 5, 'c': 6 }
       * ];
       *
       * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
       * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
       *
       * // Checking for several possible values
       * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
       * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
       */
      function matches(source) {
        return baseMatches(baseClone(source, CLONE_DEEP_FLAG$5));
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$6 = 1;

      /**
       * Creates a function that performs a partial deep comparison between the
       * value at `path` of a given object to `srcValue`, returning `true` if the
       * object value is equivalent, else `false`.
       *
       * **Note:** Partial comparisons will match empty array and empty object
       * `srcValue` values against any array or object value, respectively. See
       * `_.isEqual` for a list of supported value comparisons.
       *
       * **Note:** Multiple values can be checked by combining several matchers
       * using `_.overSome`
       *
       * @static
       * @memberOf _
       * @since 3.2.0
       * @category Util
       * @param {Array|string} path The path of the property to get.
       * @param {*} srcValue The value to match.
       * @returns {Function} Returns the new spec function.
       * @example
       *
       * var objects = [
       *   { 'a': 1, 'b': 2, 'c': 3 },
       *   { 'a': 4, 'b': 5, 'c': 6 }
       * ];
       *
       * _.find(objects, _.matchesProperty('a', 4));
       * // => { 'a': 4, 'b': 5, 'c': 6 }
       *
       * // Checking for several possible values
       * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
       * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
       */
      function matchesProperty(path, srcValue) {
        return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG$6));
      }

      /**
       * The base implementation of methods like `_.max` and `_.min` which accepts a
       * `comparator` to determine the extremum value.
       *
       * @private
       * @param {Array} array The array to iterate over.
       * @param {Function} iteratee The iteratee invoked per iteration.
       * @param {Function} comparator The comparator used to compare values.
       * @returns {*} Returns the extremum value.
       */
      function baseExtremum(array, iteratee, comparator) {
        var index = -1,
          length = array.length;
        while (++index < length) {
          var value = array[index],
            current = iteratee(value);
          if (current != null && (computed === undefined ? current === current && !isSymbol(current) : comparator(current, computed))) {
            var computed = current,
              result = value;
          }
        }
        return result;
      }

      /**
       * Computes the maximum value of `array`. If `array` is empty or falsey,
       * `undefined` is returned.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Math
       * @param {Array} array The array to iterate over.
       * @returns {*} Returns the maximum value.
       * @example
       *
       * _.max([4, 2, 8, 6]);
       * // => 8
       *
       * _.max([]);
       * // => undefined
       */
      function max(array) {
        return array && array.length ? baseExtremum(array, identity, baseGt) : undefined;
      }

      /**
       * This method is like `_.max` except that it accepts `iteratee` which is
       * invoked for each element in `array` to generate the criterion by which
       * the value is ranked. The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {*} Returns the maximum value.
       * @example
       *
       * var objects = [{ 'n': 1 }, { 'n': 2 }];
       *
       * _.maxBy(objects, function(o) { return o.n; });
       * // => { 'n': 2 }
       *
       * // The `_.property` iteratee shorthand.
       * _.maxBy(objects, 'n');
       * // => { 'n': 2 }
       */
      function maxBy(array, iteratee) {
        return array && array.length ? baseExtremum(array, baseIteratee(iteratee), baseGt) : undefined;
      }

      /**
       * The base implementation of `_.sum` and `_.sumBy` without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {number} Returns the sum.
       */
      function baseSum(array, iteratee) {
        var result,
          index = -1,
          length = array.length;
        while (++index < length) {
          var current = iteratee(array[index]);
          if (current !== undefined) {
            result = result === undefined ? current : result + current;
          }
        }
        return result;
      }

      /** Used as references for various `Number` constants. */
      var NAN$2 = 0 / 0;

      /**
       * The base implementation of `_.mean` and `_.meanBy` without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @returns {number} Returns the mean.
       */
      function baseMean(array, iteratee) {
        var length = array == null ? 0 : array.length;
        return length ? baseSum(array, iteratee) / length : NAN$2;
      }

      /**
       * Computes the mean of the values in `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @returns {number} Returns the mean.
       * @example
       *
       * _.mean([4, 2, 8, 6]);
       * // => 5
       */
      function mean(array) {
        return baseMean(array, identity);
      }

      /**
       * This method is like `_.mean` except that it accepts `iteratee` which is
       * invoked for each element in `array` to generate the value to be averaged.
       * The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.7.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {number} Returns the mean.
       * @example
       *
       * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
       *
       * _.meanBy(objects, function(o) { return o.n; });
       * // => 5
       *
       * // The `_.property` iteratee shorthand.
       * _.meanBy(objects, 'n');
       * // => 5
       */
      function meanBy(array, iteratee) {
        return baseMean(array, baseIteratee(iteratee));
      }

      /**
       * This method is like `_.assign` except that it recursively merges own and
       * inherited enumerable string keyed properties of source objects into the
       * destination object. Source properties that resolve to `undefined` are
       * skipped if a destination value exists. Array and plain object properties
       * are merged recursively. Other objects and value types are overridden by
       * assignment. Source objects are applied from left to right. Subsequent
       * sources overwrite property assignments of previous sources.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 0.5.0
       * @category Object
       * @param {Object} object The destination object.
       * @param {...Object} [sources] The source objects.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var object = {
       *   'a': [{ 'b': 2 }, { 'd': 4 }]
       * };
       *
       * var other = {
       *   'a': [{ 'c': 3 }, { 'e': 5 }]
       * };
       *
       * _.merge(object, other);
       * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
       */
      var merge = createAssigner(function (object, source, srcIndex) {
        baseMerge(object, source, srcIndex);
      });

      /**
       * Creates a function that invokes the method at `path` of a given object.
       * Any additional arguments are provided to the invoked method.
       *
       * @static
       * @memberOf _
       * @since 3.7.0
       * @category Util
       * @param {Array|string} path The path of the method to invoke.
       * @param {...*} [args] The arguments to invoke the method with.
       * @returns {Function} Returns the new invoker function.
       * @example
       *
       * var objects = [
       *   { 'a': { 'b': _.constant(2) } },
       *   { 'a': { 'b': _.constant(1) } }
       * ];
       *
       * _.map(objects, _.method('a.b'));
       * // => [2, 1]
       *
       * _.map(objects, _.method(['a', 'b']));
       * // => [2, 1]
       */
      var method = baseRest(function (path, args) {
        return function (object) {
          return baseInvoke(object, path, args);
        };
      });

      /**
       * The opposite of `_.method`; this method creates a function that invokes
       * the method at a given path of `object`. Any additional arguments are
       * provided to the invoked method.
       *
       * @static
       * @memberOf _
       * @since 3.7.0
       * @category Util
       * @param {Object} object The object to query.
       * @param {...*} [args] The arguments to invoke the method with.
       * @returns {Function} Returns the new invoker function.
       * @example
       *
       * var array = _.times(3, _.constant),
       *     object = { 'a': array, 'b': array, 'c': array };
       *
       * _.map(['a[2]', 'c[0]'], _.methodOf(object));
       * // => [2, 0]
       *
       * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
       * // => [2, 0]
       */
      var methodOf = baseRest(function (object, args) {
        return function (path) {
          return baseInvoke(object, path, args);
        };
      });

      /**
       * Computes the minimum value of `array`. If `array` is empty or falsey,
       * `undefined` is returned.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Math
       * @param {Array} array The array to iterate over.
       * @returns {*} Returns the minimum value.
       * @example
       *
       * _.min([4, 2, 8, 6]);
       * // => 2
       *
       * _.min([]);
       * // => undefined
       */
      function min(array) {
        return array && array.length ? baseExtremum(array, identity, baseLt) : undefined;
      }

      /**
       * This method is like `_.min` except that it accepts `iteratee` which is
       * invoked for each element in `array` to generate the criterion by which
       * the value is ranked. The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {*} Returns the minimum value.
       * @example
       *
       * var objects = [{ 'n': 1 }, { 'n': 2 }];
       *
       * _.minBy(objects, function(o) { return o.n; });
       * // => { 'n': 1 }
       *
       * // The `_.property` iteratee shorthand.
       * _.minBy(objects, 'n');
       * // => { 'n': 1 }
       */
      function minBy(array, iteratee) {
        return array && array.length ? baseExtremum(array, baseIteratee(iteratee), baseLt) : undefined;
      }

      /**
       * Adds all own enumerable string keyed function properties of a source
       * object to the destination object. If `object` is a function, then methods
       * are added to its prototype as well.
       *
       * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
       * avoid conflicts caused by modifying the original.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {Function|Object} [object=lodash] The destination object.
       * @param {Object} source The object of functions to add.
       * @param {Object} [options={}] The options object.
       * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
       * @returns {Function|Object} Returns `object`.
       * @example
       *
       * function vowels(string) {
       *   return _.filter(string, function(v) {
       *     return /[aeiou]/i.test(v);
       *   });
       * }
       *
       * _.mixin({ 'vowels': vowels });
       * _.vowels('fred');
       * // => ['e']
       *
       * _('fred').vowels().value();
       * // => ['e']
       *
       * _.mixin({ 'vowels': vowels }, { 'chain': false });
       * _('fred').vowels();
       * // => ['e']
       */
      function mixin(object, source, options) {
        var props = keys(source),
          methodNames = baseFunctions(source, props);
        var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
          isFunc = isFunction(object);
        arrayEach(methodNames, function (methodName) {
          var func = source[methodName];
          object[methodName] = func;
          if (isFunc) {
            object.prototype[methodName] = function () {
              var chainAll = this.__chain__;
              if (chain || chainAll) {
                var result = object(this.__wrapped__),
                  actions = result.__actions__ = copyArray(this.__actions__);
                actions.push({
                  'func': func,
                  'args': arguments,
                  'thisArg': object
                });
                result.__chain__ = chainAll;
                return result;
              }
              return func.apply(object, arrayPush([this.value()], arguments));
            };
          }
        });
        return object;
      }

      /**
       * Multiply two numbers.
       *
       * @static
       * @memberOf _
       * @since 4.7.0
       * @category Math
       * @param {number} multiplier The first number in a multiplication.
       * @param {number} multiplicand The second number in a multiplication.
       * @returns {number} Returns the product.
       * @example
       *
       * _.multiply(6, 4);
       * // => 24
       */
      var multiply = createMathOperation(function (multiplier, multiplicand) {
        return multiplier * multiplicand;
      }, 1);

      /** Error message constants. */
      var FUNC_ERROR_TEXT$8 = 'Expected a function';

      /**
       * Creates a function that negates the result of the predicate `func`. The
       * `func` predicate is invoked with the `this` binding and arguments of the
       * created function.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Function
       * @param {Function} predicate The predicate to negate.
       * @returns {Function} Returns the new negated function.
       * @example
       *
       * function isEven(n) {
       *   return n % 2 == 0;
       * }
       *
       * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
       * // => [1, 3, 5]
       */
      function negate(predicate) {
        if (typeof predicate != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$8);
        }
        return function () {
          var args = arguments;
          switch (args.length) {
            case 0:
              return !predicate.call(this);
            case 1:
              return !predicate.call(this, args[0]);
            case 2:
              return !predicate.call(this, args[0], args[1]);
            case 3:
              return !predicate.call(this, args[0], args[1], args[2]);
          }
          return !predicate.apply(this, args);
        };
      }

      /**
       * Converts `iterator` to an array.
       *
       * @private
       * @param {Object} iterator The iterator to convert.
       * @returns {Array} Returns the converted array.
       */
      function iteratorToArray(iterator) {
        var data,
          result = [];
        while (!(data = iterator.next()).done) {
          result.push(data.value);
        }
        return result;
      }

      /** `Object#toString` result references. */
      var mapTag$8 = '[object Map]',
        setTag$8 = '[object Set]';

      /** Built-in value references. */
      var symIterator = Symbol$1 ? Symbol$1.iterator : undefined;

      /**
       * Converts `value` to an array.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {Array} Returns the converted array.
       * @example
       *
       * _.toArray({ 'a': 1, 'b': 2 });
       * // => [1, 2]
       *
       * _.toArray('abc');
       * // => ['a', 'b', 'c']
       *
       * _.toArray(1);
       * // => []
       *
       * _.toArray(null);
       * // => []
       */
      function toArray$1(value) {
        if (!value) {
          return [];
        }
        if (isArrayLike(value)) {
          return isString(value) ? stringToArray(value) : copyArray(value);
        }
        if (symIterator && value[symIterator]) {
          return iteratorToArray(value[symIterator]());
        }
        var tag = getTag$1(value),
          func = tag == mapTag$8 ? mapToArray : tag == setTag$8 ? setToArray : values;
        return func(value);
      }

      /**
       * Gets the next value on a wrapped object following the
       * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
       *
       * @name next
       * @memberOf _
       * @since 4.0.0
       * @category Seq
       * @returns {Object} Returns the next iterator value.
       * @example
       *
       * var wrapped = _([1, 2]);
       *
       * wrapped.next();
       * // => { 'done': false, 'value': 1 }
       *
       * wrapped.next();
       * // => { 'done': false, 'value': 2 }
       *
       * wrapped.next();
       * // => { 'done': true, 'value': undefined }
       */
      function wrapperNext() {
        if (this.__values__ === undefined) {
          this.__values__ = toArray$1(this.value());
        }
        var done = this.__index__ >= this.__values__.length,
          value = done ? undefined : this.__values__[this.__index__++];
        return {
          'done': done,
          'value': value
        };
      }

      /**
       * The base implementation of `_.nth` which doesn't coerce arguments.
       *
       * @private
       * @param {Array} array The array to query.
       * @param {number} n The index of the element to return.
       * @returns {*} Returns the nth element of `array`.
       */
      function baseNth(array, n) {
        var length = array.length;
        if (!length) {
          return;
        }
        n += n < 0 ? length : 0;
        return isIndex(n, length) ? array[n] : undefined;
      }

      /**
       * Gets the element at index `n` of `array`. If `n` is negative, the nth
       * element from the end is returned.
       *
       * @static
       * @memberOf _
       * @since 4.11.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {number} [n=0] The index of the element to return.
       * @returns {*} Returns the nth element of `array`.
       * @example
       *
       * var array = ['a', 'b', 'c', 'd'];
       *
       * _.nth(array, 1);
       * // => 'b'
       *
       * _.nth(array, -2);
       * // => 'c';
       */
      function nth(array, n) {
        return array && array.length ? baseNth(array, toInteger(n)) : undefined;
      }

      /**
       * Creates a function that gets the argument at index `n`. If `n` is negative,
       * the nth argument from the end is returned.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {number} [n=0] The index of the argument to return.
       * @returns {Function} Returns the new pass-thru function.
       * @example
       *
       * var func = _.nthArg(1);
       * func('a', 'b', 'c', 'd');
       * // => 'b'
       *
       * var func = _.nthArg(-2);
       * func('a', 'b', 'c', 'd');
       * // => 'c'
       */
      function nthArg(n) {
        n = toInteger(n);
        return baseRest(function (args) {
          return baseNth(args, n);
        });
      }

      /**
       * The base implementation of `_.unset`.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {Array|string} path The property path to unset.
       * @returns {boolean} Returns `true` if the property is deleted, else `false`.
       */
      function baseUnset(object, path) {
        path = castPath(path, object);
        object = parent$1(object, path);
        return object == null || delete object[toKey(last(path))];
      }

      /**
       * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
       * objects.
       *
       * @private
       * @param {*} value The value to inspect.
       * @param {string} key The key of the property to inspect.
       * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
       */
      function customOmitClone(value) {
        return isPlainObject(value) ? undefined : value;
      }

      /** Used to compose bitmasks for cloning. */
      var CLONE_DEEP_FLAG$7 = 1,
        CLONE_FLAT_FLAG$1 = 2,
        CLONE_SYMBOLS_FLAG$5 = 4;

      /**
       * The opposite of `_.pick`; this method creates an object composed of the
       * own and inherited enumerable property paths of `object` that are not omitted.
       *
       * **Note:** This method is considerably slower than `_.pick`.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The source object.
       * @param {...(string|string[])} [paths] The property paths to omit.
       * @returns {Object} Returns the new object.
       * @example
       *
       * var object = { 'a': 1, 'b': '2', 'c': 3 };
       *
       * _.omit(object, ['a', 'c']);
       * // => { 'b': '2' }
       */
      var omit = flatRest(function (object, paths) {
        var result = {};
        if (object == null) {
          return result;
        }
        var isDeep = false;
        paths = arrayMap(paths, function (path) {
          path = castPath(path, object);
          isDeep || (isDeep = path.length > 1);
          return path;
        });
        copyObject(object, getAllKeysIn(object), result);
        if (isDeep) {
          result = baseClone(result, CLONE_DEEP_FLAG$7 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$5, customOmitClone);
        }
        var length = paths.length;
        while (length--) {
          baseUnset(result, paths[length]);
        }
        return result;
      });

      /**
       * The base implementation of `_.set`.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to set.
       * @param {*} value The value to set.
       * @param {Function} [customizer] The function to customize path creation.
       * @returns {Object} Returns `object`.
       */
      function baseSet(object, path, value, customizer) {
        if (!isObject(object)) {
          return object;
        }
        path = castPath(path, object);
        var index = -1,
          length = path.length,
          lastIndex = length - 1,
          nested = object;
        while (nested != null && ++index < length) {
          var key = toKey(path[index]),
            newValue = value;
          if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
            return object;
          }
          if (index != lastIndex) {
            var objValue = nested[key];
            newValue = customizer ? customizer(objValue, key, nested) : undefined;
            if (newValue === undefined) {
              newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {};
            }
          }
          assignValue(nested, key, newValue);
          nested = nested[key];
        }
        return object;
      }

      /**
       * The base implementation of  `_.pickBy` without support for iteratee shorthands.
       *
       * @private
       * @param {Object} object The source object.
       * @param {string[]} paths The property paths to pick.
       * @param {Function} predicate The function invoked per property.
       * @returns {Object} Returns the new object.
       */
      function basePickBy(object, paths, predicate) {
        var index = -1,
          length = paths.length,
          result = {};
        while (++index < length) {
          var path = paths[index],
            value = baseGet(object, path);
          if (predicate(value, path)) {
            baseSet(result, castPath(path, object), value);
          }
        }
        return result;
      }

      /**
       * Creates an object composed of the `object` properties `predicate` returns
       * truthy for. The predicate is invoked with two arguments: (value, key).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The source object.
       * @param {Function} [predicate=_.identity] The function invoked per property.
       * @returns {Object} Returns the new object.
       * @example
       *
       * var object = { 'a': 1, 'b': '2', 'c': 3 };
       *
       * _.pickBy(object, _.isNumber);
       * // => { 'a': 1, 'c': 3 }
       */
      function pickBy(object, predicate) {
        if (object == null) {
          return {};
        }
        var props = arrayMap(getAllKeysIn(object), function (prop) {
          return [prop];
        });
        predicate = baseIteratee(predicate);
        return basePickBy(object, props, function (value, path) {
          return predicate(value, path[0]);
        });
      }

      /**
       * The opposite of `_.pickBy`; this method creates an object composed of
       * the own and inherited enumerable string keyed properties of `object` that
       * `predicate` doesn't return truthy for. The predicate is invoked with two
       * arguments: (value, key).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The source object.
       * @param {Function} [predicate=_.identity] The function invoked per property.
       * @returns {Object} Returns the new object.
       * @example
       *
       * var object = { 'a': 1, 'b': '2', 'c': 3 };
       *
       * _.omitBy(object, _.isNumber);
       * // => { 'b': '2' }
       */
      function omitBy(object, predicate) {
        return pickBy(object, negate(baseIteratee(predicate)));
      }

      /**
       * Creates a function that is restricted to invoking `func` once. Repeat calls
       * to the function return the value of the first invocation. The `func` is
       * invoked with the `this` binding and arguments of the created function.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to restrict.
       * @returns {Function} Returns the new restricted function.
       * @example
       *
       * var initialize = _.once(createApplication);
       * initialize();
       * initialize();
       * // => `createApplication` is invoked once
       */
      function once(func) {
        return before(2, func);
      }

      /**
       * The base implementation of `_.sortBy` which uses `comparer` to define the
       * sort order of `array` and replaces criteria objects with their corresponding
       * values.
       *
       * @private
       * @param {Array} array The array to sort.
       * @param {Function} comparer The function to define sort order.
       * @returns {Array} Returns `array`.
       */
      function baseSortBy(array, comparer) {
        var length = array.length;
        array.sort(comparer);
        while (length--) {
          array[length] = array[length].value;
        }
        return array;
      }

      /**
       * Compares values to sort them in ascending order.
       *
       * @private
       * @param {*} value The value to compare.
       * @param {*} other The other value to compare.
       * @returns {number} Returns the sort order indicator for `value`.
       */
      function compareAscending(value, other) {
        if (value !== other) {
          var valIsDefined = value !== undefined,
            valIsNull = value === null,
            valIsReflexive = value === value,
            valIsSymbol = isSymbol(value);
          var othIsDefined = other !== undefined,
            othIsNull = other === null,
            othIsReflexive = other === other,
            othIsSymbol = isSymbol(other);
          if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
            return 1;
          }
          if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
            return -1;
          }
        }
        return 0;
      }

      /**
       * Used by `_.orderBy` to compare multiple properties of a value to another
       * and stable sort them.
       *
       * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
       * specify an order of "desc" for descending or "asc" for ascending sort order
       * of corresponding values.
       *
       * @private
       * @param {Object} object The object to compare.
       * @param {Object} other The other object to compare.
       * @param {boolean[]|string[]} orders The order to sort by for each property.
       * @returns {number} Returns the sort order indicator for `object`.
       */
      function compareMultiple(object, other, orders) {
        var index = -1,
          objCriteria = object.criteria,
          othCriteria = other.criteria,
          length = objCriteria.length,
          ordersLength = orders.length;
        while (++index < length) {
          var result = compareAscending(objCriteria[index], othCriteria[index]);
          if (result) {
            if (index >= ordersLength) {
              return result;
            }
            var order = orders[index];
            return result * (order == 'desc' ? -1 : 1);
          }
        }
        // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
        // that causes it, under certain circumstances, to provide the same value for
        // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
        // for more details.
        //
        // This also ensures a stable sort in V8 and other engines.
        // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
        return object.index - other.index;
      }

      /**
       * The base implementation of `_.orderBy` without param guards.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
       * @param {string[]} orders The sort orders of `iteratees`.
       * @returns {Array} Returns the new sorted array.
       */
      function baseOrderBy(collection, iteratees, orders) {
        if (iteratees.length) {
          iteratees = arrayMap(iteratees, function (iteratee) {
            if (isArray$1(iteratee)) {
              return function (value) {
                return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
              };
            }
            return iteratee;
          });
        } else {
          iteratees = [identity];
        }
        var index = -1;
        iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
        var result = baseMap(collection, function (value, key, collection) {
          var criteria = arrayMap(iteratees, function (iteratee) {
            return iteratee(value);
          });
          return {
            'criteria': criteria,
            'index': ++index,
            'value': value
          };
        });
        return baseSortBy(result, function (object, other) {
          return compareMultiple(object, other, orders);
        });
      }

      /**
       * This method is like `_.sortBy` except that it allows specifying the sort
       * orders of the iteratees to sort by. If `orders` is unspecified, all values
       * are sorted in ascending order. Otherwise, specify an order of "desc" for
       * descending or "asc" for ascending sort order of corresponding values.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
       *  The iteratees to sort by.
       * @param {string[]} [orders] The sort orders of `iteratees`.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
       * @returns {Array} Returns the new sorted array.
       * @example
       *
       * var users = [
       *   { 'user': 'fred',   'age': 48 },
       *   { 'user': 'barney', 'age': 34 },
       *   { 'user': 'fred',   'age': 40 },
       *   { 'user': 'barney', 'age': 36 }
       * ];
       *
       * // Sort by `user` in ascending order and by `age` in descending order.
       * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
       * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
       */
      function orderBy(collection, iteratees, orders, guard) {
        if (collection == null) {
          return [];
        }
        if (!isArray$1(iteratees)) {
          iteratees = iteratees == null ? [] : [iteratees];
        }
        orders = guard ? undefined : orders;
        if (!isArray$1(orders)) {
          orders = orders == null ? [] : [orders];
        }
        return baseOrderBy(collection, iteratees, orders);
      }

      /**
       * Creates a function like `_.over`.
       *
       * @private
       * @param {Function} arrayFunc The function to iterate over iteratees.
       * @returns {Function} Returns the new over function.
       */
      function createOver(arrayFunc) {
        return flatRest(function (iteratees) {
          iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
          return baseRest(function (args) {
            var thisArg = this;
            return arrayFunc(iteratees, function (iteratee) {
              return apply(iteratee, thisArg, args);
            });
          });
        });
      }

      /**
       * Creates a function that invokes `iteratees` with the arguments it receives
       * and returns their results.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {...(Function|Function[])} [iteratees=[_.identity]]
       *  The iteratees to invoke.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var func = _.over([Math.max, Math.min]);
       *
       * func(1, 2, 3, 4);
       * // => [4, 1]
       */
      var over = createOver(arrayMap);

      /**
       * A `baseRest` alias which can be replaced with `identity` by module
       * replacement plugins.
       *
       * @private
       * @type {Function}
       * @param {Function} func The function to apply a rest parameter to.
       * @returns {Function} Returns the new function.
       */
      var castRest = baseRest;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$8 = Math.min;

      /**
       * Creates a function that invokes `func` with its arguments transformed.
       *
       * @static
       * @since 4.0.0
       * @memberOf _
       * @category Function
       * @param {Function} func The function to wrap.
       * @param {...(Function|Function[])} [transforms=[_.identity]]
       *  The argument transforms.
       * @returns {Function} Returns the new function.
       * @example
       *
       * function doubled(n) {
       *   return n * 2;
       * }
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * var func = _.overArgs(function(x, y) {
       *   return [x, y];
       * }, [square, doubled]);
       *
       * func(9, 3);
       * // => [81, 6]
       *
       * func(10, 5);
       * // => [100, 10]
       */
      var overArgs = castRest(function (func, transforms) {
        transforms = transforms.length == 1 && isArray$1(transforms[0]) ? arrayMap(transforms[0], baseUnary(baseIteratee)) : arrayMap(baseFlatten(transforms, 1), baseUnary(baseIteratee));
        var funcsLength = transforms.length;
        return baseRest(function (args) {
          var index = -1,
            length = nativeMin$8(args.length, funcsLength);
          while (++index < length) {
            args[index] = transforms[index].call(this, args[index]);
          }
          return apply(func, this, args);
        });
      });

      /**
       * Creates a function that checks if **all** of the `predicates` return
       * truthy when invoked with the arguments it receives.
       *
       * Following shorthands are possible for providing predicates.
       * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
       * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {...(Function|Function[])} [predicates=[_.identity]]
       *  The predicates to check.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var func = _.overEvery([Boolean, isFinite]);
       *
       * func('1');
       * // => true
       *
       * func(null);
       * // => false
       *
       * func(NaN);
       * // => false
       */
      var overEvery = createOver(arrayEvery);

      /**
       * Creates a function that checks if **any** of the `predicates` return
       * truthy when invoked with the arguments it receives.
       *
       * Following shorthands are possible for providing predicates.
       * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
       * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {...(Function|Function[])} [predicates=[_.identity]]
       *  The predicates to check.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var func = _.overSome([Boolean, isFinite]);
       *
       * func('1');
       * // => true
       *
       * func(null);
       * // => true
       *
       * func(NaN);
       * // => false
       *
       * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
       * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
       */
      var overSome = createOver(arraySome);

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER$3 = 9007199254740991;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeFloor = Math.floor;

      /**
       * The base implementation of `_.repeat` which doesn't coerce arguments.
       *
       * @private
       * @param {string} string The string to repeat.
       * @param {number} n The number of times to repeat the string.
       * @returns {string} Returns the repeated string.
       */
      function baseRepeat(string, n) {
        var result = '';
        if (!string || n < 1 || n > MAX_SAFE_INTEGER$3) {
          return result;
        }
        // Leverage the exponentiation by squaring algorithm for a faster repeat.
        // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
        do {
          if (n % 2) {
            result += string;
          }
          n = nativeFloor(n / 2);
          if (n) {
            string += string;
          }
        } while (n);
        return result;
      }

      /**
       * Gets the size of an ASCII `string`.
       *
       * @private
       * @param {string} string The string inspect.
       * @returns {number} Returns the string size.
       */
      var asciiSize = baseProperty('length');

      /** Used to compose unicode character classes. */
      var rsAstralRange$3 = "\\ud800-\\udfff",
        rsComboMarksRange$4 = "\\u0300-\\u036f",
        reComboHalfMarksRange$4 = "\\ufe20-\\ufe2f",
        rsComboSymbolsRange$4 = "\\u20d0-\\u20ff",
        rsComboRange$4 = rsComboMarksRange$4 + reComboHalfMarksRange$4 + rsComboSymbolsRange$4,
        rsVarRange$3 = "\\ufe0e\\ufe0f";

      /** Used to compose unicode capture groups. */
      var rsAstral$1 = '[' + rsAstralRange$3 + ']',
        rsCombo$3 = '[' + rsComboRange$4 + ']',
        rsFitz$2 = "\\ud83c[\\udffb-\\udfff]",
        rsModifier$2 = '(?:' + rsCombo$3 + '|' + rsFitz$2 + ')',
        rsNonAstral$2 = '[^' + rsAstralRange$3 + ']',
        rsRegional$2 = "(?:\\ud83c[\\udde6-\\uddff]){2}",
        rsSurrPair$2 = "[\\ud800-\\udbff][\\udc00-\\udfff]",
        rsZWJ$3 = "\\u200d";

      /** Used to compose unicode regexes. */
      var reOptMod$2 = rsModifier$2 + '?',
        rsOptVar$2 = '[' + rsVarRange$3 + ']?',
        rsOptJoin$2 = '(?:' + rsZWJ$3 + '(?:' + [rsNonAstral$2, rsRegional$2, rsSurrPair$2].join('|') + ')' + rsOptVar$2 + reOptMod$2 + ')*',
        rsSeq$2 = rsOptVar$2 + reOptMod$2 + rsOptJoin$2,
        rsSymbol$1 = '(?:' + [rsNonAstral$2 + rsCombo$3 + '?', rsCombo$3, rsRegional$2, rsSurrPair$2, rsAstral$1].join('|') + ')';

      /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
      var reUnicode$1 = RegExp(rsFitz$2 + '(?=' + rsFitz$2 + ')|' + rsSymbol$1 + rsSeq$2, 'g');

      /**
       * Gets the size of a Unicode `string`.
       *
       * @private
       * @param {string} string The string inspect.
       * @returns {number} Returns the string size.
       */
      function unicodeSize(string) {
        var result = reUnicode$1.lastIndex = 0;
        while (reUnicode$1.test(string)) {
          ++result;
        }
        return result;
      }

      /**
       * Gets the number of symbols in `string`.
       *
       * @private
       * @param {string} string The string to inspect.
       * @returns {number} Returns the string size.
       */
      function stringSize(string) {
        return hasUnicode(string) ? unicodeSize(string) : asciiSize(string);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeCeil$1 = Math.ceil;

      /**
       * Creates the padding for `string` based on `length`. The `chars` string
       * is truncated if the number of characters exceeds `length`.
       *
       * @private
       * @param {number} length The padding length.
       * @param {string} [chars=' '] The string used as padding.
       * @returns {string} Returns the padding for `string`.
       */
      function createPadding(length, chars) {
        chars = chars === undefined ? ' ' : baseToString(chars);
        var charsLength = chars.length;
        if (charsLength < 2) {
          return charsLength ? baseRepeat(chars, length) : chars;
        }
        var result = baseRepeat(chars, nativeCeil$1(length / stringSize(chars)));
        return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeCeil$2 = Math.ceil,
        nativeFloor$1 = Math.floor;

      /**
       * Pads `string` on the left and right sides if it's shorter than `length`.
       * Padding characters are truncated if they can't be evenly divided by `length`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to pad.
       * @param {number} [length=0] The padding length.
       * @param {string} [chars=' '] The string used as padding.
       * @returns {string} Returns the padded string.
       * @example
       *
       * _.pad('abc', 8);
       * // => '  abc   '
       *
       * _.pad('abc', 8, '_-');
       * // => '_-abc_-_'
       *
       * _.pad('abc', 3);
       * // => 'abc'
       */
      function pad(string, length, chars) {
        string = toString(string);
        length = toInteger(length);
        var strLength = length ? stringSize(string) : 0;
        if (!length || strLength >= length) {
          return string;
        }
        var mid = (length - strLength) / 2;
        return createPadding(nativeFloor$1(mid), chars) + string + createPadding(nativeCeil$2(mid), chars);
      }

      /**
       * Pads `string` on the right side if it's shorter than `length`. Padding
       * characters are truncated if they exceed `length`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to pad.
       * @param {number} [length=0] The padding length.
       * @param {string} [chars=' '] The string used as padding.
       * @returns {string} Returns the padded string.
       * @example
       *
       * _.padEnd('abc', 6);
       * // => 'abc   '
       *
       * _.padEnd('abc', 6, '_-');
       * // => 'abc_-_'
       *
       * _.padEnd('abc', 3);
       * // => 'abc'
       */
      function padEnd(string, length, chars) {
        string = toString(string);
        length = toInteger(length);
        var strLength = length ? stringSize(string) : 0;
        return length && strLength < length ? string + createPadding(length - strLength, chars) : string;
      }

      /**
       * Pads `string` on the left side if it's shorter than `length`. Padding
       * characters are truncated if they exceed `length`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to pad.
       * @param {number} [length=0] The padding length.
       * @param {string} [chars=' '] The string used as padding.
       * @returns {string} Returns the padded string.
       * @example
       *
       * _.padStart('abc', 6);
       * // => '   abc'
       *
       * _.padStart('abc', 6, '_-');
       * // => '_-_abc'
       *
       * _.padStart('abc', 3);
       * // => 'abc'
       */
      function padStart(string, length, chars) {
        string = toString(string);
        length = toInteger(length);
        var strLength = length ? stringSize(string) : 0;
        return length && strLength < length ? createPadding(length - strLength, chars) + string : string;
      }

      /** Used to match leading whitespace. */
      var reTrimStart$1 = /^\s+/;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeParseInt = root.parseInt;

      /**
       * Converts `string` to an integer of the specified radix. If `radix` is
       * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
       * hexadecimal, in which case a `radix` of `16` is used.
       *
       * **Note:** This method aligns with the
       * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
       *
       * @static
       * @memberOf _
       * @since 1.1.0
       * @category String
       * @param {string} string The string to convert.
       * @param {number} [radix=10] The radix to interpret `value` by.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {number} Returns the converted integer.
       * @example
       *
       * _.parseInt('08');
       * // => 8
       *
       * _.map(['6', '08', '10'], _.parseInt);
       * // => [6, 8, 10]
       */
      function parseInt$1(string, radix, guard) {
        if (guard || radix == null) {
          radix = 0;
        } else if (radix) {
          radix = +radix;
        }
        return nativeParseInt(toString(string).replace(reTrimStart$1, ''), radix || 0);
      }

      /** Used to compose bitmasks for function metadata. */
      var WRAP_PARTIAL_FLAG$6 = 32;

      /**
       * Creates a function that invokes `func` with `partials` prepended to the
       * arguments it receives. This method is like `_.bind` except it does **not**
       * alter the `this` binding.
       *
       * The `_.partial.placeholder` value, which defaults to `_` in monolithic
       * builds, may be used as a placeholder for partially applied arguments.
       *
       * **Note:** This method doesn't set the "length" property of partially
       * applied functions.
       *
       * @static
       * @memberOf _
       * @since 0.2.0
       * @category Function
       * @param {Function} func The function to partially apply arguments to.
       * @param {...*} [partials] The arguments to be partially applied.
       * @returns {Function} Returns the new partially applied function.
       * @example
       *
       * function greet(greeting, name) {
       *   return greeting + ' ' + name;
       * }
       *
       * var sayHelloTo = _.partial(greet, 'hello');
       * sayHelloTo('fred');
       * // => 'hello fred'
       *
       * // Partially applied with placeholders.
       * var greetFred = _.partial(greet, _, 'fred');
       * greetFred('hi');
       * // => 'hi fred'
       */
      var partial = baseRest(function (func, partials) {
        var holders = replaceHolders(partials, getHolder(partial));
        return createWrap(func, WRAP_PARTIAL_FLAG$6, undefined, partials, holders);
      });

      // Assign default placeholders.
      partial.placeholder = {};

      /** Used to compose bitmasks for function metadata. */
      var WRAP_PARTIAL_RIGHT_FLAG$3 = 64;

      /**
       * This method is like `_.partial` except that partially applied arguments
       * are appended to the arguments it receives.
       *
       * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
       * builds, may be used as a placeholder for partially applied arguments.
       *
       * **Note:** This method doesn't set the "length" property of partially
       * applied functions.
       *
       * @static
       * @memberOf _
       * @since 1.0.0
       * @category Function
       * @param {Function} func The function to partially apply arguments to.
       * @param {...*} [partials] The arguments to be partially applied.
       * @returns {Function} Returns the new partially applied function.
       * @example
       *
       * function greet(greeting, name) {
       *   return greeting + ' ' + name;
       * }
       *
       * var greetFred = _.partialRight(greet, 'fred');
       * greetFred('hi');
       * // => 'hi fred'
       *
       * // Partially applied with placeholders.
       * var sayHelloTo = _.partialRight(greet, 'hello', _);
       * sayHelloTo('fred');
       * // => 'hello fred'
       */
      var partialRight = baseRest(function (func, partials) {
        var holders = replaceHolders(partials, getHolder(partialRight));
        return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders);
      });

      // Assign default placeholders.
      partialRight.placeholder = {};

      /**
       * Creates an array of elements split into two groups, the first of which
       * contains elements `predicate` returns truthy for, the second of which
       * contains elements `predicate` returns falsey for. The predicate is
       * invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the array of grouped elements.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'age': 36, 'active': false },
       *   { 'user': 'fred',    'age': 40, 'active': true },
       *   { 'user': 'pebbles', 'age': 1,  'active': false }
       * ];
       *
       * _.partition(users, function(o) { return o.active; });
       * // => objects for [['fred'], ['barney', 'pebbles']]
       *
       * // The `_.matches` iteratee shorthand.
       * _.partition(users, { 'age': 1, 'active': false });
       * // => objects for [['pebbles'], ['barney', 'fred']]
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.partition(users, ['active', false]);
       * // => objects for [['barney', 'pebbles'], ['fred']]
       *
       * // The `_.property` iteratee shorthand.
       * _.partition(users, 'active');
       * // => objects for [['fred'], ['barney', 'pebbles']]
       */
      var partition = createAggregator(function (result, value, key) {
        result[key ? 0 : 1].push(value);
      }, function () {
        return [[], []];
      });

      /**
       * The base implementation of `_.pick` without support for individual
       * property identifiers.
       *
       * @private
       * @param {Object} object The source object.
       * @param {string[]} paths The property paths to pick.
       * @returns {Object} Returns the new object.
       */
      function basePick(object, paths) {
        return basePickBy(object, paths, function (value, path) {
          return hasIn(object, path);
        });
      }

      /**
       * Creates an object composed of the picked `object` properties.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The source object.
       * @param {...(string|string[])} [paths] The property paths to pick.
       * @returns {Object} Returns the new object.
       * @example
       *
       * var object = { 'a': 1, 'b': '2', 'c': 3 };
       *
       * _.pick(object, ['a', 'c']);
       * // => { 'a': 1, 'c': 3 }
       */
      var pick = flatRest(function (object, paths) {
        return object == null ? {} : basePick(object, paths);
      });

      /**
       * Creates a clone of the chain sequence planting `value` as the wrapped value.
       *
       * @name plant
       * @memberOf _
       * @since 3.2.0
       * @category Seq
       * @param {*} value The value to plant.
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * function square(n) {
       *   return n * n;
       * }
       *
       * var wrapped = _([1, 2]).map(square);
       * var other = wrapped.plant([3, 4]);
       *
       * other.value();
       * // => [9, 16]
       *
       * wrapped.value();
       * // => [1, 4]
       */
      function wrapperPlant(value) {
        var result,
          parent = this;
        while (parent instanceof baseLodash) {
          var clone = wrapperClone(parent);
          clone.__index__ = 0;
          clone.__values__ = undefined;
          if (result) {
            previous.__wrapped__ = clone;
          } else {
            result = clone;
          }
          var previous = clone;
          parent = parent.__wrapped__;
        }
        previous.__wrapped__ = value;
        return result;
      }

      /**
       * The opposite of `_.property`; this method creates a function that returns
       * the value at a given path of `object`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Util
       * @param {Object} object The object to query.
       * @returns {Function} Returns the new accessor function.
       * @example
       *
       * var array = [0, 1, 2],
       *     object = { 'a': array, 'b': array, 'c': array };
       *
       * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
       * // => [2, 0]
       *
       * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
       * // => [2, 0]
       */
      function propertyOf(object) {
        return function (path) {
          return object == null ? undefined : baseGet(object, path);
        };
      }

      /**
       * This function is like `baseIndexOf` except that it accepts a comparator.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @param {number} fromIndex The index to search from.
       * @param {Function} comparator The comparator invoked per element.
       * @returns {number} Returns the index of the matched value, else `-1`.
       */
      function baseIndexOfWith(array, value, fromIndex, comparator) {
        var index = fromIndex - 1,
          length = array.length;
        while (++index < length) {
          if (comparator(array[index], value)) {
            return index;
          }
        }
        return -1;
      }

      /** Used for built-in method references. */
      var arrayProto$2 = Array.prototype;

      /** Built-in value references. */
      var splice$1 = arrayProto$2.splice;

      /**
       * The base implementation of `_.pullAllBy` without support for iteratee
       * shorthands.
       *
       * @private
       * @param {Array} array The array to modify.
       * @param {Array} values The values to remove.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns `array`.
       */
      function basePullAll(array, values, iteratee, comparator) {
        var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
          index = -1,
          length = values.length,
          seen = array;
        if (array === values) {
          values = copyArray(values);
        }
        if (iteratee) {
          seen = arrayMap(array, baseUnary(iteratee));
        }
        while (++index < length) {
          var fromIndex = 0,
            value = values[index],
            computed = iteratee ? iteratee(value) : value;
          while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
            if (seen !== array) {
              splice$1.call(seen, fromIndex, 1);
            }
            splice$1.call(array, fromIndex, 1);
          }
        }
        return array;
      }

      /**
       * This method is like `_.pull` except that it accepts an array of values to remove.
       *
       * **Note:** Unlike `_.difference`, this method mutates `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {Array} values The values to remove.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
       *
       * _.pullAll(array, ['a', 'c']);
       * console.log(array);
       * // => ['b', 'b']
       */
      function pullAll(array, values) {
        return array && array.length && values && values.length ? basePullAll(array, values) : array;
      }

      /**
       * Removes all given values from `array` using
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons.
       *
       * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
       * to remove elements from an array by predicate.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {...*} [values] The values to remove.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
       *
       * _.pull(array, 'a', 'c');
       * console.log(array);
       * // => ['b', 'b']
       */
      var pull = baseRest(pullAll);

      /**
       * This method is like `_.pullAll` except that it accepts `iteratee` which is
       * invoked for each element of `array` and `values` to generate the criterion
       * by which they're compared. The iteratee is invoked with one argument: (value).
       *
       * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {Array} values The values to remove.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
       *
       * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
       * console.log(array);
       * // => [{ 'x': 2 }]
       */
      function pullAllBy(array, values, iteratee) {
        return array && array.length && values && values.length ? basePullAll(array, values, baseIteratee(iteratee)) : array;
      }

      /**
       * This method is like `_.pullAll` except that it accepts `comparator` which
       * is invoked to compare elements of `array` to `values`. The comparator is
       * invoked with two arguments: (arrVal, othVal).
       *
       * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
       *
       * @static
       * @memberOf _
       * @since 4.6.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {Array} values The values to remove.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
       *
       * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
       * console.log(array);
       * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
       */
      function pullAllWith(array, values, comparator) {
        return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array;
      }

      /** Used for built-in method references. */
      var arrayProto$3 = Array.prototype;

      /** Built-in value references. */
      var splice$2 = arrayProto$3.splice;

      /**
       * The base implementation of `_.pullAt` without support for individual
       * indexes or capturing the removed elements.
       *
       * @private
       * @param {Array} array The array to modify.
       * @param {number[]} indexes The indexes of elements to remove.
       * @returns {Array} Returns `array`.
       */
      function basePullAt(array, indexes) {
        var length = array ? indexes.length : 0,
          lastIndex = length - 1;
        while (length--) {
          var index = indexes[length];
          if (length == lastIndex || index !== previous) {
            var previous = index;
            if (isIndex(index)) {
              splice$2.call(array, index, 1);
            } else {
              baseUnset(array, index);
            }
          }
        }
        return array;
      }

      /**
       * Removes elements from `array` corresponding to `indexes` and returns an
       * array of removed elements.
       *
       * **Note:** Unlike `_.at`, this method mutates `array`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {...(number|number[])} [indexes] The indexes of elements to remove.
       * @returns {Array} Returns the new array of removed elements.
       * @example
       *
       * var array = ['a', 'b', 'c', 'd'];
       * var pulled = _.pullAt(array, [1, 3]);
       *
       * console.log(array);
       * // => ['a', 'c']
       *
       * console.log(pulled);
       * // => ['b', 'd']
       */
      var pullAt = flatRest(function (array, indexes) {
        var length = array == null ? 0 : array.length,
          result = baseAt(array, indexes);
        basePullAt(array, arrayMap(indexes, function (index) {
          return isIndex(index, length) ? +index : index;
        }).sort(compareAscending));
        return result;
      });

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeFloor$2 = Math.floor,
        nativeRandom = Math.random;

      /**
       * The base implementation of `_.random` without support for returning
       * floating-point numbers.
       *
       * @private
       * @param {number} lower The lower bound.
       * @param {number} upper The upper bound.
       * @returns {number} Returns the random number.
       */
      function baseRandom(lower, upper) {
        return lower + nativeFloor$2(nativeRandom() * (upper - lower + 1));
      }

      /** Built-in method references without a dependency on `root`. */
      var freeParseFloat = parseFloat;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$9 = Math.min,
        nativeRandom$1 = Math.random;

      /**
       * Produces a random number between the inclusive `lower` and `upper` bounds.
       * If only one argument is provided a number between `0` and the given number
       * is returned. If `floating` is `true`, or either `lower` or `upper` are
       * floats, a floating-point number is returned instead of an integer.
       *
       * **Note:** JavaScript follows the IEEE-754 standard for resolving
       * floating-point values which can produce unexpected results.
       *
       * @static
       * @memberOf _
       * @since 0.7.0
       * @category Number
       * @param {number} [lower=0] The lower bound.
       * @param {number} [upper=1] The upper bound.
       * @param {boolean} [floating] Specify returning a floating-point number.
       * @returns {number} Returns the random number.
       * @example
       *
       * _.random(0, 5);
       * // => an integer between 0 and 5
       *
       * _.random(5);
       * // => also an integer between 0 and 5
       *
       * _.random(5, true);
       * // => a floating-point number between 0 and 5
       *
       * _.random(1.2, 5.2);
       * // => a floating-point number between 1.2 and 5.2
       */
      function random(lower, upper, floating) {
        if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
          upper = floating = undefined;
        }
        if (floating === undefined) {
          if (typeof upper == 'boolean') {
            floating = upper;
            upper = undefined;
          } else if (typeof lower == 'boolean') {
            floating = lower;
            lower = undefined;
          }
        }
        if (lower === undefined && upper === undefined) {
          lower = 0;
          upper = 1;
        } else {
          lower = toFinite(lower);
          if (upper === undefined) {
            upper = lower;
            lower = 0;
          } else {
            upper = toFinite(upper);
          }
        }
        if (lower > upper) {
          var temp = lower;
          lower = upper;
          upper = temp;
        }
        if (floating || lower % 1 || upper % 1) {
          var rand = nativeRandom$1();
          return nativeMin$9(lower + rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1))), upper);
        }
        return baseRandom(lower, upper);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeCeil$3 = Math.ceil,
        nativeMax$c = Math.max;

      /**
       * The base implementation of `_.range` and `_.rangeRight` which doesn't
       * coerce arguments.
       *
       * @private
       * @param {number} start The start of the range.
       * @param {number} end The end of the range.
       * @param {number} step The value to increment or decrement by.
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Array} Returns the range of numbers.
       */
      function baseRange(start, end, step, fromRight) {
        var index = -1,
          length = nativeMax$c(nativeCeil$3((end - start) / (step || 1)), 0),
          result = Array(length);
        while (length--) {
          result[fromRight ? length : ++index] = start;
          start += step;
        }
        return result;
      }

      /**
       * Creates a `_.range` or `_.rangeRight` function.
       *
       * @private
       * @param {boolean} [fromRight] Specify iterating from right to left.
       * @returns {Function} Returns the new range function.
       */
      function createRange(fromRight) {
        return function (start, end, step) {
          if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
            end = step = undefined;
          }
          // Ensure the sign of `-0` is preserved.
          start = toFinite(start);
          if (end === undefined) {
            end = start;
            start = 0;
          } else {
            end = toFinite(end);
          }
          step = step === undefined ? start < end ? 1 : -1 : toFinite(step);
          return baseRange(start, end, step, fromRight);
        };
      }

      /**
       * Creates an array of numbers (positive and/or negative) progressing from
       * `start` up to, but not including, `end`. A step of `-1` is used if a negative
       * `start` is specified without an `end` or `step`. If `end` is not specified,
       * it's set to `start` with `start` then set to `0`.
       *
       * **Note:** JavaScript follows the IEEE-754 standard for resolving
       * floating-point values which can produce unexpected results.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {number} [start=0] The start of the range.
       * @param {number} end The end of the range.
       * @param {number} [step=1] The value to increment or decrement by.
       * @returns {Array} Returns the range of numbers.
       * @see _.inRange, _.rangeRight
       * @example
       *
       * _.range(4);
       * // => [0, 1, 2, 3]
       *
       * _.range(-4);
       * // => [0, -1, -2, -3]
       *
       * _.range(1, 5);
       * // => [1, 2, 3, 4]
       *
       * _.range(0, 20, 5);
       * // => [0, 5, 10, 15]
       *
       * _.range(0, -4, -1);
       * // => [0, -1, -2, -3]
       *
       * _.range(1, 4, 0);
       * // => [1, 1, 1]
       *
       * _.range(0);
       * // => []
       */
      var range = createRange();

      /**
       * This method is like `_.range` except that it populates values in
       * descending order.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {number} [start=0] The start of the range.
       * @param {number} end The end of the range.
       * @param {number} [step=1] The value to increment or decrement by.
       * @returns {Array} Returns the range of numbers.
       * @see _.inRange, _.range
       * @example
       *
       * _.rangeRight(4);
       * // => [3, 2, 1, 0]
       *
       * _.rangeRight(-4);
       * // => [-3, -2, -1, 0]
       *
       * _.rangeRight(1, 5);
       * // => [4, 3, 2, 1]
       *
       * _.rangeRight(0, 20, 5);
       * // => [15, 10, 5, 0]
       *
       * _.rangeRight(0, -4, -1);
       * // => [-3, -2, -1, 0]
       *
       * _.rangeRight(1, 4, 0);
       * // => [1, 1, 1]
       *
       * _.rangeRight(0);
       * // => []
       */
      var rangeRight = createRange(true);

      /** Used to compose bitmasks for function metadata. */
      var WRAP_REARG_FLAG$3 = 256;

      /**
       * Creates a function that invokes `func` with arguments arranged according
       * to the specified `indexes` where the argument value at the first index is
       * provided as the first argument, the argument value at the second index is
       * provided as the second argument, and so on.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Function
       * @param {Function} func The function to rearrange arguments for.
       * @param {...(number|number[])} indexes The arranged argument indexes.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var rearged = _.rearg(function(a, b, c) {
       *   return [a, b, c];
       * }, [2, 0, 1]);
       *
       * rearged('b', 'c', 'a')
       * // => ['a', 'b', 'c']
       */
      var rearg = flatRest(function (func, indexes) {
        return createWrap(func, WRAP_REARG_FLAG$3, undefined, undefined, undefined, indexes);
      });

      /**
       * The base implementation of `_.reduce` and `_.reduceRight`, without support
       * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @param {*} accumulator The initial value.
       * @param {boolean} initAccum Specify using the first or last element of
       *  `collection` as the initial value.
       * @param {Function} eachFunc The function to iterate over `collection`.
       * @returns {*} Returns the accumulated value.
       */
      function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
        eachFunc(collection, function (value, index, collection) {
          accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection);
        });
        return accumulator;
      }

      /**
       * Reduces `collection` to a value which is the accumulated result of running
       * each element in `collection` thru `iteratee`, where each successive
       * invocation is supplied the return value of the previous. If `accumulator`
       * is not given, the first element of `collection` is used as the initial
       * value. The iteratee is invoked with four arguments:
       * (accumulator, value, index|key, collection).
       *
       * Many lodash methods are guarded to work as iteratees for methods like
       * `_.reduce`, `_.reduceRight`, and `_.transform`.
       *
       * The guarded methods are:
       * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
       * and `sortBy`
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @param {*} [accumulator] The initial value.
       * @returns {*} Returns the accumulated value.
       * @see _.reduceRight
       * @example
       *
       * _.reduce([1, 2], function(sum, n) {
       *   return sum + n;
       * }, 0);
       * // => 3
       *
       * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
       *   (result[value] || (result[value] = [])).push(key);
       *   return result;
       * }, {});
       * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
       */
      function reduce(collection, iteratee, accumulator) {
        var func = isArray$1(collection) ? arrayReduce : baseReduce,
          initAccum = arguments.length < 3;
        return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEach);
      }

      /**
       * A specialized version of `_.reduceRight` for arrays without support for
       * iteratee shorthands.
       *
       * @private
       * @param {Array} [array] The array to iterate over.
       * @param {Function} iteratee The function invoked per iteration.
       * @param {*} [accumulator] The initial value.
       * @param {boolean} [initAccum] Specify using the last element of `array` as
       *  the initial value.
       * @returns {*} Returns the accumulated value.
       */
      function arrayReduceRight(array, iteratee, accumulator, initAccum) {
        var length = array == null ? 0 : array.length;
        if (initAccum && length) {
          accumulator = array[--length];
        }
        while (length--) {
          accumulator = iteratee(accumulator, array[length], length, array);
        }
        return accumulator;
      }

      /**
       * This method is like `_.reduce` except that it iterates over elements of
       * `collection` from right to left.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @param {*} [accumulator] The initial value.
       * @returns {*} Returns the accumulated value.
       * @see _.reduce
       * @example
       *
       * var array = [[0, 1], [2, 3], [4, 5]];
       *
       * _.reduceRight(array, function(flattened, other) {
       *   return flattened.concat(other);
       * }, []);
       * // => [4, 5, 2, 3, 0, 1]
       */
      function reduceRight(collection, iteratee, accumulator) {
        var func = isArray$1(collection) ? arrayReduceRight : baseReduce,
          initAccum = arguments.length < 3;
        return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEachRight);
      }

      /**
       * The opposite of `_.filter`; this method returns the elements of `collection`
       * that `predicate` does **not** return truthy for.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new filtered array.
       * @see _.filter
       * @example
       *
       * var users = [
       *   { 'user': 'barney', 'age': 36, 'active': false },
       *   { 'user': 'fred',   'age': 40, 'active': true }
       * ];
       *
       * _.reject(users, function(o) { return !o.active; });
       * // => objects for ['fred']
       *
       * // The `_.matches` iteratee shorthand.
       * _.reject(users, { 'age': 40, 'active': true });
       * // => objects for ['barney']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.reject(users, ['active', false]);
       * // => objects for ['fred']
       *
       * // The `_.property` iteratee shorthand.
       * _.reject(users, 'active');
       * // => objects for ['barney']
       */
      function reject(collection, predicate) {
        var func = isArray$1(collection) ? arrayFilter : baseFilter;
        return func(collection, negate(baseIteratee(predicate)));
      }

      /**
       * Removes all elements from `array` that `predicate` returns truthy for
       * and returns an array of the removed elements. The predicate is invoked
       * with three arguments: (value, index, array).
       *
       * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
       * to pull elements from an array by value.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the new array of removed elements.
       * @example
       *
       * var array = [1, 2, 3, 4];
       * var evens = _.remove(array, function(n) {
       *   return n % 2 == 0;
       * });
       *
       * console.log(array);
       * // => [1, 3]
       *
       * console.log(evens);
       * // => [2, 4]
       */
      function remove(array, predicate) {
        var result = [];
        if (!(array && array.length)) {
          return result;
        }
        var index = -1,
          indexes = [],
          length = array.length;
        predicate = baseIteratee(predicate);
        while (++index < length) {
          var value = array[index];
          if (predicate(value, index, array)) {
            result.push(value);
            indexes.push(index);
          }
        }
        basePullAt(array, indexes);
        return result;
      }

      /**
       * Repeats the given string `n` times.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to repeat.
       * @param {number} [n=1] The number of times to repeat the string.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {string} Returns the repeated string.
       * @example
       *
       * _.repeat('*', 3);
       * // => '***'
       *
       * _.repeat('abc', 2);
       * // => 'abcabc'
       *
       * _.repeat('abc', 0);
       * // => ''
       */
      function repeat(string, n, guard) {
        if (guard ? isIterateeCall(string, n, guard) : n === undefined) {
          n = 1;
        } else {
          n = toInteger(n);
        }
        return baseRepeat(toString(string), n);
      }

      /**
       * Replaces matches for `pattern` in `string` with `replacement`.
       *
       * **Note:** This method is based on
       * [`String#replace`](https://mdn.io/String/replace).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to modify.
       * @param {RegExp|string} pattern The pattern to replace.
       * @param {Function|string} replacement The match replacement.
       * @returns {string} Returns the modified string.
       * @example
       *
       * _.replace('Hi Fred', 'Fred', 'Barney');
       * // => 'Hi Barney'
       */
      function replace() {
        var args = arguments,
          string = toString(args[0]);
        return args.length < 3 ? string : string.replace(args[1], args[2]);
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT$9 = 'Expected a function';

      /**
       * Creates a function that invokes `func` with the `this` binding of the
       * created function and arguments from `start` and beyond provided as
       * an array.
       *
       * **Note:** This method is based on the
       * [rest parameter](https://mdn.io/rest_parameters).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Function
       * @param {Function} func The function to apply a rest parameter to.
       * @param {number} [start=func.length-1] The start position of the rest parameter.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var say = _.rest(function(what, names) {
       *   return what + ' ' + _.initial(names).join(', ') +
       *     (_.size(names) > 1 ? ', & ' : '') + _.last(names);
       * });
       *
       * say('hello', 'fred', 'barney', 'pebbles');
       * // => 'hello fred, barney, & pebbles'
       */
      function rest(func, start) {
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$9);
        }
        start = start === undefined ? start : toInteger(start);
        return baseRest(func, start);
      }

      /**
       * This method is like `_.get` except that if the resolved value is a
       * function it's invoked with the `this` binding of its parent object and
       * its result is returned.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Object
       * @param {Object} object The object to query.
       * @param {Array|string} path The path of the property to resolve.
       * @param {*} [defaultValue] The value returned for `undefined` resolved values.
       * @returns {*} Returns the resolved value.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
       *
       * _.result(object, 'a[0].b.c1');
       * // => 3
       *
       * _.result(object, 'a[0].b.c2');
       * // => 4
       *
       * _.result(object, 'a[0].b.c3', 'default');
       * // => 'default'
       *
       * _.result(object, 'a[0].b.c3', _.constant('default'));
       * // => 'default'
       */
      function result(object, path, defaultValue) {
        path = castPath(path, object);
        var index = -1,
          length = path.length;

        // Ensure the loop is entered when path is empty.
        if (!length) {
          length = 1;
          object = undefined;
        }
        while (++index < length) {
          var value = object == null ? undefined : object[toKey(path[index])];
          if (value === undefined) {
            index = length;
            value = defaultValue;
          }
          object = isFunction(value) ? value.call(object) : value;
        }
        return object;
      }

      /** Used for built-in method references. */
      var arrayProto$4 = Array.prototype;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeReverse = arrayProto$4.reverse;

      /**
       * Reverses `array` so that the first element becomes the last, the second
       * element becomes the second to last, and so on.
       *
       * **Note:** This method mutates `array` and is based on
       * [`Array#reverse`](https://mdn.io/Array/reverse).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to modify.
       * @returns {Array} Returns `array`.
       * @example
       *
       * var array = [1, 2, 3];
       *
       * _.reverse(array);
       * // => [3, 2, 1]
       *
       * console.log(array);
       * // => [3, 2, 1]
       */
      function reverse(array) {
        return array == null ? array : nativeReverse.call(array);
      }

      /**
       * Computes `number` rounded to `precision`.
       *
       * @static
       * @memberOf _
       * @since 3.10.0
       * @category Math
       * @param {number} number The number to round.
       * @param {number} [precision=0] The precision to round to.
       * @returns {number} Returns the rounded number.
       * @example
       *
       * _.round(4.006);
       * // => 4
       *
       * _.round(4.006, 2);
       * // => 4.01
       *
       * _.round(4060, -2);
       * // => 4100
       */
      var round = createRound('round');

      /**
       * A specialized version of `_.sample` for arrays.
       *
       * @private
       * @param {Array} array The array to sample.
       * @returns {*} Returns the random element.
       */
      function arraySample(array) {
        var length = array.length;
        return length ? array[baseRandom(0, length - 1)] : undefined;
      }

      /**
       * The base implementation of `_.sample`.
       *
       * @private
       * @param {Array|Object} collection The collection to sample.
       * @returns {*} Returns the random element.
       */
      function baseSample(collection) {
        return arraySample(values(collection));
      }

      /**
       * Gets a random element from `collection`.
       *
       * @static
       * @memberOf _
       * @since 2.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to sample.
       * @returns {*} Returns the random element.
       * @example
       *
       * _.sample([1, 2, 3, 4]);
       * // => 2
       */
      function sample(collection) {
        var func = isArray$1(collection) ? arraySample : baseSample;
        return func(collection);
      }

      /**
       * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
       *
       * @private
       * @param {Array} array The array to shuffle.
       * @param {number} [size=array.length] The size of `array`.
       * @returns {Array} Returns `array`.
       */
      function shuffleSelf(array, size) {
        var index = -1,
          length = array.length,
          lastIndex = length - 1;
        size = size === undefined ? length : size;
        while (++index < size) {
          var rand = baseRandom(index, lastIndex),
            value = array[rand];
          array[rand] = array[index];
          array[index] = value;
        }
        array.length = size;
        return array;
      }

      /**
       * A specialized version of `_.sampleSize` for arrays.
       *
       * @private
       * @param {Array} array The array to sample.
       * @param {number} n The number of elements to sample.
       * @returns {Array} Returns the random elements.
       */
      function arraySampleSize(array, n) {
        return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
      }

      /**
       * The base implementation of `_.sampleSize` without param guards.
       *
       * @private
       * @param {Array|Object} collection The collection to sample.
       * @param {number} n The number of elements to sample.
       * @returns {Array} Returns the random elements.
       */
      function baseSampleSize(collection, n) {
        var array = values(collection);
        return shuffleSelf(array, baseClamp(n, 0, array.length));
      }

      /**
       * Gets `n` random elements at unique keys from `collection` up to the
       * size of `collection`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Collection
       * @param {Array|Object} collection The collection to sample.
       * @param {number} [n=1] The number of elements to sample.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the random elements.
       * @example
       *
       * _.sampleSize([1, 2, 3], 2);
       * // => [3, 1]
       *
       * _.sampleSize([1, 2, 3], 4);
       * // => [2, 3, 1]
       */
      function sampleSize(collection, n, guard) {
        if (guard ? isIterateeCall(collection, n, guard) : n === undefined) {
          n = 1;
        } else {
          n = toInteger(n);
        }
        var func = isArray$1(collection) ? arraySampleSize : baseSampleSize;
        return func(collection, n);
      }

      /**
       * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
       * it's created. Arrays are created for missing index properties while objects
       * are created for all other missing properties. Use `_.setWith` to customize
       * `path` creation.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 3.7.0
       * @category Object
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to set.
       * @param {*} value The value to set.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 3 } }] };
       *
       * _.set(object, 'a[0].b.c', 4);
       * console.log(object.a[0].b.c);
       * // => 4
       *
       * _.set(object, ['x', '0', 'y', 'z'], 5);
       * console.log(object.x[0].y.z);
       * // => 5
       */
      function set(object, path, value) {
        return object == null ? object : baseSet(object, path, value);
      }

      /**
       * This method is like `_.set` except that it accepts `customizer` which is
       * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
       * path creation is handled by the method instead. The `customizer` is invoked
       * with three arguments: (nsValue, key, nsObject).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to set.
       * @param {*} value The value to set.
       * @param {Function} [customizer] The function to customize assigned values.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var object = {};
       *
       * _.setWith(object, '[0][1]', 'a', Object);
       * // => { '0': { '1': 'a' } }
       */
      function setWith(object, path, value, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        return object == null ? object : baseSet(object, path, value, customizer);
      }

      /**
       * A specialized version of `_.shuffle` for arrays.
       *
       * @private
       * @param {Array} array The array to shuffle.
       * @returns {Array} Returns the new shuffled array.
       */
      function arrayShuffle(array) {
        return shuffleSelf(copyArray(array));
      }

      /**
       * The base implementation of `_.shuffle`.
       *
       * @private
       * @param {Array|Object} collection The collection to shuffle.
       * @returns {Array} Returns the new shuffled array.
       */
      function baseShuffle(collection) {
        return shuffleSelf(values(collection));
      }

      /**
       * Creates an array of shuffled values, using a version of the
       * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to shuffle.
       * @returns {Array} Returns the new shuffled array.
       * @example
       *
       * _.shuffle([1, 2, 3, 4]);
       * // => [4, 1, 3, 2]
       */
      function shuffle(collection) {
        var func = isArray$1(collection) ? arrayShuffle : baseShuffle;
        return func(collection);
      }

      /** `Object#toString` result references. */
      var mapTag$9 = '[object Map]',
        setTag$9 = '[object Set]';

      /**
       * Gets the size of `collection` by returning its length for array-like
       * values or the number of own enumerable string keyed properties for objects.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object|string} collection The collection to inspect.
       * @returns {number} Returns the collection size.
       * @example
       *
       * _.size([1, 2, 3]);
       * // => 3
       *
       * _.size({ 'a': 1, 'b': 2 });
       * // => 2
       *
       * _.size('pebbles');
       * // => 7
       */
      function size(collection) {
        if (collection == null) {
          return 0;
        }
        if (isArrayLike(collection)) {
          return isString(collection) ? stringSize(collection) : collection.length;
        }
        var tag = getTag$1(collection);
        if (tag == mapTag$9 || tag == setTag$9) {
          return collection.size;
        }
        return baseKeys(collection).length;
      }

      /**
       * Creates a slice of `array` from `start` up to, but not including, `end`.
       *
       * **Note:** This method is used instead of
       * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
       * returned.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to slice.
       * @param {number} [start=0] The start position.
       * @param {number} [end=array.length] The end position.
       * @returns {Array} Returns the slice of `array`.
       */
      function slice(array, start, end) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
          start = 0;
          end = length;
        } else {
          start = start == null ? 0 : toInteger(start);
          end = end === undefined ? length : toInteger(end);
        }
        return baseSlice(array, start, end);
      }

      /**
       * Converts `string` to
       * [snake case](https://en.wikipedia.org/wiki/Snake_case).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the snake cased string.
       * @example
       *
       * _.snakeCase('Foo Bar');
       * // => 'foo_bar'
       *
       * _.snakeCase('fooBar');
       * // => 'foo_bar'
       *
       * _.snakeCase('--FOO-BAR--');
       * // => 'foo_bar'
       */
      var snakeCase = createCompounder(function (result, word, index) {
        return result + (index ? '_' : '') + word.toLowerCase();
      });

      /**
       * The base implementation of `_.some` without support for iteratee shorthands.
       *
       * @private
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} predicate The function invoked per iteration.
       * @returns {boolean} Returns `true` if any element passes the predicate check,
       *  else `false`.
       */
      function baseSome(collection, predicate) {
        var result;
        baseEach(collection, function (value, index, collection) {
          result = predicate(value, index, collection);
          return !result;
        });
        return !!result;
      }

      /**
       * Checks if `predicate` returns truthy for **any** element of `collection`.
       * Iteration is stopped once `predicate` returns truthy. The predicate is
       * invoked with three arguments: (value, index|key, collection).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {boolean} Returns `true` if any element passes the predicate check,
       *  else `false`.
       * @example
       *
       * _.some([null, 0, 'yes', false], Boolean);
       * // => true
       *
       * var users = [
       *   { 'user': 'barney', 'active': true },
       *   { 'user': 'fred',   'active': false }
       * ];
       *
       * // The `_.matches` iteratee shorthand.
       * _.some(users, { 'user': 'barney', 'active': false });
       * // => false
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.some(users, ['active', false]);
       * // => true
       *
       * // The `_.property` iteratee shorthand.
       * _.some(users, 'active');
       * // => true
       */
      function some(collection, predicate, guard) {
        var func = isArray$1(collection) ? arraySome : baseSome;
        if (guard && isIterateeCall(collection, predicate, guard)) {
          predicate = undefined;
        }
        return func(collection, baseIteratee(predicate));
      }

      /**
       * Creates an array of elements, sorted in ascending order by the results of
       * running each element in a collection thru each iteratee. This method
       * performs a stable sort, that is, it preserves the original sort order of
       * equal elements. The iteratees are invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Collection
       * @param {Array|Object} collection The collection to iterate over.
       * @param {...(Function|Function[])} [iteratees=[_.identity]]
       *  The iteratees to sort by.
       * @returns {Array} Returns the new sorted array.
       * @example
       *
       * var users = [
       *   { 'user': 'fred',   'age': 48 },
       *   { 'user': 'barney', 'age': 36 },
       *   { 'user': 'fred',   'age': 30 },
       *   { 'user': 'barney', 'age': 34 }
       * ];
       *
       * _.sortBy(users, [function(o) { return o.user; }]);
       * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
       *
       * _.sortBy(users, ['user', 'age']);
       * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
       */
      var sortBy = baseRest(function (collection, iteratees) {
        if (collection == null) {
          return [];
        }
        var length = iteratees.length;
        if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
          iteratees = [];
        } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
          iteratees = [iteratees[0]];
        }
        return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
      });

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$2 = 4294967295,
        MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH$2 - 1;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeFloor$3 = Math.floor,
        nativeMin$a = Math.min;

      /**
       * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
       * which invokes `iteratee` for `value` and each element of `array` to compute
       * their sort ranking. The iteratee is invoked with one argument; (value).
       *
       * @private
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @param {Function} iteratee The iteratee invoked per element.
       * @param {boolean} [retHighest] Specify returning the highest qualified index.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       */
      function baseSortedIndexBy(array, value, iteratee, retHighest) {
        var low = 0,
          high = array == null ? 0 : array.length;
        if (high === 0) {
          return 0;
        }
        value = iteratee(value);
        var valIsNaN = value !== value,
          valIsNull = value === null,
          valIsSymbol = isSymbol(value),
          valIsUndefined = value === undefined;
        while (low < high) {
          var mid = nativeFloor$3((low + high) / 2),
            computed = iteratee(array[mid]),
            othIsDefined = computed !== undefined,
            othIsNull = computed === null,
            othIsReflexive = computed === computed,
            othIsSymbol = isSymbol(computed);
          if (valIsNaN) {
            var setLow = retHighest || othIsReflexive;
          } else if (valIsUndefined) {
            setLow = othIsReflexive && (retHighest || othIsDefined);
          } else if (valIsNull) {
            setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
          } else if (valIsSymbol) {
            setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
          } else if (othIsNull || othIsSymbol) {
            setLow = false;
          } else {
            setLow = retHighest ? computed <= value : computed < value;
          }
          if (setLow) {
            low = mid + 1;
          } else {
            high = mid;
          }
        }
        return nativeMin$a(high, MAX_ARRAY_INDEX);
      }

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$3 = 4294967295,
        HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH$3 >>> 1;

      /**
       * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
       * performs a binary search of `array` to determine the index at which `value`
       * should be inserted into `array` in order to maintain its sort order.
       *
       * @private
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @param {boolean} [retHighest] Specify returning the highest qualified index.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       */
      function baseSortedIndex(array, value, retHighest) {
        var low = 0,
          high = array == null ? low : array.length;
        if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
          while (low < high) {
            var mid = low + high >>> 1,
              computed = array[mid];
            if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) {
              low = mid + 1;
            } else {
              high = mid;
            }
          }
          return high;
        }
        return baseSortedIndexBy(array, value, identity, retHighest);
      }

      /**
       * Uses a binary search to determine the lowest index at which `value`
       * should be inserted into `array` in order to maintain its sort order.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       * @example
       *
       * _.sortedIndex([30, 50], 40);
       * // => 1
       */
      function sortedIndex(array, value) {
        return baseSortedIndex(array, value);
      }

      /**
       * This method is like `_.sortedIndex` except that it accepts `iteratee`
       * which is invoked for `value` and each element of `array` to compute their
       * sort ranking. The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       * @example
       *
       * var objects = [{ 'x': 4 }, { 'x': 5 }];
       *
       * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
       * // => 0
       *
       * // The `_.property` iteratee shorthand.
       * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
       * // => 0
       */
      function sortedIndexBy(array, value, iteratee) {
        return baseSortedIndexBy(array, value, baseIteratee(iteratee));
      }

      /**
       * This method is like `_.indexOf` except that it performs a binary
       * search on a sorted `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @returns {number} Returns the index of the matched value, else `-1`.
       * @example
       *
       * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
       * // => 1
       */
      function sortedIndexOf(array, value) {
        var length = array == null ? 0 : array.length;
        if (length) {
          var index = baseSortedIndex(array, value);
          if (index < length && eq(array[index], value)) {
            return index;
          }
        }
        return -1;
      }

      /**
       * This method is like `_.sortedIndex` except that it returns the highest
       * index at which `value` should be inserted into `array` in order to
       * maintain its sort order.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       * @example
       *
       * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
       * // => 4
       */
      function sortedLastIndex(array, value) {
        return baseSortedIndex(array, value, true);
      }

      /**
       * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
       * which is invoked for `value` and each element of `array` to compute their
       * sort ranking. The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The sorted array to inspect.
       * @param {*} value The value to evaluate.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {number} Returns the index at which `value` should be inserted
       *  into `array`.
       * @example
       *
       * var objects = [{ 'x': 4 }, { 'x': 5 }];
       *
       * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
       * // => 1
       *
       * // The `_.property` iteratee shorthand.
       * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
       * // => 1
       */
      function sortedLastIndexBy(array, value, iteratee) {
        return baseSortedIndexBy(array, value, baseIteratee(iteratee), true);
      }

      /**
       * This method is like `_.lastIndexOf` except that it performs a binary
       * search on a sorted `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {*} value The value to search for.
       * @returns {number} Returns the index of the matched value, else `-1`.
       * @example
       *
       * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
       * // => 3
       */
      function sortedLastIndexOf(array, value) {
        var length = array == null ? 0 : array.length;
        if (length) {
          var index = baseSortedIndex(array, value, true) - 1;
          if (eq(array[index], value)) {
            return index;
          }
        }
        return -1;
      }

      /**
       * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
       * support for iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @returns {Array} Returns the new duplicate free array.
       */
      function baseSortedUniq(array, iteratee) {
        var index = -1,
          length = array.length,
          resIndex = 0,
          result = [];
        while (++index < length) {
          var value = array[index],
            computed = iteratee ? iteratee(value) : value;
          if (!index || !eq(computed, seen)) {
            var seen = computed;
            result[resIndex++] = value === 0 ? 0 : value;
          }
        }
        return result;
      }

      /**
       * This method is like `_.uniq` except that it's designed and optimized
       * for sorted arrays.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @returns {Array} Returns the new duplicate free array.
       * @example
       *
       * _.sortedUniq([1, 1, 2]);
       * // => [1, 2]
       */
      function sortedUniq(array) {
        return array && array.length ? baseSortedUniq(array) : [];
      }

      /**
       * This method is like `_.uniqBy` except that it's designed and optimized
       * for sorted arrays.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @returns {Array} Returns the new duplicate free array.
       * @example
       *
       * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
       * // => [1.1, 2.3]
       */
      function sortedUniqBy(array, iteratee) {
        return array && array.length ? baseSortedUniq(array, baseIteratee(iteratee)) : [];
      }

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$4 = 4294967295;

      /**
       * Splits `string` by `separator`.
       *
       * **Note:** This method is based on
       * [`String#split`](https://mdn.io/String/split).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to split.
       * @param {RegExp|string} separator The separator pattern to split by.
       * @param {number} [limit] The length to truncate results to.
       * @returns {Array} Returns the string segments.
       * @example
       *
       * _.split('a-b-c', '-', 2);
       * // => ['a', 'b']
       */
      function split(string, separator, limit) {
        if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
          separator = limit = undefined;
        }
        limit = limit === undefined ? MAX_ARRAY_LENGTH$4 : limit >>> 0;
        if (!limit) {
          return [];
        }
        string = toString(string);
        if (string && (typeof separator == 'string' || separator != null && !isRegExp(separator))) {
          separator = baseToString(separator);
          if (!separator && hasUnicode(string)) {
            return castSlice(stringToArray(string), 0, limit);
          }
        }
        return string.split(separator, limit);
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT$a = 'Expected a function';

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$d = Math.max;

      /**
       * Creates a function that invokes `func` with the `this` binding of the
       * create function and an array of arguments much like
       * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
       *
       * **Note:** This method is based on the
       * [spread operator](https://mdn.io/spread_operator).
       *
       * @static
       * @memberOf _
       * @since 3.2.0
       * @category Function
       * @param {Function} func The function to spread arguments over.
       * @param {number} [start=0] The start position of the spread.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var say = _.spread(function(who, what) {
       *   return who + ' says ' + what;
       * });
       *
       * say(['fred', 'hello']);
       * // => 'fred says hello'
       *
       * var numbers = Promise.all([
       *   Promise.resolve(40),
       *   Promise.resolve(36)
       * ]);
       *
       * numbers.then(_.spread(function(x, y) {
       *   return x + y;
       * }));
       * // => a Promise of 76
       */
      function spread(func, start) {
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$a);
        }
        start = start == null ? 0 : nativeMax$d(toInteger(start), 0);
        return baseRest(function (args) {
          var array = args[start],
            otherArgs = castSlice(args, 0, start);
          if (array) {
            arrayPush(otherArgs, array);
          }
          return apply(func, this, otherArgs);
        });
      }

      /**
       * Converts `string` to
       * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
       *
       * @static
       * @memberOf _
       * @since 3.1.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the start cased string.
       * @example
       *
       * _.startCase('--foo-bar--');
       * // => 'Foo Bar'
       *
       * _.startCase('fooBar');
       * // => 'Foo Bar'
       *
       * _.startCase('__FOO_BAR__');
       * // => 'FOO BAR'
       */
      var startCase = createCompounder(function (result, word, index) {
        return result + (index ? ' ' : '') + upperFirst(word);
      });

      /**
       * Checks if `string` starts with the given target string.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to inspect.
       * @param {string} [target] The string to search for.
       * @param {number} [position=0] The position to search from.
       * @returns {boolean} Returns `true` if `string` starts with `target`,
       *  else `false`.
       * @example
       *
       * _.startsWith('abc', 'a');
       * // => true
       *
       * _.startsWith('abc', 'b');
       * // => false
       *
       * _.startsWith('abc', 'b', 1);
       * // => true
       */
      function startsWith(string, target, position) {
        string = toString(string);
        position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length);
        target = baseToString(target);
        return string.slice(position, position + target.length) == target;
      }

      /**
       * This method returns a new empty object.
       *
       * @static
       * @memberOf _
       * @since 4.13.0
       * @category Util
       * @returns {Object} Returns the new empty object.
       * @example
       *
       * var objects = _.times(2, _.stubObject);
       *
       * console.log(objects);
       * // => [{}, {}]
       *
       * console.log(objects[0] === objects[1]);
       * // => false
       */
      function stubObject() {
        return {};
      }

      /**
       * This method returns an empty string.
       *
       * @static
       * @memberOf _
       * @since 4.13.0
       * @category Util
       * @returns {string} Returns the empty string.
       * @example
       *
       * _.times(2, _.stubString);
       * // => ['', '']
       */
      function stubString() {
        return '';
      }

      /**
       * This method returns `true`.
       *
       * @static
       * @memberOf _
       * @since 4.13.0
       * @category Util
       * @returns {boolean} Returns `true`.
       * @example
       *
       * _.times(2, _.stubTrue);
       * // => [true, true]
       */
      function stubTrue() {
        return true;
      }

      /**
       * Subtract two numbers.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Math
       * @param {number} minuend The first number in a subtraction.
       * @param {number} subtrahend The second number in a subtraction.
       * @returns {number} Returns the difference.
       * @example
       *
       * _.subtract(6, 4);
       * // => 2
       */
      var subtract = createMathOperation(function (minuend, subtrahend) {
        return minuend - subtrahend;
      }, 0);

      /**
       * Computes the sum of the values in `array`.
       *
       * @static
       * @memberOf _
       * @since 3.4.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @returns {number} Returns the sum.
       * @example
       *
       * _.sum([4, 2, 8, 6]);
       * // => 20
       */
      function sum(array) {
        return array && array.length ? baseSum(array, identity) : 0;
      }

      /**
       * This method is like `_.sum` except that it accepts `iteratee` which is
       * invoked for each element in `array` to generate the value to be summed.
       * The iteratee is invoked with one argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Math
       * @param {Array} array The array to iterate over.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {number} Returns the sum.
       * @example
       *
       * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
       *
       * _.sumBy(objects, function(o) { return o.n; });
       * // => 20
       *
       * // The `_.property` iteratee shorthand.
       * _.sumBy(objects, 'n');
       * // => 20
       */
      function sumBy(array, iteratee) {
        return array && array.length ? baseSum(array, baseIteratee(iteratee)) : 0;
      }

      /**
       * Gets all but the first element of `array`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.tail([1, 2, 3]);
       * // => [2, 3]
       */
      function tail(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseSlice(array, 1, length) : [];
      }

      /**
       * Creates a slice of `array` with `n` elements taken from the beginning.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {number} [n=1] The number of elements to take.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.take([1, 2, 3]);
       * // => [1]
       *
       * _.take([1, 2, 3], 2);
       * // => [1, 2]
       *
       * _.take([1, 2, 3], 5);
       * // => [1, 2, 3]
       *
       * _.take([1, 2, 3], 0);
       * // => []
       */
      function take(array, n, guard) {
        if (!(array && array.length)) {
          return [];
        }
        n = guard || n === undefined ? 1 : toInteger(n);
        return baseSlice(array, 0, n < 0 ? 0 : n);
      }

      /**
       * Creates a slice of `array` with `n` elements taken from the end.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {number} [n=1] The number of elements to take.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * _.takeRight([1, 2, 3]);
       * // => [3]
       *
       * _.takeRight([1, 2, 3], 2);
       * // => [2, 3]
       *
       * _.takeRight([1, 2, 3], 5);
       * // => [1, 2, 3]
       *
       * _.takeRight([1, 2, 3], 0);
       * // => []
       */
      function takeRight(array, n, guard) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        n = guard || n === undefined ? 1 : toInteger(n);
        n = length - n;
        return baseSlice(array, n < 0 ? 0 : n, length);
      }

      /**
       * Creates a slice of `array` with elements taken from the end. Elements are
       * taken until `predicate` returns falsey. The predicate is invoked with
       * three arguments: (value, index, array).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': true },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': false }
       * ];
       *
       * _.takeRightWhile(users, function(o) { return !o.active; });
       * // => objects for ['fred', 'pebbles']
       *
       * // The `_.matches` iteratee shorthand.
       * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
       * // => objects for ['pebbles']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.takeRightWhile(users, ['active', false]);
       * // => objects for ['fred', 'pebbles']
       *
       * // The `_.property` iteratee shorthand.
       * _.takeRightWhile(users, 'active');
       * // => []
       */
      function takeRightWhile(array, predicate) {
        return array && array.length ? baseWhile(array, baseIteratee(predicate), false, true) : [];
      }

      /**
       * Creates a slice of `array` with elements taken from the beginning. Elements
       * are taken until `predicate` returns falsey. The predicate is invoked with
       * three arguments: (value, index, array).
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Array
       * @param {Array} array The array to query.
       * @param {Function} [predicate=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the slice of `array`.
       * @example
       *
       * var users = [
       *   { 'user': 'barney',  'active': false },
       *   { 'user': 'fred',    'active': false },
       *   { 'user': 'pebbles', 'active': true }
       * ];
       *
       * _.takeWhile(users, function(o) { return !o.active; });
       * // => objects for ['barney', 'fred']
       *
       * // The `_.matches` iteratee shorthand.
       * _.takeWhile(users, { 'user': 'barney', 'active': false });
       * // => objects for ['barney']
       *
       * // The `_.matchesProperty` iteratee shorthand.
       * _.takeWhile(users, ['active', false]);
       * // => objects for ['barney', 'fred']
       *
       * // The `_.property` iteratee shorthand.
       * _.takeWhile(users, 'active');
       * // => []
       */
      function takeWhile(array, predicate) {
        return array && array.length ? baseWhile(array, baseIteratee(predicate)) : [];
      }

      /**
       * This method invokes `interceptor` and returns `value`. The interceptor
       * is invoked with one argument; (value). The purpose of this method is to
       * "tap into" a method chain sequence in order to modify intermediate results.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Seq
       * @param {*} value The value to provide to `interceptor`.
       * @param {Function} interceptor The function to invoke.
       * @returns {*} Returns `value`.
       * @example
       *
       * _([1, 2, 3])
       *  .tap(function(array) {
       *    // Mutate input array.
       *    array.pop();
       *  })
       *  .reverse()
       *  .value();
       * // => [2, 1]
       */
      function tap(value, interceptor) {
        interceptor(value);
        return value;
      }

      /** Used for built-in method references. */
      var objectProto$q = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$m = objectProto$q.hasOwnProperty;

      /**
       * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
       * of source objects to the destination object for all destination properties
       * that resolve to `undefined`.
       *
       * @private
       * @param {*} objValue The destination value.
       * @param {*} srcValue The source value.
       * @param {string} key The key of the property to assign.
       * @param {Object} object The parent object of `objValue`.
       * @returns {*} Returns the value to assign.
       */
      function customDefaultsAssignIn(objValue, srcValue, key, object) {
        if (objValue === undefined || eq(objValue, objectProto$q[key]) && !hasOwnProperty$m.call(object, key)) {
          return srcValue;
        }
        return objValue;
      }

      /** Used to escape characters for inclusion in compiled string literals. */
      var stringEscapes = {
        '\\': '\\',
        "'": "'",
        '\n': 'n',
        '\r': 'r',
        "\u2028": 'u2028',
        "\u2029": 'u2029'
      };

      /**
       * Used by `_.template` to escape characters for inclusion in compiled string literals.
       *
       * @private
       * @param {string} chr The matched character to escape.
       * @returns {string} Returns the escaped character.
       */
      function escapeStringChar(chr) {
        return '\\' + stringEscapes[chr];
      }

      /** Used to match template delimiters. */
      var reInterpolate = /<%=([\s\S]+?)%>/g;

      /** Used to match template delimiters. */
      var reEscape = /<%-([\s\S]+?)%>/g;

      /** Used to match template delimiters. */
      var reEvaluate = /<%([\s\S]+?)%>/g;

      /**
       * By default, the template delimiters used by lodash are like those in
       * embedded Ruby (ERB) as well as ES2015 template strings. Change the
       * following template settings to use alternative delimiters.
       *
       * @static
       * @memberOf _
       * @type {Object}
       */
      var templateSettings = {
        /**
         * Used to detect `data` property values to be HTML-escaped.
         *
         * @memberOf _.templateSettings
         * @type {RegExp}
         */
        'escape': reEscape,
        /**
         * Used to detect code to be evaluated.
         *
         * @memberOf _.templateSettings
         * @type {RegExp}
         */
        'evaluate': reEvaluate,
        /**
         * Used to detect `data` property values to inject.
         *
         * @memberOf _.templateSettings
         * @type {RegExp}
         */
        'interpolate': reInterpolate,
        /**
         * Used to reference the data object in the template text.
         *
         * @memberOf _.templateSettings
         * @type {string}
         */
        'variable': '',
        /**
         * Used to import variables into the compiled template.
         *
         * @memberOf _.templateSettings
         * @type {Object}
         */
        'imports': {
          /**
           * A reference to the `lodash` function.
           *
           * @memberOf _.templateSettings.imports
           * @type {Function}
           */
          '_': {
            'escape': escape
          }
        }
      };

      /** Error message constants. */
      var INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';

      /** Used to match empty string literals in compiled template source. */
      var reEmptyStringLeading = /\b__p \+= '';/g,
        reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
        reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;

      /**
       * Used to validate the `validate` option in `_.template` variable.
       *
       * Forbids characters which could potentially change the meaning of the function argument definition:
       * - "()," (modification of function parameters)
       * - "=" (default value)
       * - "[]{}" (destructuring of function parameters)
       * - "/" (beginning of a comment)
       * - whitespace
       */
      var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;

      /**
       * Used to match
       * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
       */
      var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;

      /** Used to ensure capturing order of template delimiters. */
      var reNoMatch = /($^)/;

      /** Used to match unescaped characters in compiled string literals. */
      var reUnescapedString = /['\n\r\u2028\u2029\\]/g;

      /** Used for built-in method references. */
      var objectProto$r = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$n = objectProto$r.hasOwnProperty;

      /**
       * Creates a compiled template function that can interpolate data properties
       * in "interpolate" delimiters, HTML-escape interpolated data properties in
       * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
       * properties may be accessed as free variables in the template. If a setting
       * object is given, it takes precedence over `_.templateSettings` values.
       *
       * **Note:** In the development build `_.template` utilizes
       * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
       * for easier debugging.
       *
       * For more information on precompiling templates see
       * [lodash's custom builds documentation](https://lodash.com/custom-builds).
       *
       * For more information on Chrome extension sandboxes see
       * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category String
       * @param {string} [string=''] The template string.
       * @param {Object} [options={}] The options object.
       * @param {RegExp} [options.escape=_.templateSettings.escape]
       *  The HTML "escape" delimiter.
       * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
       *  The "evaluate" delimiter.
       * @param {Object} [options.imports=_.templateSettings.imports]
       *  An object to import into the template as free variables.
       * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
       *  The "interpolate" delimiter.
       * @param {string} [options.sourceURL='templateSources[n]']
       *  The sourceURL of the compiled template.
       * @param {string} [options.variable='obj']
       *  The data object variable name.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {Function} Returns the compiled template function.
       * @example
       *
       * // Use the "interpolate" delimiter to create a compiled template.
       * var compiled = _.template('hello <%= user %>!');
       * compiled({ 'user': 'fred' });
       * // => 'hello fred!'
       *
       * // Use the HTML "escape" delimiter to escape data property values.
       * var compiled = _.template('<b><%- value %></b>');
       * compiled({ 'value': '<script>' });
       * // => '<b>&lt;script&gt;</b>'
       *
       * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
       * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
       * compiled({ 'users': ['fred', 'barney'] });
       * // => '<li>fred</li><li>barney</li>'
       *
       * // Use the internal `print` function in "evaluate" delimiters.
       * var compiled = _.template('<% print("hello " + user); %>!');
       * compiled({ 'user': 'barney' });
       * // => 'hello barney!'
       *
       * // Use the ES template literal delimiter as an "interpolate" delimiter.
       * // Disable support by replacing the "interpolate" delimiter.
       * var compiled = _.template('hello ${ user }!');
       * compiled({ 'user': 'pebbles' });
       * // => 'hello pebbles!'
       *
       * // Use backslashes to treat delimiters as plain text.
       * var compiled = _.template('<%= "\\<%- value %\\>" %>');
       * compiled({ 'value': 'ignored' });
       * // => '<%- value %>'
       *
       * // Use the `imports` option to import `jQuery` as `jq`.
       * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
       * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
       * compiled({ 'users': ['fred', 'barney'] });
       * // => '<li>fred</li><li>barney</li>'
       *
       * // Use the `sourceURL` option to specify a custom sourceURL for the template.
       * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
       * compiled(data);
       * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
       *
       * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
       * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
       * compiled.source;
       * // => function(data) {
       * //   var __t, __p = '';
       * //   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
       * //   return __p;
       * // }
       *
       * // Use custom template delimiters.
       * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
       * var compiled = _.template('hello {{ user }}!');
       * compiled({ 'user': 'mustache' });
       * // => 'hello mustache!'
       *
       * // Use the `source` property to inline compiled templates for meaningful
       * // line numbers in error messages and stack traces.
       * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
       *   var JST = {\
       *     "main": ' + _.template(mainText).source + '\
       *   };\
       * ');
       */
      function template(string, options, guard) {
        // Based on John Resig's `tmpl` implementation
        // (http://ejohn.org/blog/javascript-micro-templating/)
        // and Laura Doktorova's doT.js (https://github.com/olado/doT).
        var settings = templateSettings.imports._.templateSettings || templateSettings;
        if (guard && isIterateeCall(string, options, guard)) {
          options = undefined;
        }
        string = toString(string);
        options = assignInWith({}, options, settings, customDefaultsAssignIn);
        var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
          importsKeys = keys(imports),
          importsValues = baseValues(imports, importsKeys);
        var isEscaping,
          isEvaluating,
          index = 0,
          interpolate = options.interpolate || reNoMatch,
          source = "__p += '";

        // Compile the regexp to match each delimiter.
        var reDelimiters = RegExp((options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$', 'g');

        // Use a sourceURL for easier debugging.
        // The sourceURL gets injected into the source that's eval-ed, so be careful
        // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
        // and escape the comment, thus injecting code that gets evaled.
        var sourceURL = hasOwnProperty$n.call(options, 'sourceURL') ? '//# sourceURL=' + (options.sourceURL + '').replace(/\s/g, ' ') + '\n' : '';
        string.replace(reDelimiters, function (match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
          interpolateValue || (interpolateValue = esTemplateValue);

          // Escape characters that can't be included in string literals.
          source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);

          // Replace delimiters with snippets.
          if (escapeValue) {
            isEscaping = true;
            source += "' +\n__e(" + escapeValue + ") +\n'";
          }
          if (evaluateValue) {
            isEvaluating = true;
            source += "';\n" + evaluateValue + ";\n__p += '";
          }
          if (interpolateValue) {
            source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
          }
          index = offset + match.length;

          // The JS engine embedded in Adobe products needs `match` returned in
          // order to produce the correct `offset` value.
          return match;
        });
        source += "';\n";

        // If `variable` is not specified wrap a with-statement around the generated
        // code to add the data object to the top of the scope chain.
        var variable = hasOwnProperty$n.call(options, 'variable') && options.variable;
        if (!variable) {
          source = 'with (obj) {\n' + source + '\n}\n';
        }
        // Throw an error if a forbidden character was found in `variable`, to prevent
        // potential command injection attacks.
        else if (reForbiddenIdentifierChars.test(variable)) {
          throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
        }

        // Cleanup code by stripping empty strings.
        source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source).replace(reEmptyStringMiddle, '$1').replace(reEmptyStringTrailing, '$1;');

        // Frame code as the function body.
        source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n') + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '') + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n') + source + 'return __p\n}';
        var result = attempt(function () {
          return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
        });

        // Provide the compiled function's source by its `toString` method or
        // the `source` property as a convenience for inlining compiled templates.
        result.source = source;
        if (isError(result)) {
          throw result;
        }
        return result;
      }

      /** Error message constants. */
      var FUNC_ERROR_TEXT$b = 'Expected a function';

      /**
       * Creates a throttled function that only invokes `func` at most once per
       * every `wait` milliseconds. The throttled function comes with a `cancel`
       * method to cancel delayed `func` invocations and a `flush` method to
       * immediately invoke them. Provide `options` to indicate whether `func`
       * should be invoked on the leading and/or trailing edge of the `wait`
       * timeout. The `func` is invoked with the last arguments provided to the
       * throttled function. Subsequent calls to the throttled function return the
       * result of the last `func` invocation.
       *
       * **Note:** If `leading` and `trailing` options are `true`, `func` is
       * invoked on the trailing edge of the timeout only if the throttled function
       * is invoked more than once during the `wait` timeout.
       *
       * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
       * until to the next tick, similar to `setTimeout` with a timeout of `0`.
       *
       * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
       * for details over the differences between `_.throttle` and `_.debounce`.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {Function} func The function to throttle.
       * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
       * @param {Object} [options={}] The options object.
       * @param {boolean} [options.leading=true]
       *  Specify invoking on the leading edge of the timeout.
       * @param {boolean} [options.trailing=true]
       *  Specify invoking on the trailing edge of the timeout.
       * @returns {Function} Returns the new throttled function.
       * @example
       *
       * // Avoid excessively updating the position while scrolling.
       * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
       *
       * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
       * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
       * jQuery(element).on('click', throttled);
       *
       * // Cancel the trailing throttled invocation.
       * jQuery(window).on('popstate', throttled.cancel);
       */
      function throttle(func, wait, options) {
        var leading = true,
          trailing = true;
        if (typeof func != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT$b);
        }
        if (isObject(options)) {
          leading = 'leading' in options ? !!options.leading : leading;
          trailing = 'trailing' in options ? !!options.trailing : trailing;
        }
        return debounce(func, wait, {
          'leading': leading,
          'maxWait': wait,
          'trailing': trailing
        });
      }

      /**
       * This method is like `_.tap` except that it returns the result of `interceptor`.
       * The purpose of this method is to "pass thru" values replacing intermediate
       * results in a method chain sequence.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Seq
       * @param {*} value The value to provide to `interceptor`.
       * @param {Function} interceptor The function to invoke.
       * @returns {*} Returns the result of `interceptor`.
       * @example
       *
       * _('  abc  ')
       *  .chain()
       *  .trim()
       *  .thru(function(value) {
       *    return [value];
       *  })
       *  .value();
       * // => ['abc']
       */
      function thru(value, interceptor) {
        return interceptor(value);
      }

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER$4 = 9007199254740991;

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$5 = 4294967295;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$b = Math.min;

      /**
       * Invokes the iteratee `n` times, returning an array of the results of
       * each invocation. The iteratee is invoked with one argument; (index).
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {number} n The number of times to invoke `iteratee`.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @returns {Array} Returns the array of results.
       * @example
       *
       * _.times(3, String);
       * // => ['0', '1', '2']
       *
       *  _.times(4, _.constant(0));
       * // => [0, 0, 0, 0]
       */
      function times(n, iteratee) {
        n = toInteger(n);
        if (n < 1 || n > MAX_SAFE_INTEGER$4) {
          return [];
        }
        var index = MAX_ARRAY_LENGTH$5,
          length = nativeMin$b(n, MAX_ARRAY_LENGTH$5);
        iteratee = castFunction(iteratee);
        n -= MAX_ARRAY_LENGTH$5;
        var result = baseTimes(length, iteratee);
        while (++index < n) {
          iteratee(index);
        }
        return result;
      }

      /**
       * Enables the wrapper to be iterable.
       *
       * @name Symbol.iterator
       * @memberOf _
       * @since 4.0.0
       * @category Seq
       * @returns {Object} Returns the wrapper object.
       * @example
       *
       * var wrapped = _([1, 2]);
       *
       * wrapped[Symbol.iterator]() === wrapped;
       * // => true
       *
       * Array.from(wrapped);
       * // => [1, 2]
       */
      function wrapperToIterator() {
        return this;
      }

      /**
       * The base implementation of `wrapperValue` which returns the result of
       * performing a sequence of actions on the unwrapped `value`, where each
       * successive action is supplied the return value of the previous.
       *
       * @private
       * @param {*} value The unwrapped value.
       * @param {Array} actions Actions to perform to resolve the unwrapped value.
       * @returns {*} Returns the resolved value.
       */
      function baseWrapperValue(value, actions) {
        var result = value;
        if (result instanceof LazyWrapper) {
          result = result.value();
        }
        return arrayReduce(actions, function (result, action) {
          return action.func.apply(action.thisArg, arrayPush([result], action.args));
        }, result);
      }

      /**
       * Executes the chain sequence to resolve the unwrapped value.
       *
       * @name value
       * @memberOf _
       * @since 0.1.0
       * @alias toJSON, valueOf
       * @category Seq
       * @returns {*} Returns the resolved unwrapped value.
       * @example
       *
       * _([1, 2, 3]).value();
       * // => [1, 2, 3]
       */
      function wrapperValue() {
        return baseWrapperValue(this.__wrapped__, this.__actions__);
      }

      /**
       * Converts `string`, as a whole, to lower case just like
       * [String#toLowerCase](https://mdn.io/toLowerCase).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the lower cased string.
       * @example
       *
       * _.toLower('--Foo-Bar--');
       * // => '--foo-bar--'
       *
       * _.toLower('fooBar');
       * // => 'foobar'
       *
       * _.toLower('__FOO_BAR__');
       * // => '__foo_bar__'
       */
      function toLower(value) {
        return toString(value).toLowerCase();
      }

      /**
       * Converts `value` to a property path array.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Util
       * @param {*} value The value to convert.
       * @returns {Array} Returns the new property path array.
       * @example
       *
       * _.toPath('a.b.c');
       * // => ['a', 'b', 'c']
       *
       * _.toPath('a[0].b.c');
       * // => ['a', '0', 'b', 'c']
       */
      function toPath(value) {
        if (isArray$1(value)) {
          return arrayMap(value, toKey);
        }
        return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
      }

      /** Used as references for various `Number` constants. */
      var MAX_SAFE_INTEGER$5 = 9007199254740991;

      /**
       * Converts `value` to a safe integer. A safe integer can be compared and
       * represented correctly.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Lang
       * @param {*} value The value to convert.
       * @returns {number} Returns the converted integer.
       * @example
       *
       * _.toSafeInteger(3.2);
       * // => 3
       *
       * _.toSafeInteger(Number.MIN_VALUE);
       * // => 0
       *
       * _.toSafeInteger(Infinity);
       * // => 9007199254740991
       *
       * _.toSafeInteger('3.2');
       * // => 3
       */
      function toSafeInteger(value) {
        return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER$5, MAX_SAFE_INTEGER$5) : value === 0 ? value : 0;
      }

      /**
       * Converts `string`, as a whole, to upper case just like
       * [String#toUpperCase](https://mdn.io/toUpperCase).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the upper cased string.
       * @example
       *
       * _.toUpper('--foo-bar--');
       * // => '--FOO-BAR--'
       *
       * _.toUpper('fooBar');
       * // => 'FOOBAR'
       *
       * _.toUpper('__foo_bar__');
       * // => '__FOO_BAR__'
       */
      function toUpper(value) {
        return toString(value).toUpperCase();
      }

      /**
       * An alternative to `_.reduce`; this method transforms `object` to a new
       * `accumulator` object which is the result of running each of its own
       * enumerable string keyed properties thru `iteratee`, with each invocation
       * potentially mutating the `accumulator` object. If `accumulator` is not
       * provided, a new object with the same `[[Prototype]]` will be used. The
       * iteratee is invoked with four arguments: (accumulator, value, key, object).
       * Iteratee functions may exit iteration early by explicitly returning `false`.
       *
       * @static
       * @memberOf _
       * @since 1.3.0
       * @category Object
       * @param {Object} object The object to iterate over.
       * @param {Function} [iteratee=_.identity] The function invoked per iteration.
       * @param {*} [accumulator] The custom accumulator value.
       * @returns {*} Returns the accumulated value.
       * @example
       *
       * _.transform([2, 3, 4], function(result, n) {
       *   result.push(n *= n);
       *   return n % 2 == 0;
       * }, []);
       * // => [4, 9]
       *
       * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
       *   (result[value] || (result[value] = [])).push(key);
       * }, {});
       * // => { '1': ['a', 'c'], '2': ['b'] }
       */
      function transform(object, iteratee, accumulator) {
        var isArr = isArray$1(object),
          isArrLike = isArr || isBuffer(object) || isTypedArray(object);
        iteratee = baseIteratee(iteratee);
        if (accumulator == null) {
          var Ctor = object && object.constructor;
          if (isArrLike) {
            accumulator = isArr ? new Ctor() : [];
          } else if (isObject(object)) {
            accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
          } else {
            accumulator = {};
          }
        }
        (isArrLike ? arrayEach : baseForOwn)(object, function (value, index, object) {
          return iteratee(accumulator, value, index, object);
        });
        return accumulator;
      }

      /**
       * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
       * that is not found in the character symbols.
       *
       * @private
       * @param {Array} strSymbols The string symbols to inspect.
       * @param {Array} chrSymbols The character symbols to find.
       * @returns {number} Returns the index of the last unmatched string symbol.
       */
      function charsEndIndex(strSymbols, chrSymbols) {
        var index = strSymbols.length;
        while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
        return index;
      }

      /**
       * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
       * that is not found in the character symbols.
       *
       * @private
       * @param {Array} strSymbols The string symbols to inspect.
       * @param {Array} chrSymbols The character symbols to find.
       * @returns {number} Returns the index of the first unmatched string symbol.
       */
      function charsStartIndex(strSymbols, chrSymbols) {
        var index = -1,
          length = strSymbols.length;
        while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
        return index;
      }

      /**
       * Removes leading and trailing whitespace or specified characters from `string`.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category String
       * @param {string} [string=''] The string to trim.
       * @param {string} [chars=whitespace] The characters to trim.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {string} Returns the trimmed string.
       * @example
       *
       * _.trim('  abc  ');
       * // => 'abc'
       *
       * _.trim('-_-abc-_-', '_-');
       * // => 'abc'
       *
       * _.map(['  foo  ', '  bar  '], _.trim);
       * // => ['foo', 'bar']
       */
      function trim(string, chars, guard) {
        string = toString(string);
        if (string && (guard || chars === undefined)) {
          return baseTrim(string);
        }
        if (!string || !(chars = baseToString(chars))) {
          return string;
        }
        var strSymbols = stringToArray(string),
          chrSymbols = stringToArray(chars),
          start = charsStartIndex(strSymbols, chrSymbols),
          end = charsEndIndex(strSymbols, chrSymbols) + 1;
        return castSlice(strSymbols, start, end).join('');
      }

      /**
       * Removes trailing whitespace or specified characters from `string`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to trim.
       * @param {string} [chars=whitespace] The characters to trim.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {string} Returns the trimmed string.
       * @example
       *
       * _.trimEnd('  abc  ');
       * // => '  abc'
       *
       * _.trimEnd('-_-abc-_-', '_-');
       * // => '-_-abc'
       */
      function trimEnd(string, chars, guard) {
        string = toString(string);
        if (string && (guard || chars === undefined)) {
          return string.slice(0, trimmedEndIndex(string) + 1);
        }
        if (!string || !(chars = baseToString(chars))) {
          return string;
        }
        var strSymbols = stringToArray(string),
          end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
        return castSlice(strSymbols, 0, end).join('');
      }

      /** Used to match leading whitespace. */
      var reTrimStart$2 = /^\s+/;

      /**
       * Removes leading whitespace or specified characters from `string`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to trim.
       * @param {string} [chars=whitespace] The characters to trim.
       * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
       * @returns {string} Returns the trimmed string.
       * @example
       *
       * _.trimStart('  abc  ');
       * // => 'abc  '
       *
       * _.trimStart('-_-abc-_-', '_-');
       * // => 'abc-_-'
       */
      function trimStart(string, chars, guard) {
        string = toString(string);
        if (string && (guard || chars === undefined)) {
          return string.replace(reTrimStart$2, '');
        }
        if (!string || !(chars = baseToString(chars))) {
          return string;
        }
        var strSymbols = stringToArray(string),
          start = charsStartIndex(strSymbols, stringToArray(chars));
        return castSlice(strSymbols, start).join('');
      }

      /** Used as default options for `_.truncate`. */
      var DEFAULT_TRUNC_LENGTH = 30,
        DEFAULT_TRUNC_OMISSION = '...';

      /** Used to match `RegExp` flags from their coerced string values. */
      var reFlags$1 = /\w*$/;

      /**
       * Truncates `string` if it's longer than the given maximum string length.
       * The last characters of the truncated string are replaced with the omission
       * string which defaults to "...".
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to truncate.
       * @param {Object} [options={}] The options object.
       * @param {number} [options.length=30] The maximum string length.
       * @param {string} [options.omission='...'] The string to indicate text is omitted.
       * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
       * @returns {string} Returns the truncated string.
       * @example
       *
       * _.truncate('hi-diddly-ho there, neighborino');
       * // => 'hi-diddly-ho there, neighbo...'
       *
       * _.truncate('hi-diddly-ho there, neighborino', {
       *   'length': 24,
       *   'separator': ' '
       * });
       * // => 'hi-diddly-ho there,...'
       *
       * _.truncate('hi-diddly-ho there, neighborino', {
       *   'length': 24,
       *   'separator': /,? +/
       * });
       * // => 'hi-diddly-ho there...'
       *
       * _.truncate('hi-diddly-ho there, neighborino', {
       *   'omission': ' [...]'
       * });
       * // => 'hi-diddly-ho there, neig [...]'
       */
      function truncate(string, options) {
        var length = DEFAULT_TRUNC_LENGTH,
          omission = DEFAULT_TRUNC_OMISSION;
        if (isObject(options)) {
          var separator = 'separator' in options ? options.separator : separator;
          length = 'length' in options ? toInteger(options.length) : length;
          omission = 'omission' in options ? baseToString(options.omission) : omission;
        }
        string = toString(string);
        var strLength = string.length;
        if (hasUnicode(string)) {
          var strSymbols = stringToArray(string);
          strLength = strSymbols.length;
        }
        if (length >= strLength) {
          return string;
        }
        var end = length - stringSize(omission);
        if (end < 1) {
          return omission;
        }
        var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end);
        if (separator === undefined) {
          return result + omission;
        }
        if (strSymbols) {
          end += result.length - end;
        }
        if (isRegExp(separator)) {
          if (string.slice(end).search(separator)) {
            var match,
              substring = result;
            if (!separator.global) {
              separator = RegExp(separator.source, toString(reFlags$1.exec(separator)) + 'g');
            }
            separator.lastIndex = 0;
            while (match = separator.exec(substring)) {
              var newEnd = match.index;
            }
            result = result.slice(0, newEnd === undefined ? end : newEnd);
          }
        } else if (string.indexOf(baseToString(separator), end) != end) {
          var index = result.lastIndexOf(separator);
          if (index > -1) {
            result = result.slice(0, index);
          }
        }
        return result + omission;
      }

      /**
       * Creates a function that accepts up to one argument, ignoring any
       * additional arguments.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Function
       * @param {Function} func The function to cap arguments for.
       * @returns {Function} Returns the new capped function.
       * @example
       *
       * _.map(['6', '8', '10'], _.unary(parseInt));
       * // => [6, 8, 10]
       */
      function unary(func) {
        return ary(func, 1);
      }

      /** Used to map HTML entities to characters. */
      var htmlUnescapes = {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#39;': "'"
      };

      /**
       * Used by `_.unescape` to convert HTML entities to characters.
       *
       * @private
       * @param {string} chr The matched character to unescape.
       * @returns {string} Returns the unescaped character.
       */
      var unescapeHtmlChar = basePropertyOf(htmlUnescapes);

      /** Used to match HTML entities and HTML characters. */
      var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
        reHasEscapedHtml = RegExp(reEscapedHtml.source);

      /**
       * The inverse of `_.escape`; this method converts the HTML entities
       * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
       * their corresponding characters.
       *
       * **Note:** No other HTML entities are unescaped. To unescape additional
       * HTML entities use a third-party library like [_he_](https://mths.be/he).
       *
       * @static
       * @memberOf _
       * @since 0.6.0
       * @category String
       * @param {string} [string=''] The string to unescape.
       * @returns {string} Returns the unescaped string.
       * @example
       *
       * _.unescape('fred, barney, &amp; pebbles');
       * // => 'fred, barney, & pebbles'
       */
      function unescape(string) {
        string = toString(string);
        return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string;
      }

      /** Used as references for various `Number` constants. */
      var INFINITY$5 = 1 / 0;

      /**
       * Creates a set object of `values`.
       *
       * @private
       * @param {Array} values The values to add to the set.
       * @returns {Object} Returns the new set.
       */
      var createSet = !(Set$1 && 1 / setToArray(new Set$1([, -0]))[1] == INFINITY$5) ? noop : function (values) {
        return new Set$1(values);
      };

      /** Used as the size to enable large array optimizations. */
      var LARGE_ARRAY_SIZE$2 = 200;

      /**
       * The base implementation of `_.uniqBy` without support for iteratee shorthands.
       *
       * @private
       * @param {Array} array The array to inspect.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new duplicate free array.
       */
      function baseUniq(array, iteratee, comparator) {
        var index = -1,
          includes = arrayIncludes,
          length = array.length,
          isCommon = true,
          result = [],
          seen = result;
        if (comparator) {
          isCommon = false;
          includes = arrayIncludesWith;
        } else if (length >= LARGE_ARRAY_SIZE$2) {
          var set = iteratee ? null : createSet(array);
          if (set) {
            return setToArray(set);
          }
          isCommon = false;
          includes = cacheHas;
          seen = new SetCache();
        } else {
          seen = iteratee ? [] : result;
        }
        outer: while (++index < length) {
          var value = array[index],
            computed = iteratee ? iteratee(value) : value;
          value = comparator || value !== 0 ? value : 0;
          if (isCommon && computed === computed) {
            var seenIndex = seen.length;
            while (seenIndex--) {
              if (seen[seenIndex] === computed) {
                continue outer;
              }
            }
            if (iteratee) {
              seen.push(computed);
            }
            result.push(value);
          } else if (!includes(seen, computed, comparator)) {
            if (seen !== result) {
              seen.push(computed);
            }
            result.push(value);
          }
        }
        return result;
      }

      /**
       * Creates an array of unique values, in order, from all given arrays using
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @returns {Array} Returns the new array of combined values.
       * @example
       *
       * _.union([2], [1, 2]);
       * // => [2, 1]
       */
      var union = baseRest(function (arrays) {
        return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
      });

      /**
       * This method is like `_.union` except that it accepts `iteratee` which is
       * invoked for each element of each `arrays` to generate the criterion by
       * which uniqueness is computed. Result values are chosen from the first
       * array in which the value occurs. The iteratee is invoked with one argument:
       * (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns the new array of combined values.
       * @example
       *
       * _.unionBy([2.1], [1.2, 2.3], Math.floor);
       * // => [2.1, 1.2]
       *
       * // The `_.property` iteratee shorthand.
       * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
       * // => [{ 'x': 1 }, { 'x': 2 }]
       */
      var unionBy = baseRest(function (arrays) {
        var iteratee = last(arrays);
        if (isArrayLikeObject(iteratee)) {
          iteratee = undefined;
        }
        return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), baseIteratee(iteratee));
      });

      /**
       * This method is like `_.union` except that it accepts `comparator` which
       * is invoked to compare elements of `arrays`. Result values are chosen from
       * the first array in which the value occurs. The comparator is invoked
       * with two arguments: (arrVal, othVal).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of combined values.
       * @example
       *
       * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
       * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
       *
       * _.unionWith(objects, others, _.isEqual);
       * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
       */
      var unionWith = baseRest(function (arrays) {
        var comparator = last(arrays);
        comparator = typeof comparator == 'function' ? comparator : undefined;
        return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
      });

      /**
       * Creates a duplicate-free version of an array, using
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons, in which only the first occurrence of each element
       * is kept. The order of result values is determined by the order they occur
       * in the array.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @returns {Array} Returns the new duplicate free array.
       * @example
       *
       * _.uniq([2, 1, 2]);
       * // => [2, 1]
       */
      function uniq(array) {
        return array && array.length ? baseUniq(array) : [];
      }

      /**
       * This method is like `_.uniq` except that it accepts `iteratee` which is
       * invoked for each element in `array` to generate the criterion by which
       * uniqueness is computed. The order of result values is determined by the
       * order they occur in the array. The iteratee is invoked with one argument:
       * (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns the new duplicate free array.
       * @example
       *
       * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
       * // => [2.1, 1.2]
       *
       * // The `_.property` iteratee shorthand.
       * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
       * // => [{ 'x': 1 }, { 'x': 2 }]
       */
      function uniqBy(array, iteratee) {
        return array && array.length ? baseUniq(array, baseIteratee(iteratee)) : [];
      }

      /**
       * This method is like `_.uniq` except that it accepts `comparator` which
       * is invoked to compare elements of `array`. The order of result values is
       * determined by the order they occur in the array.The comparator is invoked
       * with two arguments: (arrVal, othVal).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new duplicate free array.
       * @example
       *
       * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
       *
       * _.uniqWith(objects, _.isEqual);
       * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
       */
      function uniqWith(array, comparator) {
        comparator = typeof comparator == 'function' ? comparator : undefined;
        return array && array.length ? baseUniq(array, undefined, comparator) : [];
      }

      /** Used to generate unique IDs. */
      var idCounter$1 = 0;

      /**
       * Generates a unique ID. If `prefix` is given, the ID is appended to it.
       *
       * @static
       * @since 0.1.0
       * @memberOf _
       * @category Util
       * @param {string} [prefix=''] The value to prefix the ID with.
       * @returns {string} Returns the unique ID.
       * @example
       *
       * _.uniqueId('contact_');
       * // => 'contact_104'
       *
       * _.uniqueId();
       * // => '105'
       */
      function uniqueId(prefix) {
        var id = ++idCounter$1;
        return toString(prefix) + id;
      }

      /**
       * Removes the property at `path` of `object`.
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Object
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to unset.
       * @returns {boolean} Returns `true` if the property is deleted, else `false`.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 7 } }] };
       * _.unset(object, 'a[0].b.c');
       * // => true
       *
       * console.log(object);
       * // => { 'a': [{ 'b': {} }] };
       *
       * _.unset(object, ['a', '0', 'b', 'c']);
       * // => true
       *
       * console.log(object);
       * // => { 'a': [{ 'b': {} }] };
       */
      function unset(object, path) {
        return object == null ? true : baseUnset(object, path);
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$e = Math.max;

      /**
       * This method is like `_.zip` except that it accepts an array of grouped
       * elements and creates an array regrouping the elements to their pre-zip
       * configuration.
       *
       * @static
       * @memberOf _
       * @since 1.2.0
       * @category Array
       * @param {Array} array The array of grouped elements to process.
       * @returns {Array} Returns the new array of regrouped elements.
       * @example
       *
       * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
       * // => [['a', 1, true], ['b', 2, false]]
       *
       * _.unzip(zipped);
       * // => [['a', 'b'], [1, 2], [true, false]]
       */
      function unzip(array) {
        if (!(array && array.length)) {
          return [];
        }
        var length = 0;
        array = arrayFilter(array, function (group) {
          if (isArrayLikeObject(group)) {
            length = nativeMax$e(group.length, length);
            return true;
          }
        });
        return baseTimes(length, function (index) {
          return arrayMap(array, baseProperty(index));
        });
      }

      /**
       * This method is like `_.unzip` except that it accepts `iteratee` to specify
       * how regrouped values should be combined. The iteratee is invoked with the
       * elements of each group: (...group).
       *
       * @static
       * @memberOf _
       * @since 3.8.0
       * @category Array
       * @param {Array} array The array of grouped elements to process.
       * @param {Function} [iteratee=_.identity] The function to combine
       *  regrouped values.
       * @returns {Array} Returns the new array of regrouped elements.
       * @example
       *
       * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
       * // => [[1, 10, 100], [2, 20, 200]]
       *
       * _.unzipWith(zipped, _.add);
       * // => [3, 30, 300]
       */
      function unzipWith(array, iteratee) {
        if (!(array && array.length)) {
          return [];
        }
        var result = unzip(array);
        if (iteratee == null) {
          return result;
        }
        return arrayMap(result, function (group) {
          return apply(iteratee, undefined, group);
        });
      }

      /**
       * The base implementation of `_.update`.
       *
       * @private
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to update.
       * @param {Function} updater The function to produce the updated value.
       * @param {Function} [customizer] The function to customize path creation.
       * @returns {Object} Returns `object`.
       */
      function baseUpdate(object, path, updater, customizer) {
        return baseSet(object, path, updater(baseGet(object, path)), customizer);
      }

      /**
       * This method is like `_.set` except that accepts `updater` to produce the
       * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
       * is invoked with one argument: (value).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.6.0
       * @category Object
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to set.
       * @param {Function} updater The function to produce the updated value.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 3 } }] };
       *
       * _.update(object, 'a[0].b.c', function(n) { return n * n; });
       * console.log(object.a[0].b.c);
       * // => 9
       *
       * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
       * console.log(object.x[0].y.z);
       * // => 0
       */
      function update(object, path, updater) {
        return object == null ? object : baseUpdate(object, path, castFunction(updater));
      }

      /**
       * This method is like `_.update` except that it accepts `customizer` which is
       * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
       * path creation is handled by the method instead. The `customizer` is invoked
       * with three arguments: (nsValue, key, nsObject).
       *
       * **Note:** This method mutates `object`.
       *
       * @static
       * @memberOf _
       * @since 4.6.0
       * @category Object
       * @param {Object} object The object to modify.
       * @param {Array|string} path The path of the property to set.
       * @param {Function} updater The function to produce the updated value.
       * @param {Function} [customizer] The function to customize assigned values.
       * @returns {Object} Returns `object`.
       * @example
       *
       * var object = {};
       *
       * _.updateWith(object, '[0][1]', _.constant('a'), Object);
       * // => { '0': { '1': 'a' } }
       */
      function updateWith(object, path, updater, customizer) {
        customizer = typeof customizer == 'function' ? customizer : undefined;
        return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
      }

      /**
       * Converts `string`, as space separated words, to upper case.
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the upper cased string.
       * @example
       *
       * _.upperCase('--foo-bar');
       * // => 'FOO BAR'
       *
       * _.upperCase('fooBar');
       * // => 'FOO BAR'
       *
       * _.upperCase('__foo_bar__');
       * // => 'FOO BAR'
       */
      var upperCase = createCompounder(function (result, word, index) {
        return result + (index ? ' ' : '') + word.toUpperCase();
      });

      /**
       * Creates an array of the own and inherited enumerable string keyed property
       * values of `object`.
       *
       * **Note:** Non-object values are coerced to objects.
       *
       * @static
       * @memberOf _
       * @since 3.0.0
       * @category Object
       * @param {Object} object The object to query.
       * @returns {Array} Returns the array of property values.
       * @example
       *
       * function Foo() {
       *   this.a = 1;
       *   this.b = 2;
       * }
       *
       * Foo.prototype.c = 3;
       *
       * _.valuesIn(new Foo);
       * // => [1, 2, 3] (iteration order is not guaranteed)
       */
      function valuesIn(object) {
        return object == null ? [] : baseValues(object, keysIn(object));
      }

      /**
       * Creates an array excluding all given values using
       * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
       * for equality comparisons.
       *
       * **Note:** Unlike `_.pull`, this method returns a new array.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {Array} array The array to inspect.
       * @param {...*} [values] The values to exclude.
       * @returns {Array} Returns the new array of filtered values.
       * @see _.difference, _.xor
       * @example
       *
       * _.without([2, 1, 2, 3], 1, 2);
       * // => [3]
       */
      var without = baseRest(function (array, values) {
        return isArrayLikeObject(array) ? baseDifference(array, values) : [];
      });

      /**
       * Creates a function that provides `value` to `wrapper` as its first
       * argument. Any additional arguments provided to the function are appended
       * to those provided to the `wrapper`. The wrapper is invoked with the `this`
       * binding of the created function.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Function
       * @param {*} value The value to wrap.
       * @param {Function} [wrapper=identity] The wrapper function.
       * @returns {Function} Returns the new function.
       * @example
       *
       * var p = _.wrap(_.escape, function(func, text) {
       *   return '<p>' + func(text) + '</p>';
       * });
       *
       * p('fred, barney, & pebbles');
       * // => '<p>fred, barney, &amp; pebbles</p>'
       */
      function wrap(value, wrapper) {
        return partial(castFunction(wrapper), value);
      }

      /**
       * This method is the wrapper version of `_.at`.
       *
       * @name at
       * @memberOf _
       * @since 1.0.0
       * @category Seq
       * @param {...(string|string[])} [paths] The property paths to pick.
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
       *
       * _(object).at(['a[0].b.c', 'a[1]']).value();
       * // => [3, 4]
       */
      var wrapperAt = flatRest(function (paths) {
        var length = paths.length,
          start = length ? paths[0] : 0,
          value = this.__wrapped__,
          interceptor = function interceptor(object) {
            return baseAt(object, paths);
          };
        if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) {
          return this.thru(interceptor);
        }
        value = value.slice(start, +start + (length ? 1 : 0));
        value.__actions__.push({
          'func': thru,
          'args': [interceptor],
          'thisArg': undefined
        });
        return new LodashWrapper(value, this.__chain__).thru(function (array) {
          if (length && !array.length) {
            array.push(undefined);
          }
          return array;
        });
      });

      /**
       * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
       *
       * @name chain
       * @memberOf _
       * @since 0.1.0
       * @category Seq
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * var users = [
       *   { 'user': 'barney', 'age': 36 },
       *   { 'user': 'fred',   'age': 40 }
       * ];
       *
       * // A sequence without explicit chaining.
       * _(users).head();
       * // => { 'user': 'barney', 'age': 36 }
       *
       * // A sequence with explicit chaining.
       * _(users)
       *   .chain()
       *   .head()
       *   .pick('user')
       *   .value();
       * // => { 'user': 'barney' }
       */
      function wrapperChain() {
        return chain(this);
      }

      /**
       * This method is the wrapper version of `_.reverse`.
       *
       * **Note:** This method mutates the wrapped array.
       *
       * @name reverse
       * @memberOf _
       * @since 0.1.0
       * @category Seq
       * @returns {Object} Returns the new `lodash` wrapper instance.
       * @example
       *
       * var array = [1, 2, 3];
       *
       * _(array).reverse().value()
       * // => [3, 2, 1]
       *
       * console.log(array);
       * // => [3, 2, 1]
       */
      function wrapperReverse() {
        var value = this.__wrapped__;
        if (value instanceof LazyWrapper) {
          var wrapped = value;
          if (this.__actions__.length) {
            wrapped = new LazyWrapper(this);
          }
          wrapped = wrapped.reverse();
          wrapped.__actions__.push({
            'func': thru,
            'args': [reverse],
            'thisArg': undefined
          });
          return new LodashWrapper(wrapped, this.__chain__);
        }
        return this.thru(reverse);
      }

      /**
       * The base implementation of methods like `_.xor`, without support for
       * iteratee shorthands, that accepts an array of arrays to inspect.
       *
       * @private
       * @param {Array} arrays The arrays to inspect.
       * @param {Function} [iteratee] The iteratee invoked per element.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of values.
       */
      function baseXor(arrays, iteratee, comparator) {
        var length = arrays.length;
        if (length < 2) {
          return length ? baseUniq(arrays[0]) : [];
        }
        var index = -1,
          result = Array(length);
        while (++index < length) {
          var array = arrays[index],
            othIndex = -1;
          while (++othIndex < length) {
            if (othIndex != index) {
              result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
            }
          }
        }
        return baseUniq(baseFlatten(result, 1), iteratee, comparator);
      }

      /**
       * Creates an array of unique values that is the
       * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
       * of the given arrays. The order of result values is determined by the order
       * they occur in the arrays.
       *
       * @static
       * @memberOf _
       * @since 2.4.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @returns {Array} Returns the new array of filtered values.
       * @see _.difference, _.without
       * @example
       *
       * _.xor([2, 1], [2, 3]);
       * // => [1, 3]
       */
      var xor = baseRest(function (arrays) {
        return baseXor(arrayFilter(arrays, isArrayLikeObject));
      });

      /**
       * This method is like `_.xor` except that it accepts `iteratee` which is
       * invoked for each element of each `arrays` to generate the criterion by
       * which by which they're compared. The order of result values is determined
       * by the order they occur in the arrays. The iteratee is invoked with one
       * argument: (value).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
       * @returns {Array} Returns the new array of filtered values.
       * @example
       *
       * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
       * // => [1.2, 3.4]
       *
       * // The `_.property` iteratee shorthand.
       * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
       * // => [{ 'x': 2 }]
       */
      var xorBy = baseRest(function (arrays) {
        var iteratee = last(arrays);
        if (isArrayLikeObject(iteratee)) {
          iteratee = undefined;
        }
        return baseXor(arrayFilter(arrays, isArrayLikeObject), baseIteratee(iteratee));
      });

      /**
       * This method is like `_.xor` except that it accepts `comparator` which is
       * invoked to compare elements of `arrays`. The order of result values is
       * determined by the order they occur in the arrays. The comparator is invoked
       * with two arguments: (arrVal, othVal).
       *
       * @static
       * @memberOf _
       * @since 4.0.0
       * @category Array
       * @param {...Array} [arrays] The arrays to inspect.
       * @param {Function} [comparator] The comparator invoked per element.
       * @returns {Array} Returns the new array of filtered values.
       * @example
       *
       * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
       * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
       *
       * _.xorWith(objects, others, _.isEqual);
       * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
       */
      var xorWith = baseRest(function (arrays) {
        var comparator = last(arrays);
        comparator = typeof comparator == 'function' ? comparator : undefined;
        return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
      });

      /**
       * Creates an array of grouped elements, the first of which contains the
       * first elements of the given arrays, the second of which contains the
       * second elements of the given arrays, and so on.
       *
       * @static
       * @memberOf _
       * @since 0.1.0
       * @category Array
       * @param {...Array} [arrays] The arrays to process.
       * @returns {Array} Returns the new array of grouped elements.
       * @example
       *
       * _.zip(['a', 'b'], [1, 2], [true, false]);
       * // => [['a', 1, true], ['b', 2, false]]
       */
      var zip = baseRest(unzip);

      /**
       * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
       *
       * @private
       * @param {Array} props The property identifiers.
       * @param {Array} values The property values.
       * @param {Function} assignFunc The function to assign values.
       * @returns {Object} Returns the new object.
       */
      function baseZipObject(props, values, assignFunc) {
        var index = -1,
          length = props.length,
          valsLength = values.length,
          result = {};
        while (++index < length) {
          var value = index < valsLength ? values[index] : undefined;
          assignFunc(result, props[index], value);
        }
        return result;
      }

      /**
       * This method is like `_.fromPairs` except that it accepts two arrays,
       * one of property identifiers and one of corresponding values.
       *
       * @static
       * @memberOf _
       * @since 0.4.0
       * @category Array
       * @param {Array} [props=[]] The property identifiers.
       * @param {Array} [values=[]] The property values.
       * @returns {Object} Returns the new object.
       * @example
       *
       * _.zipObject(['a', 'b'], [1, 2]);
       * // => { 'a': 1, 'b': 2 }
       */
      function zipObject(props, values) {
        return baseZipObject(props || [], values || [], assignValue);
      }

      /**
       * This method is like `_.zipObject` except that it supports property paths.
       *
       * @static
       * @memberOf _
       * @since 4.1.0
       * @category Array
       * @param {Array} [props=[]] The property identifiers.
       * @param {Array} [values=[]] The property values.
       * @returns {Object} Returns the new object.
       * @example
       *
       * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
       * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
       */
      function zipObjectDeep(props, values) {
        return baseZipObject(props || [], values || [], baseSet);
      }

      /**
       * This method is like `_.zip` except that it accepts `iteratee` to specify
       * how grouped values should be combined. The iteratee is invoked with the
       * elements of each group: (...group).
       *
       * @static
       * @memberOf _
       * @since 3.8.0
       * @category Array
       * @param {...Array} [arrays] The arrays to process.
       * @param {Function} [iteratee=_.identity] The function to combine
       *  grouped values.
       * @returns {Array} Returns the new array of grouped elements.
       * @example
       *
       * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
       *   return a + b + c;
       * });
       * // => [111, 222]
       */
      var zipWith = baseRest(function (arrays) {
        var length = arrays.length,
          iteratee = length > 1 ? arrays[length - 1] : undefined;
        iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
        return unzipWith(arrays, iteratee);
      });
      var array = {
        chunk: chunk,
        compact: compact,
        concat: concat,
        difference: difference,
        differenceBy: differenceBy,
        differenceWith: differenceWith,
        drop: drop,
        dropRight: dropRight,
        dropRightWhile: dropRightWhile,
        dropWhile: dropWhile,
        fill: fill,
        findIndex: findIndex,
        findLastIndex: findLastIndex,
        first: head,
        flatten: flatten,
        flattenDeep: flattenDeep,
        flattenDepth: flattenDepth,
        fromPairs: fromPairs,
        head: head,
        indexOf: indexOf,
        initial: initial,
        intersection: intersection,
        intersectionBy: intersectionBy,
        intersectionWith: intersectionWith,
        join: join,
        last: last,
        lastIndexOf: lastIndexOf,
        nth: nth,
        pull: pull,
        pullAll: pullAll,
        pullAllBy: pullAllBy,
        pullAllWith: pullAllWith,
        pullAt: pullAt,
        remove: remove,
        reverse: reverse,
        slice: slice,
        sortedIndex: sortedIndex,
        sortedIndexBy: sortedIndexBy,
        sortedIndexOf: sortedIndexOf,
        sortedLastIndex: sortedLastIndex,
        sortedLastIndexBy: sortedLastIndexBy,
        sortedLastIndexOf: sortedLastIndexOf,
        sortedUniq: sortedUniq,
        sortedUniqBy: sortedUniqBy,
        tail: tail,
        take: take,
        takeRight: takeRight,
        takeRightWhile: takeRightWhile,
        takeWhile: takeWhile,
        union: union,
        unionBy: unionBy,
        unionWith: unionWith,
        uniq: uniq,
        uniqBy: uniqBy,
        uniqWith: uniqWith,
        unzip: unzip,
        unzipWith: unzipWith,
        without: without,
        xor: xor,
        xorBy: xorBy,
        xorWith: xorWith,
        zip: zip,
        zipObject: zipObject,
        zipObjectDeep: zipObjectDeep,
        zipWith: zipWith
      };
      var collection = {
        countBy: countBy,
        each: forEach,
        eachRight: forEachRight,
        every: every,
        filter: filter,
        find: find,
        findLast: findLast,
        flatMap: flatMap,
        flatMapDeep: flatMapDeep,
        flatMapDepth: flatMapDepth,
        forEach: forEach,
        forEachRight: forEachRight,
        groupBy: groupBy,
        includes: includes,
        invokeMap: invokeMap,
        keyBy: keyBy,
        map: map,
        orderBy: orderBy,
        partition: partition,
        reduce: reduce,
        reduceRight: reduceRight,
        reject: reject,
        sample: sample,
        sampleSize: sampleSize,
        shuffle: shuffle,
        size: size,
        some: some,
        sortBy: sortBy
      };
      var date = {
        now: now
      };
      var func = {
        after: after,
        ary: ary,
        before: before,
        bind: bind,
        bindKey: bindKey,
        curry: curry,
        curryRight: curryRight,
        debounce: debounce,
        defer: defer,
        delay: delay,
        flip: flip,
        memoize: memoize,
        negate: negate,
        once: once,
        overArgs: overArgs,
        partial: partial,
        partialRight: partialRight,
        rearg: rearg,
        rest: rest,
        spread: spread,
        throttle: throttle,
        unary: unary,
        wrap: wrap
      };
      var lang = {
        castArray: castArray,
        clone: clone,
        cloneDeep: cloneDeep,
        cloneDeepWith: cloneDeepWith,
        cloneWith: cloneWith,
        conformsTo: conformsTo,
        eq: eq,
        gt: gt,
        gte: gte,
        isArguments: isArguments,
        isArray: isArray$1,
        isArrayBuffer: isArrayBuffer,
        isArrayLike: isArrayLike,
        isArrayLikeObject: isArrayLikeObject,
        isBoolean: isBoolean,
        isBuffer: isBuffer,
        isDate: isDate,
        isElement: isElement,
        isEmpty: isEmpty,
        isEqual: isEqual,
        isEqualWith: isEqualWith,
        isError: isError,
        isFinite: isFinite$1,
        isFunction: isFunction,
        isInteger: isInteger,
        isLength: isLength,
        isMap: isMap,
        isMatch: isMatch,
        isMatchWith: isMatchWith,
        isNaN: isNaN,
        isNative: isNative,
        isNil: isNil,
        isNull: isNull,
        isNumber: isNumber,
        isObject: isObject,
        isObjectLike: isObjectLike,
        isPlainObject: isPlainObject,
        isRegExp: isRegExp,
        isSafeInteger: isSafeInteger,
        isSet: isSet,
        isString: isString,
        isSymbol: isSymbol,
        isTypedArray: isTypedArray,
        isUndefined: isUndefined,
        isWeakMap: isWeakMap,
        isWeakSet: isWeakSet,
        lt: lt,
        lte: lte,
        toArray: toArray$1,
        toFinite: toFinite,
        toInteger: toInteger,
        toLength: toLength,
        toNumber: toNumber,
        toPlainObject: toPlainObject,
        toSafeInteger: toSafeInteger,
        toString: toString
      };
      var math = {
        add: add,
        ceil: ceil,
        divide: divide,
        floor: floor,
        max: max,
        maxBy: maxBy,
        mean: mean,
        meanBy: meanBy,
        min: min,
        minBy: minBy,
        multiply: multiply,
        round: round,
        subtract: subtract,
        sum: sum,
        sumBy: sumBy
      };
      var number = {
        clamp: clamp,
        inRange: inRange,
        random: random
      };
      var object = {
        assign: assign$1,
        assignIn: assignIn,
        assignInWith: assignInWith,
        assignWith: assignWith,
        at: at,
        create: create,
        defaults: defaults,
        defaultsDeep: defaultsDeep,
        entries: toPairs,
        entriesIn: toPairsIn,
        extend: assignIn,
        extendWith: assignInWith,
        findKey: findKey,
        findLastKey: findLastKey,
        forIn: forIn,
        forInRight: forInRight,
        forOwn: forOwn,
        forOwnRight: forOwnRight,
        functions: functions,
        functionsIn: functionsIn,
        get: get,
        has: has,
        hasIn: hasIn,
        invert: invert,
        invertBy: invertBy,
        invoke: invoke,
        keys: keys,
        keysIn: keysIn,
        mapKeys: mapKeys,
        mapValues: mapValues$1,
        merge: merge,
        mergeWith: mergeWith,
        omit: omit,
        omitBy: omitBy,
        pick: pick,
        pickBy: pickBy,
        result: result,
        set: set,
        setWith: setWith,
        toPairs: toPairs,
        toPairsIn: toPairsIn,
        transform: transform,
        unset: unset,
        update: update,
        updateWith: updateWith,
        values: values,
        valuesIn: valuesIn
      };
      var seq = {
        at: wrapperAt,
        chain: chain,
        commit: wrapperCommit,
        lodash: lodash,
        next: wrapperNext,
        plant: wrapperPlant,
        reverse: wrapperReverse,
        tap: tap,
        thru: thru,
        toIterator: wrapperToIterator,
        toJSON: wrapperValue,
        value: wrapperValue,
        valueOf: wrapperValue,
        wrapperChain: wrapperChain
      };
      var string = {
        camelCase: camelCase,
        capitalize: capitalize,
        deburr: deburr,
        endsWith: endsWith,
        escape: escape,
        escapeRegExp: escapeRegExp,
        kebabCase: kebabCase,
        lowerCase: lowerCase,
        lowerFirst: lowerFirst,
        pad: pad,
        padEnd: padEnd,
        padStart: padStart,
        parseInt: parseInt$1,
        repeat: repeat,
        replace: replace,
        snakeCase: snakeCase,
        split: split,
        startCase: startCase,
        startsWith: startsWith,
        template: template,
        templateSettings: templateSettings,
        toLower: toLower,
        toUpper: toUpper,
        trim: trim,
        trimEnd: trimEnd,
        trimStart: trimStart,
        truncate: truncate,
        unescape: unescape,
        upperCase: upperCase,
        upperFirst: upperFirst,
        words: words
      };
      var util = {
        attempt: attempt,
        bindAll: bindAll,
        cond: cond,
        conforms: conforms,
        constant: constant,
        defaultTo: defaultTo,
        flow: flow,
        flowRight: flowRight,
        identity: identity,
        iteratee: iteratee,
        matches: matches,
        matchesProperty: matchesProperty,
        method: method,
        methodOf: methodOf,
        mixin: mixin,
        noop: noop,
        nthArg: nthArg,
        over: over,
        overEvery: overEvery,
        overSome: overSome,
        property: property,
        propertyOf: propertyOf,
        range: range,
        rangeRight: rangeRight,
        stubArray: stubArray,
        stubFalse: stubFalse,
        stubObject: stubObject,
        stubString: stubString,
        stubTrue: stubTrue,
        times: times,
        toPath: toPath,
        uniqueId: uniqueId
      };

      /**
       * Creates a clone of the lazy wrapper object.
       *
       * @private
       * @name clone
       * @memberOf LazyWrapper
       * @returns {Object} Returns the cloned `LazyWrapper` object.
       */
      function lazyClone() {
        var result = new LazyWrapper(this.__wrapped__);
        result.__actions__ = copyArray(this.__actions__);
        result.__dir__ = this.__dir__;
        result.__filtered__ = this.__filtered__;
        result.__iteratees__ = copyArray(this.__iteratees__);
        result.__takeCount__ = this.__takeCount__;
        result.__views__ = copyArray(this.__views__);
        return result;
      }

      /**
       * Reverses the direction of lazy iteration.
       *
       * @private
       * @name reverse
       * @memberOf LazyWrapper
       * @returns {Object} Returns the new reversed `LazyWrapper` object.
       */
      function lazyReverse() {
        if (this.__filtered__) {
          var result = new LazyWrapper(this);
          result.__dir__ = -1;
          result.__filtered__ = true;
        } else {
          result = this.clone();
          result.__dir__ *= -1;
        }
        return result;
      }

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$f = Math.max,
        nativeMin$c = Math.min;

      /**
       * Gets the view, applying any `transforms` to the `start` and `end` positions.
       *
       * @private
       * @param {number} start The start of the view.
       * @param {number} end The end of the view.
       * @param {Array} transforms The transformations to apply to the view.
       * @returns {Object} Returns an object containing the `start` and `end`
       *  positions of the view.
       */
      function getView(start, end, transforms) {
        var index = -1,
          length = transforms.length;
        while (++index < length) {
          var data = transforms[index],
            size = data.size;
          switch (data.type) {
            case 'drop':
              start += size;
              break;
            case 'dropRight':
              end -= size;
              break;
            case 'take':
              end = nativeMin$c(end, start + size);
              break;
            case 'takeRight':
              start = nativeMax$f(start, end - size);
              break;
          }
        }
        return {
          'start': start,
          'end': end
        };
      }

      /** Used to indicate the type of lazy iteratees. */
      var LAZY_FILTER_FLAG = 1,
        LAZY_MAP_FLAG = 2;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMin$d = Math.min;

      /**
       * Extracts the unwrapped value from its lazy wrapper.
       *
       * @private
       * @name value
       * @memberOf LazyWrapper
       * @returns {*} Returns the unwrapped value.
       */
      function lazyValue() {
        var array = this.__wrapped__.value(),
          dir = this.__dir__,
          isArr = isArray$1(array),
          isRight = dir < 0,
          arrLength = isArr ? array.length : 0,
          view = getView(0, arrLength, this.__views__),
          start = view.start,
          end = view.end,
          length = end - start,
          index = isRight ? end : start - 1,
          iteratees = this.__iteratees__,
          iterLength = iteratees.length,
          resIndex = 0,
          takeCount = nativeMin$d(length, this.__takeCount__);
        if (!isArr || !isRight && arrLength == length && takeCount == length) {
          return baseWrapperValue(array, this.__actions__);
        }
        var result = [];
        outer: while (length-- && resIndex < takeCount) {
          index += dir;
          var iterIndex = -1,
            value = array[index];
          while (++iterIndex < iterLength) {
            var data = iteratees[iterIndex],
              iteratee = data.iteratee,
              type = data.type,
              computed = iteratee(value);
            if (type == LAZY_MAP_FLAG) {
              value = computed;
            } else if (!computed) {
              if (type == LAZY_FILTER_FLAG) {
                continue outer;
              } else {
                break outer;
              }
            }
          }
          result[resIndex++] = value;
        }
        return result;
      }

      /**
       * @license
       * Lodash (Custom Build) <https://lodash.com/>
       * Build: `lodash modularize exports="es" -o ./`
       * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
       * Released under MIT license <https://lodash.com/license>
       * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
       * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
       */

      /** Used as the semantic version number. */
      var VERSION = '4.17.21';

      /** Used to compose bitmasks for function metadata. */
      var WRAP_BIND_KEY_FLAG$6 = 2;

      /** Used to indicate the type of lazy iteratees. */
      var LAZY_FILTER_FLAG$1 = 1,
        LAZY_WHILE_FLAG = 3;

      /** Used as references for the maximum length and index of an array. */
      var MAX_ARRAY_LENGTH$6 = 4294967295;

      /** Used for built-in method references. */
      var arrayProto$5 = Array.prototype,
        objectProto$s = Object.prototype;

      /** Used to check objects for own properties. */
      var hasOwnProperty$o = objectProto$s.hasOwnProperty;

      /** Built-in value references. */
      var symIterator$1 = Symbol$1 ? Symbol$1.iterator : undefined;

      /* Built-in method references for those with the same name as other `lodash` methods. */
      var nativeMax$g = Math.max,
        nativeMin$e = Math.min;

      // wrap `_.mixin` so it works when provided only one argument
      var mixin$1 = function (func) {
        return function (object, source, options) {
          if (options == null) {
            var isObj = isObject(source),
              props = isObj && keys(source),
              methodNames = props && props.length && baseFunctions(source, props);
            if (!(methodNames ? methodNames.length : isObj)) {
              options = source;
              source = object;
              object = this;
            }
          }
          return func(object, source, options);
        };
      }(mixin);

      // Add methods that return wrapped values in chain sequences.
      lodash.after = func.after;
      lodash.ary = func.ary;
      lodash.assign = object.assign;
      lodash.assignIn = object.assignIn;
      lodash.assignInWith = object.assignInWith;
      lodash.assignWith = object.assignWith;
      lodash.at = object.at;
      lodash.before = func.before;
      lodash.bind = func.bind;
      lodash.bindAll = util.bindAll;
      lodash.bindKey = func.bindKey;
      lodash.castArray = lang.castArray;
      lodash.chain = seq.chain;
      lodash.chunk = array.chunk;
      lodash.compact = array.compact;
      lodash.concat = array.concat;
      lodash.cond = util.cond;
      lodash.conforms = util.conforms;
      lodash.constant = util.constant;
      lodash.countBy = collection.countBy;
      lodash.create = object.create;
      lodash.curry = func.curry;
      lodash.curryRight = func.curryRight;
      lodash.debounce = func.debounce;
      lodash.defaults = object.defaults;
      lodash.defaultsDeep = object.defaultsDeep;
      lodash.defer = func.defer;
      lodash.delay = func.delay;
      lodash.difference = array.difference;
      lodash.differenceBy = array.differenceBy;
      lodash.differenceWith = array.differenceWith;
      lodash.drop = array.drop;
      lodash.dropRight = array.dropRight;
      lodash.dropRightWhile = array.dropRightWhile;
      lodash.dropWhile = array.dropWhile;
      lodash.fill = array.fill;
      lodash.filter = collection.filter;
      lodash.flatMap = collection.flatMap;
      lodash.flatMapDeep = collection.flatMapDeep;
      lodash.flatMapDepth = collection.flatMapDepth;
      lodash.flatten = array.flatten;
      lodash.flattenDeep = array.flattenDeep;
      lodash.flattenDepth = array.flattenDepth;
      lodash.flip = func.flip;
      lodash.flow = util.flow;
      lodash.flowRight = util.flowRight;
      lodash.fromPairs = array.fromPairs;
      lodash.functions = object.functions;
      lodash.functionsIn = object.functionsIn;
      lodash.groupBy = collection.groupBy;
      lodash.initial = array.initial;
      lodash.intersection = array.intersection;
      lodash.intersectionBy = array.intersectionBy;
      lodash.intersectionWith = array.intersectionWith;
      lodash.invert = object.invert;
      lodash.invertBy = object.invertBy;
      lodash.invokeMap = collection.invokeMap;
      lodash.iteratee = util.iteratee;
      lodash.keyBy = collection.keyBy;
      lodash.keys = keys;
      lodash.keysIn = object.keysIn;
      lodash.map = collection.map;
      lodash.mapKeys = object.mapKeys;
      lodash.mapValues = object.mapValues;
      lodash.matches = util.matches;
      lodash.matchesProperty = util.matchesProperty;
      lodash.memoize = func.memoize;
      lodash.merge = object.merge;
      lodash.mergeWith = object.mergeWith;
      lodash.method = util.method;
      lodash.methodOf = util.methodOf;
      lodash.mixin = mixin$1;
      lodash.negate = negate;
      lodash.nthArg = util.nthArg;
      lodash.omit = object.omit;
      lodash.omitBy = object.omitBy;
      lodash.once = func.once;
      lodash.orderBy = collection.orderBy;
      lodash.over = util.over;
      lodash.overArgs = func.overArgs;
      lodash.overEvery = util.overEvery;
      lodash.overSome = util.overSome;
      lodash.partial = func.partial;
      lodash.partialRight = func.partialRight;
      lodash.partition = collection.partition;
      lodash.pick = object.pick;
      lodash.pickBy = object.pickBy;
      lodash.property = util.property;
      lodash.propertyOf = util.propertyOf;
      lodash.pull = array.pull;
      lodash.pullAll = array.pullAll;
      lodash.pullAllBy = array.pullAllBy;
      lodash.pullAllWith = array.pullAllWith;
      lodash.pullAt = array.pullAt;
      lodash.range = util.range;
      lodash.rangeRight = util.rangeRight;
      lodash.rearg = func.rearg;
      lodash.reject = collection.reject;
      lodash.remove = array.remove;
      lodash.rest = func.rest;
      lodash.reverse = array.reverse;
      lodash.sampleSize = collection.sampleSize;
      lodash.set = object.set;
      lodash.setWith = object.setWith;
      lodash.shuffle = collection.shuffle;
      lodash.slice = array.slice;
      lodash.sortBy = collection.sortBy;
      lodash.sortedUniq = array.sortedUniq;
      lodash.sortedUniqBy = array.sortedUniqBy;
      lodash.split = string.split;
      lodash.spread = func.spread;
      lodash.tail = array.tail;
      lodash.take = array.take;
      lodash.takeRight = array.takeRight;
      lodash.takeRightWhile = array.takeRightWhile;
      lodash.takeWhile = array.takeWhile;
      lodash.tap = seq.tap;
      lodash.throttle = func.throttle;
      lodash.thru = thru;
      lodash.toArray = lang.toArray;
      lodash.toPairs = object.toPairs;
      lodash.toPairsIn = object.toPairsIn;
      lodash.toPath = util.toPath;
      lodash.toPlainObject = lang.toPlainObject;
      lodash.transform = object.transform;
      lodash.unary = func.unary;
      lodash.union = array.union;
      lodash.unionBy = array.unionBy;
      lodash.unionWith = array.unionWith;
      lodash.uniq = array.uniq;
      lodash.uniqBy = array.uniqBy;
      lodash.uniqWith = array.uniqWith;
      lodash.unset = object.unset;
      lodash.unzip = array.unzip;
      lodash.unzipWith = array.unzipWith;
      lodash.update = object.update;
      lodash.updateWith = object.updateWith;
      lodash.values = object.values;
      lodash.valuesIn = object.valuesIn;
      lodash.without = array.without;
      lodash.words = string.words;
      lodash.wrap = func.wrap;
      lodash.xor = array.xor;
      lodash.xorBy = array.xorBy;
      lodash.xorWith = array.xorWith;
      lodash.zip = array.zip;
      lodash.zipObject = array.zipObject;
      lodash.zipObjectDeep = array.zipObjectDeep;
      lodash.zipWith = array.zipWith;

      // Add aliases.
      lodash.entries = object.toPairs;
      lodash.entriesIn = object.toPairsIn;
      lodash.extend = object.assignIn;
      lodash.extendWith = object.assignInWith;

      // Add methods to `lodash.prototype`.
      mixin$1(lodash, lodash);

      // Add methods that return unwrapped values in chain sequences.
      lodash.add = math.add;
      lodash.attempt = util.attempt;
      lodash.camelCase = string.camelCase;
      lodash.capitalize = string.capitalize;
      lodash.ceil = math.ceil;
      lodash.clamp = number.clamp;
      lodash.clone = lang.clone;
      lodash.cloneDeep = lang.cloneDeep;
      lodash.cloneDeepWith = lang.cloneDeepWith;
      lodash.cloneWith = lang.cloneWith;
      lodash.conformsTo = lang.conformsTo;
      lodash.deburr = string.deburr;
      lodash.defaultTo = util.defaultTo;
      lodash.divide = math.divide;
      lodash.endsWith = string.endsWith;
      lodash.eq = lang.eq;
      lodash.escape = string.escape;
      lodash.escapeRegExp = string.escapeRegExp;
      lodash.every = collection.every;
      lodash.find = collection.find;
      lodash.findIndex = array.findIndex;
      lodash.findKey = object.findKey;
      lodash.findLast = collection.findLast;
      lodash.findLastIndex = array.findLastIndex;
      lodash.findLastKey = object.findLastKey;
      lodash.floor = math.floor;
      lodash.forEach = collection.forEach;
      lodash.forEachRight = collection.forEachRight;
      lodash.forIn = object.forIn;
      lodash.forInRight = object.forInRight;
      lodash.forOwn = object.forOwn;
      lodash.forOwnRight = object.forOwnRight;
      lodash.get = object.get;
      lodash.gt = lang.gt;
      lodash.gte = lang.gte;
      lodash.has = object.has;
      lodash.hasIn = object.hasIn;
      lodash.head = array.head;
      lodash.identity = identity;
      lodash.includes = collection.includes;
      lodash.indexOf = array.indexOf;
      lodash.inRange = number.inRange;
      lodash.invoke = object.invoke;
      lodash.isArguments = lang.isArguments;
      lodash.isArray = isArray$1;
      lodash.isArrayBuffer = lang.isArrayBuffer;
      lodash.isArrayLike = lang.isArrayLike;
      lodash.isArrayLikeObject = lang.isArrayLikeObject;
      lodash.isBoolean = lang.isBoolean;
      lodash.isBuffer = lang.isBuffer;
      lodash.isDate = lang.isDate;
      lodash.isElement = lang.isElement;
      lodash.isEmpty = lang.isEmpty;
      lodash.isEqual = lang.isEqual;
      lodash.isEqualWith = lang.isEqualWith;
      lodash.isError = lang.isError;
      lodash.isFinite = lang.isFinite;
      lodash.isFunction = lang.isFunction;
      lodash.isInteger = lang.isInteger;
      lodash.isLength = lang.isLength;
      lodash.isMap = lang.isMap;
      lodash.isMatch = lang.isMatch;
      lodash.isMatchWith = lang.isMatchWith;
      lodash.isNaN = lang.isNaN;
      lodash.isNative = lang.isNative;
      lodash.isNil = lang.isNil;
      lodash.isNull = lang.isNull;
      lodash.isNumber = lang.isNumber;
      lodash.isObject = isObject;
      lodash.isObjectLike = lang.isObjectLike;
      lodash.isPlainObject = lang.isPlainObject;
      lodash.isRegExp = lang.isRegExp;
      lodash.isSafeInteger = lang.isSafeInteger;
      lodash.isSet = lang.isSet;
      lodash.isString = lang.isString;
      lodash.isSymbol = lang.isSymbol;
      lodash.isTypedArray = lang.isTypedArray;
      lodash.isUndefined = lang.isUndefined;
      lodash.isWeakMap = lang.isWeakMap;
      lodash.isWeakSet = lang.isWeakSet;
      lodash.join = array.join;
      lodash.kebabCase = string.kebabCase;
      lodash.last = last;
      lodash.lastIndexOf = array.lastIndexOf;
      lodash.lowerCase = string.lowerCase;
      lodash.lowerFirst = string.lowerFirst;
      lodash.lt = lang.lt;
      lodash.lte = lang.lte;
      lodash.max = math.max;
      lodash.maxBy = math.maxBy;
      lodash.mean = math.mean;
      lodash.meanBy = math.meanBy;
      lodash.min = math.min;
      lodash.minBy = math.minBy;
      lodash.stubArray = util.stubArray;
      lodash.stubFalse = util.stubFalse;
      lodash.stubObject = util.stubObject;
      lodash.stubString = util.stubString;
      lodash.stubTrue = util.stubTrue;
      lodash.multiply = math.multiply;
      lodash.nth = array.nth;
      lodash.noop = util.noop;
      lodash.now = date.now;
      lodash.pad = string.pad;
      lodash.padEnd = string.padEnd;
      lodash.padStart = string.padStart;
      lodash.parseInt = string.parseInt;
      lodash.random = number.random;
      lodash.reduce = collection.reduce;
      lodash.reduceRight = collection.reduceRight;
      lodash.repeat = string.repeat;
      lodash.replace = string.replace;
      lodash.result = object.result;
      lodash.round = math.round;
      lodash.sample = collection.sample;
      lodash.size = collection.size;
      lodash.snakeCase = string.snakeCase;
      lodash.some = collection.some;
      lodash.sortedIndex = array.sortedIndex;
      lodash.sortedIndexBy = array.sortedIndexBy;
      lodash.sortedIndexOf = array.sortedIndexOf;
      lodash.sortedLastIndex = array.sortedLastIndex;
      lodash.sortedLastIndexBy = array.sortedLastIndexBy;
      lodash.sortedLastIndexOf = array.sortedLastIndexOf;
      lodash.startCase = string.startCase;
      lodash.startsWith = string.startsWith;
      lodash.subtract = math.subtract;
      lodash.sum = math.sum;
      lodash.sumBy = math.sumBy;
      lodash.template = string.template;
      lodash.times = util.times;
      lodash.toFinite = lang.toFinite;
      lodash.toInteger = toInteger;
      lodash.toLength = lang.toLength;
      lodash.toLower = string.toLower;
      lodash.toNumber = lang.toNumber;
      lodash.toSafeInteger = lang.toSafeInteger;
      lodash.toString = lang.toString;
      lodash.toUpper = string.toUpper;
      lodash.trim = string.trim;
      lodash.trimEnd = string.trimEnd;
      lodash.trimStart = string.trimStart;
      lodash.truncate = string.truncate;
      lodash.unescape = string.unescape;
      lodash.uniqueId = util.uniqueId;
      lodash.upperCase = string.upperCase;
      lodash.upperFirst = string.upperFirst;

      // Add aliases.
      lodash.each = collection.forEach;
      lodash.eachRight = collection.forEachRight;
      lodash.first = array.head;
      mixin$1(lodash, function () {
        var source = {};
        baseForOwn(lodash, function (func, methodName) {
          if (!hasOwnProperty$o.call(lodash.prototype, methodName)) {
            source[methodName] = func;
          }
        });
        return source;
      }(), {
        'chain': false
      });

      /**
       * The semantic version number.
       *
       * @static
       * @memberOf _
       * @type {string}
       */
      lodash.VERSION = VERSION;
      (lodash.templateSettings = string.templateSettings).imports._ = lodash;

      // Assign default placeholders.
      arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function (methodName) {
        lodash[methodName].placeholder = lodash;
      });

      // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
      arrayEach(['drop', 'take'], function (methodName, index) {
        LazyWrapper.prototype[methodName] = function (n) {
          n = n === undefined ? 1 : nativeMax$g(toInteger(n), 0);
          var result = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone();
          if (result.__filtered__) {
            result.__takeCount__ = nativeMin$e(n, result.__takeCount__);
          } else {
            result.__views__.push({
              'size': nativeMin$e(n, MAX_ARRAY_LENGTH$6),
              'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
            });
          }
          return result;
        };
        LazyWrapper.prototype[methodName + 'Right'] = function (n) {
          return this.reverse()[methodName](n).reverse();
        };
      });

      // Add `LazyWrapper` methods that accept an `iteratee` value.
      arrayEach(['filter', 'map', 'takeWhile'], function (methodName, index) {
        var type = index + 1,
          isFilter = type == LAZY_FILTER_FLAG$1 || type == LAZY_WHILE_FLAG;
        LazyWrapper.prototype[methodName] = function (iteratee) {
          var result = this.clone();
          result.__iteratees__.push({
            'iteratee': baseIteratee(iteratee),
            'type': type
          });
          result.__filtered__ = result.__filtered__ || isFilter;
          return result;
        };
      });

      // Add `LazyWrapper` methods for `_.head` and `_.last`.
      arrayEach(['head', 'last'], function (methodName, index) {
        var takeName = 'take' + (index ? 'Right' : '');
        LazyWrapper.prototype[methodName] = function () {
          return this[takeName](1).value()[0];
        };
      });

      // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
      arrayEach(['initial', 'tail'], function (methodName, index) {
        var dropName = 'drop' + (index ? '' : 'Right');
        LazyWrapper.prototype[methodName] = function () {
          return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
        };
      });
      LazyWrapper.prototype.compact = function () {
        return this.filter(identity);
      };
      LazyWrapper.prototype.find = function (predicate) {
        return this.filter(predicate).head();
      };
      LazyWrapper.prototype.findLast = function (predicate) {
        return this.reverse().find(predicate);
      };
      LazyWrapper.prototype.invokeMap = baseRest(function (path, args) {
        if (typeof path == 'function') {
          return new LazyWrapper(this);
        }
        return this.map(function (value) {
          return baseInvoke(value, path, args);
        });
      });
      LazyWrapper.prototype.reject = function (predicate) {
        return this.filter(negate(baseIteratee(predicate)));
      };
      LazyWrapper.prototype.slice = function (start, end) {
        start = toInteger(start);
        var result = this;
        if (result.__filtered__ && (start > 0 || end < 0)) {
          return new LazyWrapper(result);
        }
        if (start < 0) {
          result = result.takeRight(-start);
        } else if (start) {
          result = result.drop(start);
        }
        if (end !== undefined) {
          end = toInteger(end);
          result = end < 0 ? result.dropRight(-end) : result.take(end - start);
        }
        return result;
      };
      LazyWrapper.prototype.takeRightWhile = function (predicate) {
        return this.reverse().takeWhile(predicate).reverse();
      };
      LazyWrapper.prototype.toArray = function () {
        return this.take(MAX_ARRAY_LENGTH$6);
      };

      // Add `LazyWrapper` methods to `lodash.prototype`.
      baseForOwn(LazyWrapper.prototype, function (func, methodName) {
        var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
          isTaker = /^(?:head|last)$/.test(methodName),
          lodashFunc = lodash[isTaker ? 'take' + (methodName == 'last' ? 'Right' : '') : methodName],
          retUnwrapped = isTaker || /^find/.test(methodName);
        if (!lodashFunc) {
          return;
        }
        lodash.prototype[methodName] = function () {
          var value = this.__wrapped__,
            args = isTaker ? [1] : arguments,
            isLazy = value instanceof LazyWrapper,
            iteratee = args[0],
            useLazy = isLazy || isArray$1(value);
          var interceptor = function interceptor(value) {
            var result = lodashFunc.apply(lodash, arrayPush([value], args));
            return isTaker && chainAll ? result[0] : result;
          };
          if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
            // Avoid lazy use if the iteratee has a "length" value other than `1`.
            isLazy = useLazy = false;
          }
          var chainAll = this.__chain__,
            isHybrid = !!this.__actions__.length,
            isUnwrapped = retUnwrapped && !chainAll,
            onlyLazy = isLazy && !isHybrid;
          if (!retUnwrapped && useLazy) {
            value = onlyLazy ? value : new LazyWrapper(this);
            var result = func.apply(value, args);
            result.__actions__.push({
              'func': thru,
              'args': [interceptor],
              'thisArg': undefined
            });
            return new LodashWrapper(result, chainAll);
          }
          if (isUnwrapped && onlyLazy) {
            return func.apply(this, args);
          }
          result = this.thru(interceptor);
          return isUnwrapped ? isTaker ? result.value()[0] : result.value() : result;
        };
      });

      // Add `Array` methods to `lodash.prototype`.
      arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function (methodName) {
        var func = arrayProto$5[methodName],
          chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
          retUnwrapped = /^(?:pop|shift)$/.test(methodName);
        lodash.prototype[methodName] = function () {
          var args = arguments;
          if (retUnwrapped && !this.__chain__) {
            var value = this.value();
            return func.apply(isArray$1(value) ? value : [], args);
          }
          return this[chainName](function (value) {
            return func.apply(isArray$1(value) ? value : [], args);
          });
        };
      });

      // Map minified method names to their real names.
      baseForOwn(LazyWrapper.prototype, function (func, methodName) {
        var lodashFunc = lodash[methodName];
        if (lodashFunc) {
          var key = lodashFunc.name + '';
          if (!hasOwnProperty$o.call(realNames, key)) {
            realNames[key] = [];
          }
          realNames[key].push({
            'name': methodName,
            'func': lodashFunc
          });
        }
      });
      realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG$6).name] = [{
        'name': 'wrapper',
        'func': undefined
      }];

      // Add methods to `LazyWrapper`.
      LazyWrapper.prototype.clone = lazyClone;
      LazyWrapper.prototype.reverse = lazyReverse;
      LazyWrapper.prototype.value = lazyValue;

      // Add chain sequence methods to the `lodash` wrapper.
      lodash.prototype.at = seq.at;
      lodash.prototype.chain = seq.wrapperChain;
      lodash.prototype.commit = seq.commit;
      lodash.prototype.next = seq.next;
      lodash.prototype.plant = seq.plant;
      lodash.prototype.reverse = seq.reverse;
      lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = seq.value;

      // Add lazy aliases.
      lodash.prototype.first = lodash.prototype.head;
      if (symIterator$1) {
        lodash.prototype[symIterator$1] = seq.toIterator;
      }
      var _dec$4, _dec2$4, _dec3$4, _class$5;
      cclegacy._RF.push({}, "d6027gM+nZPzZKrK13xWdXk", "KeyInputManager", undefined);
      var ccclass$4 = _decorator.ccclass,
        menu$4 = _decorator.menu,
        disallowMultiple$4 = _decorator.disallowMultiple;

      // 枚举工具确保反向映射存在
      Enum(KeyCode);

      /**
       * 按键事件回调函数类型
       */

      /**
       * 按键监听器
       */

      // 1. 获取所有枚举的数值（过滤反向映射的字符串）
      var allKeyCodes = Object.values(KeyCode).filter(function (value) {
        return typeof value === 'number';
      });
      var log$1 = new LogBuilder();

      /**
       * 按键事件监听管理器
       * 提供对特定按键的监听功能，作为事件总线触发监听特定按键的事件
       */
      var KeyInputManager = (_dec$4 = ccclass$4('KeyInputManager'), _dec2$4 = menu$4('Utils/KeyInputManager'), _dec3$4 = disallowMultiple$4(true), _dec$4(_class$5 = _dec2$4(_class$5 = _dec3$4(_class$5 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(KeyInputManager, _Component);
        function KeyInputManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          /**
           * 存储按键监听器的映射表
           * key: KeyCode 按键码
           * value: KeyCallback[] 按键回调函数数组
           */
          _this.key_Down_Listeners = new Map(allKeyCodes.map(function (code) {
            return [code, new Map()];
          }));
          _this.key_Up_Listeners = new Map(allKeyCodes.map(function (code) {
            return [code, new Map()];
          }));
          _this.listeners = {
            down: _this.key_Down_Listeners,
            up: _this.key_Up_Listeners
          };
          // 添加成员变量
          _this._downHandler = void 0;
          _this._upHandler = void 0;
          return _this;
        }
        var _proto = KeyInputManager.prototype;
        _proto.onLoad = function onLoad() {
          log$1.This(this).Method('onLoad');
          log$1.log('KeyInputManager loaded');
          this._downHandler = this.handleKey(this.key_Down_Listeners, '按下');
          this._upHandler = this.handleKey(this.key_Up_Listeners, '释放');
        };
        _proto.onDestroy = function onDestroy() {
          this.clear();
        };
        _proto.onEnable = function onEnable() {
          // 监听按键按下事件
          input.on(Input.EventType.KEY_DOWN, this._downHandler, this);
          // 监听按键释放事件
          input.on(Input.EventType.KEY_UP, this._upHandler, this);
        };
        _proto.onDisable = function onDisable() {
          input.off(Input.EventType.KEY_DOWN, this._downHandler, this);
          input.off(Input.EventType.KEY_UP, this._upHandler, this);
        }

        /**
         * 监听特定按键按下事件
         * @param keyCode 按键码
         * @param callback 回调函数
         */;
        _proto.onKeyDown = function onKeyDown(keyCode, callback) {
          this.onKey(keyCode, 'down', callback);
        }

        /**
         * 监听特定按键释放事件
         * @param keyCode 按键码
         * @param callback 回调函数
         */;
        _proto.onKeyUp = function onKeyUp(keyCode, callback) {
          this.onKey(keyCode, 'up', callback);
        }

        /**
         * 移除特定按键的按下事件监听器
         * @param keyCode 按键码
         * @param callback 要移除的回调函数（可选，如果不传则移除该按键的所有监听器）
         */;
        _proto.offKeyDown = function offKeyDown(keyCode, callback) {
          this.offKey(keyCode, 'down', callback);
        }

        /**
         * 移除特定按键的释放事件监听器
         * @param keyCode 按键码
         * @param callback 要移除的回调函数（可选，如果不传则移除该按键的所有监听器）
         */;
        _proto.offKeyUp = function offKeyUp(keyCode, callback) {
          this.offKey(keyCode, 'up', callback);
        }

        /**
         * 监听特定按钮事件
         * @param keyCode 按键码
         * @param type 按键类型
         * @param callback 回调函数
         */;
        _proto.onKey = function onKey(keyCode, type, callback) {
          var _this$listeners$type$;
          log$1.Method('onKey').log("\u76D1\u542C\u6309\u952E " + KeyCode[keyCode] + "\u7684" + type + "\u4E8B\u4EF6");
          (_this$listeners$type$ = this.listeners[type].get(keyCode)) == null || _this$listeners$type$.set(callback, callback);
        }

        /**
         * 移除特定按键的按下事件监听器
         * @param keyCode 按键码
         * @param callback 要移除的回调函数（可选，如果不传则移除该按键的所有监听器）
         */;
        _proto.offKey = function offKey(keyCode, type, callback) {
          log$1.Method('offKey');
          if (callback) {
            var _this$listeners$type$2;
            log$1.Method('offKey').log("\u79FB\u9664\u6309\u952E " + KeyCode[keyCode] + "\u7684\u6307\u5B9A" + type + "\u4E8B\u4EF6\u76D1\u542C\u5668");
            (_this$listeners$type$2 = this.listeners[type].get(keyCode)) == null || _this$listeners$type$2.delete(callback);
          } else {
            var _this$listeners$type$3;
            log$1.Method('offKey').log("\u79FB\u9664\u6309\u952E " + KeyCode[keyCode] + "\u7684\u6240\u6709" + type + "\u4E8B\u4EF6\u76D1\u542C\u5668");
            (_this$listeners$type$3 = this.listeners[type].get(keyCode)) == null || _this$listeners$type$3.clear();
          }
        }

        /**
         * 创建按键事件处理器
         * @param listeners 监听器映射表
         * @returns 事件处理器函数
         */;
        _proto.handleKey = function handleKey(listeners, logMsg) {
          if (logMsg === void 0) {
            logMsg = '按下';
          }
          return function (event) {
            log$1.Method('handleKey').log(logMsg + "\u6309\u952E " + KeyCode[event.keyCode]);
            for (var _iterator = _createForOfIteratorHelperLoose(listeners.get(event.keyCode)), _step; !(_step = _iterator()).done;) {
              var _step$value = _step.value,
                value = _step$value[1];
              value(event);
            }
          };
        }

        /**
         * 清理所有监听器
         */;
        _proto.clear = function clear() {
          this.key_Down_Listeners.clear();
          this.key_Up_Listeners.clear();
          input.off(Input.EventType.KEY_DOWN, this._downHandler, this);
          input.off(Input.EventType.KEY_UP, this._upHandler, this);
        };
        return KeyInputManager;
      }(Component)) || _class$5) || _class$5) || _class$5);
      var keyIO = cache$1(function () {
        return find$1('GameManager').getComponent(KeyInputManager);
      });
      cclegacy._RF.pop();
      var _dec$5, _dec2$5, _dec3$5, _class$6;
      cclegacy._RF.push({}, "3f515tG3wVPP5ca65YPOpiP", "MouseInputManager", undefined);
      var ccclass$5 = _decorator.ccclass,
        menu$5 = _decorator.menu,
        disallowMultiple$5 = _decorator.disallowMultiple;
      var mainCameraCmp = cache$1(function () {
        return find$1('Canvas/Camera').getComponent(Camera);
      });

      /**
       * 鼠标事件回调函数类型
       */

      /**
       * 鼠标监听器
       */

      /**
       * 鼠标事件
       */
      var MouseEvent = /*#__PURE__*/function (MouseEvent) {
        MouseEvent["leftMouseDown"] = "leftMouseDown";
        MouseEvent["leftMouseUp"] = "leftMouseUp";
        MouseEvent["rightMouseDown"] = "rightMouseDown";
        MouseEvent["rightMouseUp"] = "rightMouseUp";
        MouseEvent["mouseMove"] = "mouseMove";
        return MouseEvent;
      }({});
      var _tmp_vec3 = new Vec3();

      /**
       * 鼠标事件监听管理器
       * 提供对鼠标左键、右键和移动事件的监听功能，作为事件总线触发监听特定鼠标事件
       */
      var MouseInputManager = (_dec$5 = ccclass$5('MouseInputManager'), _dec2$5 = menu$5('Utils/MouseInputManager'), _dec3$5 = disallowMultiple$5(true), _dec$5(_class$6 = _dec2$5(_class$6 = _dec3$5(_class$6 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MouseInputManager, _Component);
        function MouseInputManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.log = new LogBuilder();
          _this.Listeners = new Map([[MouseEvent.leftMouseDown, new Map()], [MouseEvent.leftMouseUp, new Map()], [MouseEvent.rightMouseDown, new Map()], [MouseEvent.rightMouseUp, new Map()], [MouseEvent.mouseMove, new Map()]]);
          _this.handleMouseUp = function (event) {
            _this.log.Method('handleMouseUp');
            var leftFlag = event.getButton() === EventMouse.BUTTON_LEFT;
            var key = leftFlag ? MouseEvent.leftMouseUp : MouseEvent.rightMouseUp;
            var msgKey = leftFlag ? '左键' : '右键';
            _this.handleAllCallback(key, msgKey, '抬起')(event);
          };
          _this.handleMouseDown = function (event) {
            _this.log.Method('handleMouseDown');
            var leftFlag = event.getButton() === EventMouse.BUTTON_LEFT;
            var key = leftFlag ? MouseEvent.leftMouseDown : MouseEvent.rightMouseDown;
            var msgKey = leftFlag ? '左键' : '右键';
            _this.handleAllCallback(key, msgKey, '按下')(event);
          };
          _this.handleMouseMove = function (event) {
            var _this$Listeners$get;
            return (_this$Listeners$get = _this.Listeners.get(MouseEvent.mouseMove)) == null ? void 0 : _this$Listeners$get.forEach(function (callback) {
              return callback(event);
            });
          };
          // 触发所有的事件
          _this.handleAllCallback = function (type, msgKey, msg2) {
            return function (event) {
              var _this$Listeners$get2;
              _this.log.log("\u89E6\u53D1\u9F20\u6807\u4E8B\u4EF6 " + msgKey + msg2);
              (_this$Listeners$get2 = _this.Listeners.get(type)) == null || _this$Listeners$get2.forEach(function (callback) {
                return callback(event);
              });
            };
          };
          return _this;
        }
        var _proto = MouseInputManager.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this).Method('onLoad').log('MouseInputManager loaded');
        };
        _proto.onEnable = function onEnable() {
          // 注册事件监听
          input.on(Input.EventType.MOUSE_DOWN, this.handleMouseDown, this);
          input.on(Input.EventType.MOUSE_UP, this.handleMouseUp, this);
          input.on(Input.EventType.MOUSE_MOVE, this.handleMouseMove, this);
        };
        _proto.onDisable = function onDisable() {
          // 移除所有事件监听
          input.off(Input.EventType.MOUSE_DOWN, this.handleMouseDown, this);
          input.off(Input.EventType.MOUSE_UP, this.handleMouseUp, this);
          input.off(Input.EventType.MOUSE_MOVE, this.handleMouseMove, this);
        };
        _proto.onDestroy = function onDestroy() {
          this.Listeners.forEach(function (listener) {
            return listener.clear();
          });
          this.Listeners.clear();
        }

        // 注册鼠标事件监听
        ;

        _proto.on = function on(type, callback, thisArg) {
          var _this$Listeners$get3;
          this.log.Method('on').log("\u76D1\u542C\u9F20\u6807\u4E8B\u4EF6 " + MouseEvent[type]);
          (_this$Listeners$get3 = this.Listeners.get(type)) == null || _this$Listeners$get3.set(callback, callback.bind(thisArg));
        }
        // 移除鼠标事件监听
        ;

        _proto.off = function off(type, callback) {
          var _this$Listeners$get4;
          this.log.Method('off').log("\u79FB\u9664\u9F20\u6807\u4E8B\u4EF6 " + MouseEvent[type]);
          (_this$Listeners$get4 = this.Listeners.get(type)) == null || _this$Listeners$get4.delete(callback);
        };
        /**
         * 转换鼠标坐标到世界坐标
         */
        _proto.screenToWorld = function screenToWorld(event) {
          var screenPos = event.getLocation().toVec3();
          mainCameraCmp().screenToWorld(screenPos, _tmp_vec3);
          return _tmp_vec3;
        };
        return MouseInputManager;
      }(Component)) || _class$6) || _class$6) || _class$6);
      var mouseIO = cache$1(function () {
        return find$1('GameManager').getComponent(MouseInputManager);
      });
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "7c13dJhG9JPSpQAJxJX3wMW", "autoEventBind", undefined);

      /**
       * 添加事件监听
       * @param event 事件对象
       * @param eventDict 事件字典
       */
      function addEventListener(event, eventDict) {
        event.on(eventDict.event, eventDict.callback);
      }

      /**
       * 移除事件监听
       * @param event 事件对象
       * @param eventDict 事件字典
       */
      function removeEventListener(event, eventDict) {
        event.off(eventDict.event, eventDict.callback);
      }

      // Game 事件绑定和监听器函数

      function GameListener(fn) {
        return function (binding) {
          fn(gmVar().gameEvent, binding);
        };
      }
      var addGameListener = GameListener(addEventListener);
      var removeGameListener = GameListener(removeEventListener);

      // Player 事件绑定和监听器函数

      function PlayerListener(fn) {
        return function (binding) {
          fn(gmVar().playerEvent, binding);
        };
      }
      var addPlayerListener = PlayerListener(addEventListener);
      var removePlayerListener = PlayerListener(removeEventListener);

      // 鼠标事件绑定和监听器函数

      function addMouseListener(binding) {
        var _mouseIO;
        (_mouseIO = mouseIO()) == null || _mouseIO.on(binding.mouseEvent, binding.callback);
      }
      function removeMouseListener(binding) {
        var _mouseIO2;
        (_mouseIO2 = mouseIO()) == null || _mouseIO2.off(binding.mouseEvent, binding.callback);
      }

      // 键盘事件绑定和监听器函数

      function addKeyListener(binding) {
        var _keyIO;
        (_keyIO = keyIO()) == null || _keyIO.onKeyDown(binding.keyCode, binding.callback);
      }
      function removeKeyListener(binding) {
        var _keyIO2;
        (_keyIO2 = keyIO()) == null || _keyIO2.offKeyDown(binding.keyCode, binding.callback);
      }

      // ==================== Atom 监听相关 ====================

      /**
       * Atom 监听绑定
       */
      /**
       * 添加 Atom 监听
       * @param binding Atom 绑定对象
       * @returns 取消订阅函数
       */
      function addAtomListener(binding) {
        return atomListenerManager.add(binding);
      }

      /**
       * 移除 Atom 监听（实际上只需要调用 subscribe 返回的取消函数）
       * 注意：由于 atom 的 subscribe 方法返回的是取消函数，所以 removeAtomListener
       * 需要保存这些取消函数并在需要时调用它们
       */
      function removeAtomListener(binding) {
        return atomListenerManager.remove(binding);
      }

      // ==================== Atom Map 监听管理 ====================

      /**
       * Atom Map 监听管理器
       * 使用 Map 以回调函数为键，取消订阅函数为值
       */
      var AtomListenerManager = /*#__PURE__*/function () {
        function AtomListenerManager() {
          this.unsubscribes = new Map();
        }
        var _proto = AtomListenerManager.prototype;
        /**
         * 添加 Atom 监听，并将取消函数存入 Map
         * @param binding Atom 绑定对象
         * @returns 回调函数（用于后续取消）
         */
        _proto.add = function add(binding) {
          var unsubscribe = binding.atom().subscribe(binding.callback);
          this.unsubscribes.set(binding.callback, unsubscribe);
          return binding.callback;
        }

        /**
         * 使用回调函数作为键，取出并执行对应的取消函数
         * @param callback 之前添加监听时的回调函数
         */;
        _proto.remove = function remove(binding) {
          var unsubscribe = this.unsubscribes.get(binding.callback);
          if (unsubscribe) {
            unsubscribe();
            this.unsubscribes.delete(binding.callback);
          }
        }

        /**
         * 清除所有监听
         */;
        _proto.clear = function clear() {
          for (var _iterator = _createForOfIteratorHelperLoose(this.unsubscribes.values()), _step; !(_step = _iterator()).done;) {
            var unsubscribe = _step.value;
            unsubscribe();
          }
          this.unsubscribes.clear();
        }

        /**
         * 获取当前监听数量
         */;
        /**
         * 检查是否存在某个回调的监听
         */
        _proto.has = function has(callback) {
          return this.unsubscribes.has(callback);
        };
        _createClass(AtomListenerManager, [{
          key: "size",
          get: function get() {
            return this.unsubscribes.size;
          }
        }]);
        return AtomListenerManager;
      }();
      var atomListenerManager = new AtomListenerManager();

      // ==================== 自动事件监听注册 ====================

      /**
       * 创建自动监听器管理器（高阶函数）
       * @param propertyKey1 findBindings 的第一个属性名
       * @param propertyKey2 findBindings 的第二个属性名
       * @param listenerFunction 当 tag 吻合时调用的函数
       * @returns 返回一个函数，接受 target 和可选的 tag
       */
      function AutoListener(propertyKey1, propertyKey2, listenerFunction) {
        return function (target, tag) {
          var bindings = findBindings(target, propertyKey1, propertyKey2);
          for (var _i = 0, _bindings = bindings; _i < _bindings.length; _i++) {
            var binding = _bindings[_i];
            if (tag === undefined) {
              listenerFunction(binding);
            } else if (typeof tag === 'string') {
              if (binding.tag === tag) {
                listenerFunction(binding);
              }
            } else if (binding.tag !== undefined && tag.test(binding.tag)) {
              listenerFunction(binding);
            }
          }
        };
      }

      // 游戏事件
      var AutoGameListener = function AutoGameListener(fn) {
        return AutoListener('event', 'callback', fn);
      };
      var autoRegisterGameListeners = AutoGameListener(addGameListener);
      var autoUnregisterGameListeners = AutoGameListener(removeGameListener);

      // 按键事件
      var AutoKeyListener = function AutoKeyListener(fn) {
        return AutoListener('keyCode', 'callback', fn);
      };
      var autoRegisterKeyListeners = AutoKeyListener(addKeyListener);
      var autoUnregisterKeyListeners = AutoKeyListener(removeKeyListener);

      // 鼠标事件
      var AutoMouseListener = function AutoMouseListener(fn) {
        return AutoListener('mouseEvent', 'callback', fn);
      };
      var autoRegisterMouseListeners = AutoMouseListener(addMouseListener);
      var autoUnregisterMouseListeners = AutoMouseListener(removeMouseListener);

      // 玩家事件
      var AutoPlayerListener = function AutoPlayerListener(fn) {
        return AutoListener('event', 'callback', fn);
      };
      var autoRegisterPlayerListeners = AutoPlayerListener(addPlayerListener);
      var autoUnregisterPlayerListeners = AutoPlayerListener(removePlayerListener);

      // Atom 事件
      var AutoAtomListener = function AutoAtomListener(fn) {
        return AutoListener('atom', 'callback', fn);
      };
      var autoRegisterAtomListeners = AutoAtomListener(addAtomListener);
      var autoUnregisterAtomListeners = AutoAtomListener(removeAtomListener);

      // ==================== 辅助函数 ====================

      /**
       * 查找对象中所有符合特定结构的事件绑定
       * @param target 目标对象
       * @param requiredProp1 必需属性名1（如 event）
       * @param requiredProp2 必需属性名2（如 callback）
       * @returns 匹配的事件绑定列表
       */
      function findBindings(target, requiredProp1, requiredProp2) {
        var bindings = [];
        for (var key in target) {
          if (Object.prototype.hasOwnProperty.call(target, key)) {
            var value = target[key];
            if (value && typeof value === 'object' && requiredProp1 in value && requiredProp2 in value) {
              bindings.push(value);
            }
          }
        }
        if (bindings.length === 0) {
          logger.warn("\u672A\u5728 " + target + " \u4E2D\u627E\u5230\u7B26\u5408{" + requiredProp1.toString() + ", " + requiredProp2.toString() + "}\u8981\u6C42\u7684\u4E8B\u4EF6\u7ED1\u5B9A");
        }
        return bindings;
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "961d4/F0zVC9K5+8A3cOB2q", "AlwaysUsed", undefined);
      function pOpt1(type, tooltip, id, names) {
        return {
          type: type,
          tooltip: tooltip,
          group: {
            id: id,
            name: id + names
          }
        };
      }
      function pOpt2(tooltip, id, names) {
        return {
          tooltip: tooltip,
          group: {
            id: id,
            name: id + names
          }
        };
      }

      // 缓存变量
      function cache$1(finder) {
        var cacheValue;
        var safeFinder = fromThrowable(finder, function () {});
        return function () {
          var _cacheValue;
          return (_cacheValue = cacheValue) != null ? _cacheValue : cacheValue = safeFinder().unwrapOr(undefined);
        };
      }

      /**
       * 令vec3 转换为限制数字长度的字符串
       */
      function vec3ToString(vec3, precision) {
        if (precision === void 0) {
          precision = 2;
        }
        return "(" + vec3.x.toFixed(precision) + ", " + vec3.y.toFixed(precision) + ", " + vec3.z.toFixed(precision) + ")";
      }
      /**
       * 令vec2 转换为限制数字长度的字符串
       */
      function vec2ToString(vec2, precision) {
        if (precision === void 0) {
          precision = 2;
        }
        return "(" + vec2.x.toFixed(precision) + ", " + vec2.y.toFixed(precision) + ")";
      }

      /**
       * 返回距离最近的一个点
       */
      function getNearestPoint(points, point, distance) {
        return minBy(points, function (p) {
          return distance(p, point);
        });
      }

      /**
       * 方向向量转旋转四元数
       */
      function quatFromVec(vec, out) {
        if (out === void 0) {
          out = new Quat();
        }
        var angle = toDegree(Math.atan2(vec.y, vec.x)) - 90;
        Quat.fromAngleZ(out, angle);
        return out;
      }

      /**
       * 方向向量转z轴旋转角度
       */
      function zRotFromVec(vec) {
        return toDegree(Math.atan2(-vec.y, vec.x));
      }

      /**
       * 创建线性空间
       * @param start 起始值
       * @param end 结束值
       * @param count 数量
       */
      function linearSpace(start, end, count) {
        var result;
        if (count === 1) {
          // 处理 count 为 1 的情况，避免除以零
          result = [start];
        } else {
          // 其他非标情况会from会自动处理，一般是空数组
          result = Array.from({
            length: count
          }, function (_, i) {
            return start + i * (end - start) / (count - 1);
          });
        }
        return result;
      }

      /**
       * 自定义节流函数. 默认仅首次调用执行，后续忽略
       */
      function sthrottle(func, wait, options) {
        if (options === void 0) {
          options = {
            leading: true,
            trailing: false
          };
        }
        return throttle(func, wait, options);
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "1b21c8dVk1MYbpK6yByT+iu", "AsyncUtils", undefined);

      /**
       * 轮询配置选项
       */

      /**
       * 异步轮询函数，直到测试函数通过才解决
       * @param testFn 测试函数，返回 true 表示通过
       * @param component Cocos Creator 组件实例，用于调度
       * @param options 轮询配置选项
       * @returns Promise，在测试通过后解决
       * @example
       * // 等待材质加载
       * await pollUntil(
       *     () => sprite.material !== null,
       *     this,
       *     { maxRetries: 30, interval: 0 }
       * );
       */
      function _pollUntil(testFn, component, options) {
        if (options === void 0) {
          options = {};
        }
        var _options = options,
          _options$interval = _options.interval,
          interval = _options$interval === void 0 ? 0 : _options$interval,
          _options$maxRetries = _options.maxRetries,
          maxRetries = _options$maxRetries === void 0 ? 30 : _options$maxRetries,
          _options$warningThres = _options.warningThreshold,
          warningThreshold = _options$warningThres === void 0 ? 100 : _options$warningThres;
        return new Promise(function (resolve, reject) {
          var retryCount = 0;
          var attempt = /*#__PURE__*/function () {
            var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
              var result;
              return _regeneratorRuntime().wrap(function _callee$(_context) {
                while (1) switch (_context.prev = _context.next) {
                  case 0:
                    _context.prev = 0;
                    _context.next = 3;
                    return testFn();
                  case 3:
                    result = _context.sent;
                    if (!result) {
                      _context.next = 7;
                      break;
                    }
                    resolve();
                    return _context.abrupt("return");
                  case 7:
                    if (retryCount >= warningThreshold) {
                      logger.warn("PollUntil: " + retryCount + " times without triggering", {
                        funcName: "pollUntil"
                      });
                    }
                    if (!(retryCount >= maxRetries)) {
                      _context.next = 11;
                      break;
                    }
                    reject();
                    return _context.abrupt("return");
                  case 11:
                    retryCount++;
                    component.scheduleOnce(attempt, interval);
                    _context.next = 18;
                    break;
                  case 15:
                    _context.prev = 15;
                    _context.t0 = _context["catch"](0);
                    reject(_context.t0);
                  case 18:
                  case "end":
                    return _context.stop();
                }
              }, _callee, null, [[0, 15]]);
            }));
            return function attempt() {
              return _ref.apply(this, arguments);
            };
          }();
          attempt();
        });
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "4c47bkJRFtJCKnKG/jkpMco", "ColliderTag", undefined);

      /**
       * @readonly
       * @description 碰撞体的tag
       */
      var ColliderTag = /*#__PURE__*/function (ColliderTag) {
        ColliderTag[ColliderTag["NONE"] = 0] = "NONE";
        ColliderTag[ColliderTag["Player"] = 1] = "Player";
        ColliderTag[ColliderTag["Monster"] = 2] = "Monster";
        ColliderTag[ColliderTag["Wall"] = 3] = "Wall";
        ColliderTag[ColliderTag["Prop"] = 4] = "Prop";
        ColliderTag[ColliderTag["Freeze"] = 5] = "Freeze";
        return ColliderTag;
      }(ColliderTag || {});
      Enum(ColliderTag);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "9d49f9N35RMlZH/sI4NSNdC", "RigidBodyGroup", undefined);
      var RigidBodyGroup = /*#__PURE__*/function (RigidBodyGroup) {
        RigidBodyGroup[RigidBodyGroup["DEFAULT"] = 1] = "DEFAULT";
        RigidBodyGroup[RigidBodyGroup["MONSTER"] = 2] = "MONSTER";
        RigidBodyGroup[RigidBodyGroup["PLAYER"] = 4] = "PLAYER";
        RigidBodyGroup[RigidBodyGroup["WALL"] = 8] = "WALL";
        RigidBodyGroup[RigidBodyGroup["ANCHOR"] = 16] = "ANCHOR";
        RigidBodyGroup[RigidBodyGroup["PROP"] = 32] = "PROP";
        RigidBodyGroup[RigidBodyGroup["MONSTER_PROP"] = 64] = "MONSTER_PROP";
        return RigidBodyGroup;
      }(RigidBodyGroup || {}); // 怪物道具
      Enum(RigidBodyGroup);
      cclegacy._RF.pop();
      var _dec$6, _dec2$6, _dec3$6, _dec4$4, _dec5, _class$7;
      cclegacy._RF.push({}, "f6a4fGPBGlPRZEK8cFxWxa6", "SectorColliderAble", undefined);
      var ccclass$6 = _decorator.ccclass,
        menu$6 = _decorator.menu,
        executionOrder$4 = _decorator.executionOrder,
        disallowMultiple$6 = _decorator.disallowMultiple,
        requireComponent = _decorator.requireComponent;

      /**
       * 扇形区域碰撞事件组件
       * 专门用于扇形区域的碰撞事件处理
       */
      var SectorColliderAble = (_dec$6 = ccclass$6('SectorColliderAble'), _dec2$6 = menu$6('Utils/SectorColliderAble'), _dec3$6 = disallowMultiple$6(true), _dec4$4 = executionOrder$4(-1), _dec5 = requireComponent([PolygonCollider2D, RigidBody2D]), _dec$6(_class$7 = _dec2$6(_class$7 = _dec3$6(_class$7 = _dec4$4(_class$7 = _dec5(_class$7 = /*#__PURE__*/function (_ref) {
        _inheritsLoose(SectorColliderAble, _ref);
        function SectorColliderAble() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ref.call.apply(_ref, [this].concat(args)) || this;
          _this.Collider = null;
          _this.RigidBody = null;
          // 扇形区域参数
          _this.area = null;
          /**
           * 通用碰撞
           */
          _this.handleCollision = function (state, msg) {
            return function (selfCollider, otherCollider, _contact) {
              _this.log.Method('handleCollision' + ("-" + state)).log("\u6247\u5F62\u533A\u57DF" + _this.node.name + "\u4E8E" + vec3ToString(_this.node.worldPosition) + msg + "\u78B0\u649E\uFF0C" + ("\u78B0\u649E\u5BF9\u8C61" + otherCollider.node.name + "\u3001uuid=" + otherCollider.node.uuid));
              if (_this.area) {
                // 在自己的节点事件中发送事件
                var tag = ColliderTag[otherCollider.tag];
                _this.emit("collider.Sector" + tag + "." + state, otherCollider, _this.area);
              }
            };
          };
          _this.handleBeginContact = _this.handleCollision('start', '开始');
          _this.handleStayContact = _this.handleCollision('stay', '持续');
          _this.handleEndContact = _this.handleCollision('end', '结束');
          return _this;
        }
        var _proto = SectorColliderAble.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this).Method('onLoad');

          // 获取刚体组件
          this.RigidBody = this.getComponent(RigidBody2D);
          // 获取碰撞体组件
          this.Collider = this.getComponent(PolygonCollider2D);
        };
        _proto.onEnable = function onEnable() {
          // 监听碰撞事件
          this.Collider.on(Contact2DType.BEGIN_CONTACT, this.handleBeginContact);
          // this.Collider.on(Contact2DType.PRE_SOLVE, this.handleStayContact);
          this.Collider.on(Contact2DType.END_CONTACT, this.handleEndContact);
        };
        _proto.onDisable = function onDisable() {
          // 取消监听碰撞事件
          this.Collider.off(Contact2DType.BEGIN_CONTACT, this.handleBeginContact);
          // this.Collider.off(Contact2DType.PRE_SOLVE, this.handleStayContact);
          this.Collider.off(Contact2DType.END_CONTACT, this.handleEndContact);
        };
        _proto.start = function start() {
          var _this$area$group, _this$area, _this$area$tag, _this$area2, _this$area$group2, _this$area3, _this$area$polygonPoi, _this$area4;
          this.area = sectorAreaManager().getSectorAreaByUuid(this.node.uuid);

          // 设置刚体
          this.RigidBody.enabledContactListener = true; // 启用碰撞监听
          this.RigidBody.type = ERigidBody2DType.Static;
          this.RigidBody.group = (_this$area$group = (_this$area = this.area) == null ? void 0 : _this$area.group) != null ? _this$area$group : RigidBodyGroup.DEFAULT;
          this.RigidBody.wakeUp();
          // 设置碰撞体
          this.Collider.tag = (_this$area$tag = (_this$area2 = this.area) == null ? void 0 : _this$area2.tag) != null ? _this$area$tag : ColliderTag.Freeze;
          this.Collider.sensor = true;
          this.Collider.group = (_this$area$group2 = (_this$area3 = this.area) == null ? void 0 : _this$area3.group) != null ? _this$area$group2 : RigidBodyGroup.DEFAULT;
          this.Collider.points = (_this$area$polygonPoi = (_this$area4 = this.area) == null ? void 0 : _this$area4.polygonPoints) != null ? _this$area$polygonPoi : [];
          this.Collider.apply();
        };
        return SectorColliderAble;
      }(BaseEventCmp)) || _class$7) || _class$7) || _class$7) || _class$7) || _class$7);
      cclegacy._RF.pop();
      var _dec$7, _dec2$7, _dec3$7, _dec4$5, _dec5$1, _dec6, _class$8, _class2, _descriptor, _descriptor2, _descriptor3;
      cclegacy._RF.push({}, "a5cdf9O1YhHj4pDYLSfZnRW", "RefreshRatioLabel", undefined);
      var ccclass$7 = _decorator.ccclass,
        menu$7 = _decorator.menu,
        disallowMultiple$7 = _decorator.disallowMultiple,
        property$1 = _decorator.property;
      var RefreshRatioLabel = (_dec$7 = ccclass$7('RefreshRatioLabel'), _dec2$7 = menu$7('UI/RefreshRatioLabel'), _dec3$7 = disallowMultiple$7(true), _dec4$5 = property$1({
        tooltip: '最大值'
      }), _dec5$1 = property$1({
        tooltip: '当前值'
      }), _dec6 = property$1({
        type: Label,
        tooltip: '文本组件'
      }), _dec$7(_class$8 = _dec2$7(_class$8 = _dec3$7(_class$8 = (_class2 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(RefreshRatioLabel, _Component);
        function RefreshRatioLabel() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "maxValue", _descriptor, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "currentValue", _descriptor2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "label", _descriptor3, _assertThisInitialized(_this));
          _this.handleRefreshRatio = function (currentValue, maxValue) {
            _this.currentValue = currentValue;
            _this.maxValue = maxValue;
            _this.label.string = _this.currentValue.toFixed(0) + "/" + _this.maxValue.toFixed(0);
          };
          return _this;
        }
        var _proto = RefreshRatioLabel.prototype;
        _proto.onLoad = function onLoad() {
          this.label = this.getComponent(Label);
        };
        return RefreshRatioLabel;
      }(Component), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "maxValue", [_dec4$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "currentValue", [_dec5$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "label", [_dec6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2)) || _class$8) || _class$8) || _class$8);
      cclegacy._RF.pop();
      var _dec$8, _dec2$8, _dec3$8, _dec4$6, _dec5$2, _class$9;
      cclegacy._RF.push({}, "7be54EjI+1BH5OV3AA9P8dT", "ColliderAble", undefined);
      var ccclass$8 = _decorator.ccclass,
        menu$8 = _decorator.menu,
        executionOrder$5 = _decorator.executionOrder,
        disallowMultiple$8 = _decorator.disallowMultiple,
        requireComponent$1 = _decorator.requireComponent;

      /**
       * 碰撞事件组件
       */
      var ColliderAble = (_dec$8 = ccclass$8('ColliderAble'), _dec2$8 = menu$8('Utils/ColliderAble'), _dec3$8 = disallowMultiple$8(true), _dec4$6 = executionOrder$5(-1), _dec5$2 = requireComponent$1([Collider2D, RigidBody2D]), _dec$8(_class$9 = _dec2$8(_class$9 = _dec3$8(_class$9 = _dec4$6(_class$9 = _dec5$2(_class$9 = /*#__PURE__*/function (_ref) {
        _inheritsLoose(ColliderAble, _ref);
        function ColliderAble() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ref.call.apply(_ref, [this].concat(args)) || this;
          _this.Collider = null;
          _this.RigidBody = null;
          /**
           * 当触发器被进入时调用
           * @param selfCollider 自身碰撞体
           * @param otherCollider 其他碰撞体
           * @param contact 碰撞接触信息
           */
          _this.handleBeginContact = _this.handleCollision('handleBeginContact', '开始', 'start');
          /**
           * 当触发器被离开时调用
           * @param selfCollider 自身碰撞体
           * @param otherCollider 其他碰撞体
           * @param contact 碰撞接触信息
           */
          _this.handleEndContact = _this.handleCollision('handleEndContact', '结束', 'end');
          return _this;
        }
        var _proto = ColliderAble.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this).Method('onLoad');

          // 获取刚体组件
          this.RigidBody = this.getComponent(RigidBody2D);
          // 获取碰撞体组件
          this.Collider = this.getComponent(Collider2D);
          this.RigidBody.enabledContactListener = true; // 启用碰撞监听
        };

        _proto.onEnable = function onEnable() {
          // 监听碰撞事件
          this.Collider.on(Contact2DType.BEGIN_CONTACT, this.handleBeginContact);
          this.Collider.on(Contact2DType.END_CONTACT, this.handleEndContact);
        };
        _proto.onDisable = function onDisable() {
          // 取消监听碰撞事件
          this.Collider.off(Contact2DType.BEGIN_CONTACT, this.handleBeginContact);
          this.Collider.off(Contact2DType.END_CONTACT, this.handleEndContact);
        };
        _proto.handleCollision = function handleCollision(name, msg1, eventType) {
          var _this2 = this;
          return function (selfCollider, otherCollider, contact) {
            _this2.log.Method(name).log("\u8282\u70B9" + _this2.node.name + "\u4E8E" + vec3ToString(_this2.node.worldPosition) + msg1 + "\u78B0\u649E\uFF0C" + ("\u78B0\u649E\u5BF9\u8C61" + otherCollider.node.name + "\u3001") + ("tag=" + ColliderTag[otherCollider.tag] + "\u3001") + ("uuid=" + otherCollider.node.uuid));

            // 发送碰撞事件
            var tag = ColliderTag[otherCollider.tag];
            if (tag) {
              _this2.emit("collider." + tag + "." + eventType, selfCollider, otherCollider, contact);
            }
          };
        };
        return ColliderAble;
      }(BaseEventCmp)) || _class$9) || _class$9) || _class$9) || _class$9) || _class$9);
      cclegacy._RF.pop();
      var _dec$9, _dec2$9, _dec3$9, _class$a;
      cclegacy._RF.push({}, "adb3epjFnBNY7YUnuO0y/+P", "MonsterMove", undefined);
      var ccclass$9 = _decorator.ccclass,
        menu$9 = _decorator.menu,
        disallowMultiple$9 = _decorator.disallowMultiple;
      var Enum_MonsterMoveStates = /*#__PURE__*/function (Enum_MonsterMoveStates) {
        Enum_MonsterMoveStates["MOVE"] = "move";
        Enum_MonsterMoveStates["STOP"] = "stop";
        Enum_MonsterMoveStates["STAND"] = "stand";
        return Enum_MonsterMoveStates;
      }({});
      Enum(Enum_MonsterMoveStates);
      var MonsterMove = (_dec$9 = ccclass$9('MonsterMove'), _dec2$9 = menu$9('Monster/MonsterMove'), _dec3$9 = disallowMultiple$9(true), _dec$9(_class$a = _dec2$9(_class$a = _dec3$9(_class$a = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MonsterMove, _Component);
        function MonsterMove() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this._tmpQuat = new Quat();
          /**
           * 处理移动事件
           * @param direction 目标位置
           */
          _this.handleMove = function (direction) {
            // 空闲状态才移动
            if (_this.State.moveState !== Enum_MonsterMoveStates.STOP) {
              return;
            }
            var targetVec2 = direction.subtract(_this.node.worldPosition.toVec2());

            // 计算移动向量
            var movement = targetVec2.normalize().multiplyScalar(_this.State.moveSpeed);

            // 应用移动
            var rigidBody = _this.State.colliderAble.RigidBody;
            rigidBody.linearVelocity = movement;

            // 调整角度
            var _tmp_quat = quatFromVec(targetVec2, _this._tmpQuat);
            _this.node.worldRotation = _tmp_quat;
          };
          /**
           * 处理停止事件
           */
          _this.handleStop = function () {
            // 停止移动
            var rigidBody = _this.State.colliderAble.RigidBody;
            rigidBody.linearVelocity = new Vec2(0, 0);
            _this.State.moveState = Enum_MonsterMoveStates.STOP;
          };
          return _this;
        }
        var _proto = MonsterMove.prototype;
        _proto.onEnable = function onEnable() {
          var _this$State$event, _this$State$event2;
          (_this$State$event = this.State.event) == null || _this$State$event.on('move', this.handleMove);
          (_this$State$event2 = this.State.event) == null || _this$State$event2.on('stop', this.handleStop);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event3, _this$State$event4;
          (_this$State$event3 = this.State.event) == null || _this$State$event3.off('move', this.handleMove);
          (_this$State$event4 = this.State.event) == null || _this$State$event4.off('stop', this.handleStop);
        };
        return MonsterMove;
      }(Component)) || _class$a) || _class$a) || _class$a);
      cclegacy._RF.pop();
      var _dec$a, _dec2$a, _dec3$a, _dec4$7, _dec5$3, _dec6$1, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _dec15, _class$b, _class2$1, _descriptor$1, _descriptor2$1, _descriptor3$1, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12;
      cclegacy._RF.push({}, "11b82Tc79FMKrSwX+APnPpJ", "MonsterState", undefined);
      var ccclass$a = _decorator.ccclass,
        property$2 = _decorator.property,
        disallowMultiple$a = _decorator.disallowMultiple;
      var MonsterState = (_dec$a = ccclass$a('MonsterState'), _dec2$a = disallowMultiple$a(true), _dec3$a = property$2(pOpt2('停止时间', '基础', '控制')), _dec4$7 = property$2(pOpt1(Enum_MonsterMoveStates, '移动状态', '移动', '状态')), _dec5$3 = property$2(pOpt2('移动速度（像素/秒）', '移动', '控制')), _dec6$1 = property$2(pOpt1(Node, '目标节点', '跟随', '绑定')), _dec7 = property$2(pOpt2('停止距离（像素）', '跟随', '控制')), _dec8 = property$2(pOpt2('移动间隔（秒）', '跟随', '控制')), _dec9 = property$2(pOpt2('检测间隔（秒）', '跟随', '控制')), _dec10 = property$2(pOpt2('最大生命值', '生命', '控制')), _dec11 = property$2(pOpt2('当前生命值', '生命', '控制')), _dec12 = property$2(pOpt1(ProgressBar, '生命条', '生命', '绑定')), _dec13 = property$2(pOpt1(RefreshRatioLabel, '生命百分比', '生命', '绑定')), _dec14 = property$2(pOpt2('当前伤害加数', '伤害', '控制')), _dec15 = property$2(pOpt2('当前伤害乘数', '伤害', '控制')), _dec$a(_class$b = _dec2$a(_class$b = (_class2$1 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MonsterState, _Component);
        function MonsterState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.colliderAble = null;
          _this.event = null;
          /* -------------------- nanostores状态变量 -------------------- */
          // 需要被监听的变量使用atom注册，使用下划线前缀
          _this._moveState = atom(Enum_MonsterMoveStates.STOP);
          _this._maxHealth = atom(100);
          /* -------------------- 基础控制 -------------------- */
          _initializerDefineProperty(_this, "stopTime", _descriptor$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "moveSpeed", _descriptor2$1, _assertThisInitialized(_this));
          /* -------------------- 跟随 -------------------- */
          _initializerDefineProperty(_this, "target", _descriptor3$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "stopDistance", _descriptor4, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "moveInterval", _descriptor5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "followCheckInterval", _descriptor6, _assertThisInitialized(_this));
          /* -------------------- 生命值 -------------------- */
          _initializerDefineProperty(_this, "maxHealth", _descriptor7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_health", _descriptor8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "healthBar", _descriptor9, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "healthRatioLabel", _descriptor10, _assertThisInitialized(_this));
          /* -------------------- 伤害 -------------------- */
          _initializerDefineProperty(_this, "damageAdd", _descriptor11, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "damageMultiply", _descriptor12, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = MonsterState.prototype;
        _proto.onLoad = function onLoad() {
          this._health = atom(this.maxHealth);
          this.colliderAble = this.getComponent(ColliderAble);
          this.event = this.getComponent(MonsterEventCmp);
          // 绑定
          this.target = gmVar().player;
        };
        _proto.start = function start() {
          var _this$event;
          (_this$event = this.event) == null || _this$event.emit('hp.change', {
            now_value: this.health,
            old_value: this.health,
            max_value: this.maxHealth
          });
        };
        _createClass(MonsterState, [{
          key: "moveState",
          get: /* -------------------- 移动 -------------------- */
          function get() {
            return this._moveState.get();
          },
          set: function set(value) {
            this._moveState.set(value);
          }
        }, {
          key: "health",
          get: function get() {
            return this._health.get();
          },
          set: function set(value) {
            var _this$maxHealth;
            var nowValue = clamp$1(value != null ? value : 0, 0, (_this$maxHealth = this.maxHealth) != null ? _this$maxHealth : 0);
            this._health.set(nowValue);
          }
        }]);
        return MonsterState;
      }(Component), (_descriptor$1 = _applyDecoratedDescriptor(_class2$1.prototype, "stopTime", [_dec3$a], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _applyDecoratedDescriptor(_class2$1.prototype, "moveState", [_dec4$7], Object.getOwnPropertyDescriptor(_class2$1.prototype, "moveState"), _class2$1.prototype), _descriptor2$1 = _applyDecoratedDescriptor(_class2$1.prototype, "moveSpeed", [_dec5$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor3$1 = _applyDecoratedDescriptor(_class2$1.prototype, "target", [_dec6$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor4 = _applyDecoratedDescriptor(_class2$1.prototype, "stopDistance", [_dec7], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor5 = _applyDecoratedDescriptor(_class2$1.prototype, "moveInterval", [_dec8], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      }), _descriptor6 = _applyDecoratedDescriptor(_class2$1.prototype, "followCheckInterval", [_dec9], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      }), _descriptor7 = _applyDecoratedDescriptor(_class2$1.prototype, "maxHealth", [_dec10], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor8 = _applyDecoratedDescriptor(_class2$1.prototype, "_health", [property$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _applyDecoratedDescriptor(_class2$1.prototype, "health", [_dec11], Object.getOwnPropertyDescriptor(_class2$1.prototype, "health"), _class2$1.prototype), _descriptor9 = _applyDecoratedDescriptor(_class2$1.prototype, "healthBar", [_dec12], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor10 = _applyDecoratedDescriptor(_class2$1.prototype, "healthRatioLabel", [_dec13], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor11 = _applyDecoratedDescriptor(_class2$1.prototype, "damageAdd", [_dec14], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 10;
        }
      }), _descriptor12 = _applyDecoratedDescriptor(_class2$1.prototype, "damageMultiply", [_dec15], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      })), _class2$1)) || _class$b) || _class$b);
      cclegacy._RF.pop();
      var _dec$b, _dec2$b, _dec3$b, _dec4$8, _dec5$4, _dec6$2, _class$c, _class2$2, _descriptor$2, _descriptor2$2, _descriptor3$2;
      cclegacy._RF.push({}, "51833yZ0i9C54CRVYNATrej", "SectorFreeze", undefined);
      var ccclass$b = _decorator.ccclass,
        menu$a = _decorator.menu,
        property$3 = _decorator.property,
        disallowMultiple$b = _decorator.disallowMultiple,
        requireComponent$2 = _decorator.requireComponent;

      /**
       * 扇形冰冻区域组件
       * 添加到扇形区域节点上，当怪物进入时减速，离开时恢复速度
       */
      var SectorFreeze = (_dec$b = ccclass$b('SectorFreeze'), _dec2$b = menu$a('Sector/SectorFreeze'), _dec3$b = disallowMultiple$b(true), _dec4$8 = requireComponent$2(SectorColliderAble), _dec5$4 = property$3({
        tooltip: '伤害'
      }), _dec6$2 = property$3({
        tooltip: '伤害间隔'
      }), _dec$b(_class$c = _dec2$b(_class$c = _dec3$b(_class$c = _dec4$8(_class$c = (_class2$2 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(SectorFreeze, _Component);
        function SectorFreeze() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          /** 扇形碰撞组件 */
          _this.sectorCollider = null;
          /** 区域内怪物的速度记录 */
          _this.monsterSpeedRecords = new Map();
          /** 减速比例（默认50%） */
          _initializerDefineProperty(_this, "slowRatio", _descriptor$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "damage", _descriptor2$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "damageInterval", _descriptor3$2, _assertThisInitialized(_this));
          /**
           * 处理怪物进入冰冻区域
           */
          _this.handleEnterFreezeArea = function (otherCollider, _area) {
            var monsterNode = otherCollider.node;

            // 以前减速过，则不减速
            if (_this.monsterSpeedRecords.has(monsterNode.uuid)) {
              return;
            }

            // 获取怪物的状态组件
            var monsterState = monsterNode.getComponent(MonsterState);
            if (!monsterState) {
              return;
            }
            // 造成伤害
            var handleDamage = function handleDamage() {
              _this.handleDamage(otherCollider, _area);
            };
            monsterState.schedule(handleDamage, _this.damageInterval);

            // 计算当前速度和减速后的速度
            var currentSpeed = monsterState.moveSpeed;
            var targetSpeed = currentSpeed * _this.slowRatio;
            var speedReduction = currentSpeed - targetSpeed;

            // 记录
            var map = {
              speedReduction: speedReduction,
              damageCallback: handleDamage
            };
            _this.monsterSpeedRecords.set(monsterNode.uuid, map);

            // 应用减速
            monsterState.moveSpeed = targetSpeed;
          };
          /**
           * 处理怪物离开冰冻区域
           */
          _this.handleExitFreezeArea = function (otherCollider, _area) {
            var monsterNode = otherCollider.node;

            // 获取记录
            var record = _this.monsterSpeedRecords.get(monsterNode.uuid);
            if (!record) {
              return;
            }

            // 恢复怪物的速度（将减少的速度加回去）
            var monsterState = monsterNode.getComponent(MonsterState);
            if (monsterState) {
              monsterState.moveSpeed += record.speedReduction;
            }

            // 取消怪物伤害
            monsterState == null || monsterState.unschedule(record.damageCallback);

            // 移除记录
            _this.monsterSpeedRecords.delete(monsterNode.uuid);
          };
          _this.handleDamage = function (otherCollider, _area) {
            var _monsterState$event;
            var monsterNode = otherCollider.node;
            var monsterState = monsterNode.getComponent(MonsterState);
            monsterState == null || (_monsterState$event = monsterState.event) == null || _monsterState$event.emit('damage', _this.damage);
          };
          return _this;
        }
        var _proto = SectorFreeze.prototype;
        _proto.onLoad = function onLoad() {
          this.sectorCollider = this.getComponent(SectorColliderAble);
        };
        _proto.onEnable = function onEnable() {
          // 监听冰冻区域碰撞事件
          this.sectorCollider.on('collider.SectorMonster.start', this.handleEnterFreezeArea);
          this.sectorCollider.on('collider.SectorMonster.end', this.handleExitFreezeArea);
        };
        _proto.onDisable = function onDisable() {
          this.sectorCollider.off('collider.SectorFreeze.start', this.handleEnterFreezeArea);
          this.sectorCollider.off('collider.SectorFreeze.end', this.handleExitFreezeArea);
        };
        return SectorFreeze;
      }(Component), (_descriptor$2 = _applyDecoratedDescriptor(_class2$2.prototype, "slowRatio", [property$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor2$2 = _applyDecoratedDescriptor(_class2$2.prototype, "damage", [_dec5$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor3$2 = _applyDecoratedDescriptor(_class2$2.prototype, "damageInterval", [_dec6$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      })), _class2$2)) || _class$c) || _class$c) || _class$c) || _class$c);
      cclegacy._RF.pop();
      var _dec$c, _dec2$c, _class$d, _class2$3, _descriptor$3, _descriptor2$3, _dec3$c, _dec4$9, _dec5$5, _dec6$3, _class4, _class5, _descriptor3$3, _descriptor4$1;
      cclegacy._RF.push({}, "a06e8ItkURJR7gsHvfQK5Yq", "SectorAreaManager", undefined);
      var ccclass$c = _decorator.ccclass,
        menu$b = _decorator.menu,
        disallowMultiple$c = _decorator.disallowMultiple,
        property$4 = _decorator.property;

      /**
       * 扇形区域数据结构
       */

      var SectorAreaTag = function (SectorAreaTag) {
        SectorAreaTag[SectorAreaTag["Freeze"] = ColliderTag.Freeze] = "Freeze";
        return SectorAreaTag;
      }({});
      Enum(SectorAreaTag);

      /**
       * 创建扇形区域的参数
       */
      var TagColor = (_dec$c = ccclass$c('TagColor'), _dec2$c = property$4({
        type: SectorAreaTag
      }), _dec$c(_class$d = (_class2$3 = function TagColor() {
        _initializerDefineProperty(this, "tag", _descriptor$3, this);
        _initializerDefineProperty(this, "color", _descriptor2$3, this);
      }, (_descriptor$3 = _applyDecoratedDescriptor(_class2$3.prototype, "tag", [_dec2$c], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return SectorAreaTag.Freeze;
        }
      }), _descriptor2$3 = _applyDecoratedDescriptor(_class2$3.prototype, "color", [property$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$3)) || _class$d);
      /**
       * 扇形区域管理器
       * 管理扇形区域的创建和物体检测
       */
      var SectorAreaManager = (_dec3$c = ccclass$c('SectorAreaManager'), _dec4$9 = menu$b('Game/SectorAreaManager'), _dec5$5 = disallowMultiple$c(true), _dec6$3 = property$4({
        type: [TagColor]
      }), _dec3$c(_class4 = _dec4$9(_class4 = _dec5$5(_class4 = (_class5 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(SectorAreaManager, _Component);
        function SectorAreaManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.log = new LogBuilder();
          _this.event = null;
          /** 扇形区域列表 */
          _this.sectorAreas = new Map();
          /** 区域检测更新间隔（秒） */
          _initializerDefineProperty(_this, "detectionInterval", _descriptor3$3, _assertThisInitialized(_this));
          /** 标签颜色列表 */
          _initializerDefineProperty(_this, "tagColors", _descriptor4$1, _assertThisInitialized(_this));
          /**
           * 处理创建扇形区域事件
           */
          _this.handleCreateSector = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(opt) {
            var _opt$sampleCount;
            var params, _yield$_this$createSe, sectorNode, sectorCollider, points, sectorArea;
            return _regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  // 采样点数，每15度一个采样点
                  params = _extends({}, opt, {
                    sampleCount: (_opt$sampleCount = opt.sampleCount) != null ? _opt$sampleCount : Math.ceil(Math.abs(opt.rotateAngle) / 15) + 2
                  });
                  _context.prev = 1;
                  _context.next = 4;
                  return _this.createSectorNode(params);
                case 4:
                  _yield$_this$createSe = _context.sent;
                  sectorNode = _yield$_this$createSe.sectorNode;
                  sectorCollider = _yield$_this$createSe.sectorCollider;
                  points = _yield$_this$createSe.points;
                  // 创建扇形区域
                  sectorArea = _extends({}, params, {
                    uuid: sectorNode.uuid,
                    center: {
                      x: params.center.x,
                      y: params.center.y
                    },
                    sectorNode: sectorNode,
                    sectorCollider: sectorCollider,
                    polygonPoints: points
                  }); // 添加到区域列表
                  _this.sectorAreas.set(sectorNode.uuid, sectorArea);

                  // 发送创建成功事件
                  _this.event.emit('sector.created', sectorNode.uuid);
                  _this.log.log("\u521B\u5EFA\u6247\u5F62\u533A\u57DF" + ("UUID:" + sectorNode.uuid + " ") + ("\u6807\u7B7E:" + params.tag + " ") + ("\u5206\u7EC4:" + params.group + " ") + ("\u4E2D\u5FC3:(" + params.center.x.toFixed(1) + "," + params.center.y.toFixed(1) + ") ") + ("\u65CB\u8F6C:" + params.rotateAngle.toFixed(1) + "\xB0 ") + ("\u89D2\u5EA6:" + params.startAngle.toFixed(1) + "\xB0~" + (params.startAngle + params.rotateAngle).toFixed(1) + "\xB0 ") + ("\u534A\u5F84:" + params.radius.toFixed(1) + " ") + ("\u6301\u7EED:" + params.duration + "s"));
                  // 定期移除
                  _this.scheduleOnce(function () {
                    return sectorNode.destroy();
                  }, params.duration);
                  return _context.abrupt("return", sectorNode.uuid);
                case 16:
                  _context.prev = 16;
                  _context.t0 = _context["catch"](1);
                  _this.log.error("\u521B\u5EFA\u6247\u5F62\u533A\u57DF\u5931\u8D25: " + _context.t0);
                  throw _context.t0;
                case 20:
                case "end":
                  return _context.stop();
              }
            }, _callee, null, [[1, 16]]);
          }));
          return _this;
        }
        var _proto = SectorAreaManager.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
          this.event = gmVar().gameEvent;
        };
        _proto.onEnable = function onEnable() {
          // 监听创建扇形区域事件
          this.event.on('sector.create', this.handleCreateSector);

          // DEBUG_TEST: 测试创建扇形区域
          // const pos = getGameVar()!.player.worldPosition;
          // this.scheduleOnce(() =>
          //     this.handleCreateSector({
          //         tag: SectorAreaTag.Freeze,
          //         group: RigidBodyGroup.PROP,
          //         startAngle: -180,
          //         rotateAngle: 100,
          //         center: { x: pos.x, y: pos.y },
          //         radius: 100,
          //         duration: 20,
          //     })
          // );
        };

        _proto.onDisable = function onDisable() {
          // 取消事件监听
          this.event.off('sector.create', this.handleCreateSector);
        }

        /**
         * 通过uuid获取扇形区域
         */;
        _proto.getSectorAreaByUuid = function getSectorAreaByUuid(uuid) {
          var _this$sectorAreas$get;
          return (_this$sectorAreas$get = this.sectorAreas.get(uuid)) != null ? _this$sectorAreas$get : null;
        };
        /**
         * 通过圆弧采样生成扇形多边形顶点
         * @param radius 半径
         * @param startAngle 起始角度（度）
         * @param rotateAngle 旋转角度（度）
         * @param sampleCount 采样点数
         * @returns 多边形顶点数组
         */
        _proto.genSectorPolygonPoints = function genSectorPolygonPoints(opt) {
          // 转换为弧度
          var startAngle = toRadian(opt.startAngle);
          var endAngle = toRadian(opt.startAngle + opt.rotateAngle);

          // 获取采样点
          var angleSteps = linearSpace(startAngle, endAngle, opt.sampleCount);

          // 创建顶点数组
          var vertices = [];

          // 添加中心点
          vertices.push(v2(0, 0));

          // 添加圆弧上的采样点（从起始角度开始）
          for (var _iterator = _createForOfIteratorHelperLoose(angleSteps), _step; !(_step = _iterator()).done;) {
            var angle = _step.value;
            var x = Math.cos(angle) * opt.radius;
            var y = -Math.sin(angle) * opt.radius;
            vertices.push(v2(x, y));
          }
          return vertices;
        }

        /**
         * 创建扇形节点和碰撞体
         * @param params 创建扇形区域的参数
         * @param sampleCount 采样点数
         * @returns 扇形节点和碰撞体
         */;
        _proto.createSectorNode = /*#__PURE__*/
        function () {
          var _createSectorNode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(params) {
            var gameVar, sectorNode, points, uiTransform, colliderAble, sectorCollider;
            return _regeneratorRuntime().wrap(function _callee2$(_context2) {
              while (1) switch (_context2.prev = _context2.next) {
                case 0:
                  gameVar = gmVar(); // 实例化扇形预制体
                  sectorNode = instantiate(gameVar.sectorPrefab); // 设置位置
                  sectorNode.setWorldPosition(params.center.x, params.center.y, 0);

                  // 先添加到场景树，确保组件正确初始化
                  sectorNode.setParent(gameVar.sectorContainer, true);

                  // 生成扇形多边形顶点
                  points = this.genSectorPolygonPoints(params); // 修改材质属性（等待材质更新成功）
                  this.updateSectorMaterial(sectorNode, params);

                  // 调整精灵大小对应半径
                  uiTransform = sectorNode.getComponent(UITransform);
                  uiTransform.setContentSize(params.radius * 2, params.radius * 2);

                  // 获取扇形区域碰撞组件
                  colliderAble = sectorNode.getComponent(SectorColliderAble);
                  sectorCollider = colliderAble.Collider; // 根据标签添加对应的组件
                  this.addSectorEffect(sectorNode, params.tag);
                  return _context2.abrupt("return", {
                    sectorNode: sectorNode,
                    sectorCollider: sectorCollider,
                    points: points
                  });
                case 12:
                case "end":
                  return _context2.stop();
              }
            }, _callee2, this);
          }));
          function createSectorNode(_x2) {
            return _createSectorNode.apply(this, arguments);
          }
          return createSectorNode;
        }()
        /**
         * 更新扇形区域的材质属性
         * @param sectorNode 扇形节点
         * @param params 扇形参数
         */;

        _proto.updateSectorMaterial = /*#__PURE__*/
        function () {
          var _updateSectorMaterial = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(sectorNode, params) {
            var sprite, material, index, color;
            return _regeneratorRuntime().wrap(function _callee3$(_context3) {
              while (1) switch (_context3.prev = _context3.next) {
                case 0:
                  this.log.Method('updateSectorMaterial');
                  sprite = sectorNode.getComponent(Sprite);
                  if (!sprite) {
                    this.log.error("\u6247\u5F62\u8282\u70B9\u6CA1\u6709\u7CBE\u7075\u7EC4\u4EF6");
                  }

                  // 等待材质加载
                  _context3.next = 5;
                  return _pollUntil(function () {
                    return sprite.material !== null;
                  }, this, {
                    interval: 0,
                    maxRetries: 30
                  });
                case 5:
                  this.log.log("\u6750\u8D28\u52A0\u8F7D\u6210\u529F\uFF0C\u8BBE\u7F6E\u5C5E\u6027...");
                  material = sprite.getMaterialInstance(0); // 设置扇形参数到材质
                  material.setProperty('centerX', 0.5);
                  material.setProperty('centerY', 0.5);
                  material.setProperty('startAngle', params.startAngle);
                  material.setProperty('sweepAngle', params.rotateAngle);
                  material.setProperty('radius', 0.5);

                  // 根据标签设置不同的颜色
                  index = this.tagColors.findIndex(function (tagColor) {
                    return tagColor.tag === params.tag;
                  });
                  color = index !== -1 ? this.tagColors[index].color : Color.BLUE;
                  material.setProperty('mainColor', color);
                case 15:
                case "end":
                  return _context3.stop();
              }
            }, _callee3, this);
          }));
          function updateSectorMaterial(_x3, _x4) {
            return _updateSectorMaterial.apply(this, arguments);
          }
          return updateSectorMaterial;
        }()
        /**
         * 根据标签添加对应的扇形效果组件
         * @param sectorNode 扇形节点
         * @param tag 扇形标签
         */;

        _proto.addSectorEffect = function addSectorEffect(sectorNode, tag) {
          var _this2 = this,
            _tagDict,
            _tagDict$tag;
          this.log.Method('addSectorEffect');
          var tagDict = (_tagDict = {}, _tagDict[SectorAreaTag.Freeze] = function () {
            sectorNode.addComponent(SectorFreeze);
            _this2.log.log("\u6247\u5F62\u533A\u57DF\u6DFB\u52A0\u51B0\u51BB\u6548\u679C\u7EC4\u4EF6");
          }, _tagDict);
          (_tagDict$tag = tagDict[tag]) == null || _tagDict$tag.call(tagDict);
        };
        return SectorAreaManager;
      }(Component), (_descriptor3$3 = _applyDecoratedDescriptor(_class5.prototype, "detectionInterval", [property$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      }), _descriptor4$1 = _applyDecoratedDescriptor(_class5.prototype, "tagColors", [_dec6$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      })), _class5)) || _class4) || _class4) || _class4);
      var sectorAreaManager = cache$1(function () {
        return find$1('GameManager').getComponentInChildren(SectorAreaManager);
      });
      cclegacy._RF.pop();
      var _dec$d, _dec2$d, _dec3$d, _dec4$a, _dec5$6, _dec6$4, _dec7$1, _dec8$1, _dec9$1, _dec10$1, _dec11$1, _dec12$1, _dec13$1, _dec14$1, _dec15$1, _dec16, _dec17, _dec18, _dec19, _dec20, _dec21, _dec22, _dec23, _dec24, _dec25, _dec26, _dec27, _dec28, _dec29, _dec30, _dec31, _dec32, _dec33, _dec34, _dec35, _dec36, _dec37, _dec38, _class$e, _class2$4, _descriptor$4, _descriptor2$4, _descriptor3$4, _descriptor4$2, _descriptor5$1, _descriptor6$1, _descriptor7$1, _descriptor8$1, _descriptor9$1, _descriptor10$1, _descriptor11$1, _descriptor12$1, _descriptor13, _descriptor14, _descriptor15, _descriptor16, _descriptor17, _descriptor18, _descriptor19, _descriptor20, _descriptor21;
      cclegacy._RF.push({}, "1ac13fNKqpMt4eG+wOvlYac", "PlayerState", undefined);
      var ccclass$d = _decorator.ccclass,
        menu$c = _decorator.menu,
        property$5 = _decorator.property,
        disallowMultiple$d = _decorator.disallowMultiple,
        executionOrder$6 = _decorator.executionOrder;
      var PlayerMoveStates = /*#__PURE__*/function (PlayerMoveStates) {
        PlayerMoveStates["IDLE"] = "idle";
        PlayerMoveStates["DASHING"] = "dashing";
        PlayerMoveStates["ROTATING"] = "rotating";
        return PlayerMoveStates;
      }({});
      var PlayerRotateStates = /*#__PURE__*/function (PlayerRotateStates) {
        PlayerRotateStates["LEFT"] = "left";
        PlayerRotateStates["RIGHT"] = "right";
        PlayerRotateStates["STOP"] = "stop";
        return PlayerRotateStates;
      }({});
      Enum(PlayerMoveStates);
      Enum(PlayerRotateStates);
      var PlayerState = (_dec$d = ccclass$d('PlayerState'), _dec2$d = menu$c('Player/PlayerState'), _dec3$d = disallowMultiple$d(true), _dec4$a = executionOrder$6(0), _dec5$6 = property$5(pOpt1(LineEventCmp, '线事件', '绑定', '')), _dec6$4 = property$5(pOpt1(PlayerMoveStates, '移动状态', '移动', '状态')), _dec7$1 = property$5(pOpt2('移动速度（像素/秒）', '移动', '控制')), _dec8$1 = property$5(pOpt2('冲刺速度（像素/秒）', '冲刺', '控制')), _dec9$1 = property$5(pOpt1(Node, '当前锚点', '锚点', '控制')), _dec10$1 = property$5(pOpt2('锚点生命时长（秒）', '锚点', '控制')), _dec11$1 = property$5(pOpt2('最大锚点连接距离（像素）', '锚点', '控制')), _dec12$1 = property$5(pOpt2('锚点断开距离（像素）', '锚点', '控制')), _dec13$1 = property$5(pOpt2('锚点断开检测间隔（秒）', '锚点', '控制')), _dec14$1 = property$5(pOpt1(PlayerRotateStates, '旋转状态', '旋转', '状态')), _dec15$1 = property$5(pOpt2('旋转速度', '旋转', '控制')), _dec16 = property$5(pOpt1(Node, '旋转中心', '旋转', '绑定')), _dec17 = property$5(pOpt1(Node, '旋转边缘节点', '旋转', '绑定')), _dec18 = property$5(pOpt1(Joint2D, '旋转中心关节', '旋转', '绑定')), _dec19 = property$5(pOpt1(RigidBody2D, '旋转中心刚体', '旋转', '绑定')), _dec20 = property$5(pOpt2('最大生命值', '生命', '控制')), _dec21 = property$5(pOpt2('当前生命值', '生命', '控制')), _dec22 = property$5(pOpt1(ProgressBar, '生命条', '生命', '绑定')), _dec23 = property$5(pOpt1(RefreshRatioLabel, '生命百分比', '生命', '绑定')), _dec24 = property$5(pOpt2('当前恢复加数', '恢复', '控制')), _dec25 = property$5(pOpt2('当前恢复乘数', '恢复', '控制')), _dec26 = property$5(pOpt2('当前减伤乘数', '减伤', '控制')), _dec27 = property$5(pOpt2('当前减伤加数', '减伤', '控制')), _dec28 = property$5(pOpt2('当前伤害加数', '伤害', '控制')), _dec29 = property$5(pOpt2('当前伤害乘数', '伤害', '控制')), _dec30 = property$5(pOpt2('线段伤害', '伤害', '控制')), _dec31 = property$5(pOpt2('线段总伤害', '伤害', '控制')), _dec32 = property$5(pOpt2('扇形持续时间', '扇形', '控制')), _dec33 = property$5(pOpt1(SectorAreaTag, '扇形类型', '扇形', '控制')), _dec34 = property$5(pOpt2('当前等级', '等级', '状态')), _dec35 = property$5(pOpt2('当前经验值', '等级', '状态')), _dec36 = property$5(pOpt2('当前升级所需经验', '等级', '状态')), _dec37 = property$5(pOpt1([CCInteger], '升级经验值数组配置（自定义每级所需经验值）', '等级', '控制')), _dec38 = property$5(pOpt2('升级提高的最大生命值', '等级', '控制')), _dec$d(_class$e = _dec2$d(_class$e = _dec3$d(_class$e = _dec4$a(_class$e = (_class2$4 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerState, _Component);
        function PlayerState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.colliderAble = null;
          _this.event = null;
          _initializerDefineProperty(_this, "lineEvent", _descriptor$4, _assertThisInitialized(_this));
          /* -------------------- 移动 ------------------------ */
          _initializerDefineProperty(_this, "moveState", _descriptor2$4, _assertThisInitialized(_this));
          _this._moveSpeed = null;
          /* -------------------- 冲刺 ------------------------ */
          _initializerDefineProperty(_this, "dashSpeedMultiplier", _descriptor3$4, _assertThisInitialized(_this));
          /* -------------------- 锚点切换 ------------------------ */
          _initializerDefineProperty(_this, "nowAnchor", _descriptor4$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorLifeTime", _descriptor5$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "maxAnchorDistance", _descriptor6$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorBreakDistance", _descriptor7$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorBreakCheckInterval", _descriptor8$1, _assertThisInitialized(_this));
          /* -------------------- 旋转 ------------------------ */
          _initializerDefineProperty(_this, "rotateState", _descriptor9$1, _assertThisInitialized(_this));
          _this._rotateSpeed = null;
          _initializerDefineProperty(_this, "rotateCenter", _descriptor10$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "rotateEdge", _descriptor11$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "rotateCenterJoint", _descriptor12$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "rotateCenterRigidBody", _descriptor13, _assertThisInitialized(_this));
          /* -------------------- 生命和伤害 --------------------------- */
          _this._maxHealth = null;
          _this._health = null;
          _initializerDefineProperty(_this, "healthBar", _descriptor14, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "healthRatioLabel", _descriptor15, _assertThisInitialized(_this));
          _this._recoveryAdd = null;
          _this._recoveryMultiply = null;
          _this._defenseMultiply = null;
          _this._defenseAdd = null;
          /**----------------------------伤害------------------------------ */
          _this._damageAdd = null;
          _this._damageMultiply = null;
          _this._lineDamage = null;
          // 线段总伤害 = 线段伤害 * 伤害乘数 + 伤害加数
          _this._lineTotalDamage = null;
          /* -------------------- 旋转产生扇形区域 --------------------------- */
          _initializerDefineProperty(_this, "fanDuration", _descriptor16, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "fanType", _descriptor17, _assertThisInitialized(_this));
          /* -------------------- 等级和经验 --------------------------- */
          _initializerDefineProperty(_this, "_level", _descriptor18, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_exp", _descriptor19, _assertThisInitialized(_this));
          // 升级经验值数组配置（自定义每级所需经验值）
          _initializerDefineProperty(_this, "levelExpArray", _descriptor20, _assertThisInitialized(_this));
          // 升级提高的最大生命值
          _initializerDefineProperty(_this, "maxHealthAdd", _descriptor21, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = PlayerState.prototype;
        _proto.onLoad = function onLoad() {
          this._maxHealth = atom(100);
          this._health = atom(this.maxHealth);
          this._exp = atom(0);
          this._level = atom(0);
          this._damageAdd = atom(0);
          this._damageMultiply = atom(1);
          this._recoveryAdd = atom(0);
          this._recoveryMultiply = atom(1);
          this._defenseMultiply = atom(0);
          this._defenseAdd = atom(0);
          this._lineDamage = atom(10);
          this._lineTotalDamage = computed([this._lineDamage, this._damageMultiply, this._damageAdd], function (lineDamage, damageMultiply, damageAdd) {
            return lineDamage * damageMultiply + damageAdd;
          });
          this._moveSpeed = atom(10);
          this._rotateSpeed = atom(110);
          this.colliderAble = this.getComponent(ColliderAble);
          this.event = this.getComponent(PlayerEventCmp);
        };
        _proto.start = function start() {
          // 通知状态刷新
          this._maxHealth.notify();
          this._health.notify();
          this._exp.notify();
          this._level.notify();
          this._damageAdd.notify();
          this._damageMultiply.notify();
          this._recoveryAdd.notify();
          this._recoveryMultiply.notify();
          this._defenseMultiply.notify();
          this._defenseAdd.notify();
          this._lineDamage.notify();
          this._lineTotalDamage.notify();
          this._moveSpeed.notify();
          this._rotateSpeed.notify();
        };
        _createClass(PlayerState, [{
          key: "moveSpeed",
          get: function get() {
            return this._moveSpeed.get();
          },
          set: function set(value) {
            this._moveSpeed.set(value);
          }
        }, {
          key: "rotateSpeed",
          get: function get() {
            return this._rotateSpeed.get();
          },
          set: function set(value) {
            this._rotateSpeed.set(value);
          }
        }, {
          key: "maxHealth",
          get: function get() {
            return this._maxHealth.get();
          },
          set: function set(value) {
            this._maxHealth.set(value);
          }
        }, {
          key: "health",
          get: function get() {
            return this._health.get();
          },
          set: function set(value) {
            var _this$maxHealth;
            var nowValue = clamp$1(value != null ? value : 0, 0, (_this$maxHealth = this.maxHealth) != null ? _this$maxHealth : 0);
            this._health.set(nowValue);
          }
        }, {
          key: "recoveryAdd",
          get: function get() {
            return this._recoveryAdd.get();
          },
          set: function set(value) {
            this._recoveryAdd.set(value);
          }
        }, {
          key: "recoveryMultiply",
          get: function get() {
            return this._recoveryMultiply.get();
          },
          set: function set(value) {
            this._recoveryMultiply.set(value);
          }
        }, {
          key: "defenseMultiply",
          get: function get() {
            return this._defenseMultiply.get();
          },
          set: function set(value) {
            this._defenseMultiply.set(value);
          }
        }, {
          key: "defenseAdd",
          get: function get() {
            return this._defenseAdd.get();
          },
          set: function set(value) {
            this._defenseAdd.set(value);
          }
        }, {
          key: "damageAdd",
          get: function get() {
            return this._damageAdd.get();
          },
          set: function set(value) {
            this._damageAdd.set(value);
          }
        }, {
          key: "damageMultiply",
          get: function get() {
            return this._damageMultiply.get();
          },
          set: function set(value) {
            this._damageMultiply.set(value);
          }
        }, {
          key: "lineDamage",
          get: function get() {
            return this._lineDamage.get();
          },
          set: function set(value) {
            this._lineDamage.set(value);
          }
        }, {
          key: "lineTotalDamage",
          get: function get() {
            return this._lineTotalDamage.get();
          }
        }, {
          key: "level",
          get: function get() {
            return this._level.get();
          },
          set: function set(value) {
            this._level.set(value);
          }
        }, {
          key: "exp",
          get: function get() {
            return this._exp.get();
          },
          set: function set(value) {
            this._exp.set(value);
          }
        }, {
          key: "nowLevelExp",
          get: function get() {
            var _this$levelExpArray$a;
            return (_this$levelExpArray$a = this.levelExpArray.at(this.level)) != null ? _this$levelExpArray$a : Infinity;
          }
        }]);
        return PlayerState;
      }(Component), (_descriptor$4 = _applyDecoratedDescriptor(_class2$4.prototype, "lineEvent", [_dec5$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$4 = _applyDecoratedDescriptor(_class2$4.prototype, "moveState", [_dec6$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return PlayerMoveStates.IDLE;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "moveSpeed", [_dec7$1], Object.getOwnPropertyDescriptor(_class2$4.prototype, "moveSpeed"), _class2$4.prototype), _descriptor3$4 = _applyDecoratedDescriptor(_class2$4.prototype, "dashSpeedMultiplier", [_dec8$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1000;
        }
      }), _descriptor4$2 = _applyDecoratedDescriptor(_class2$4.prototype, "nowAnchor", [_dec9$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor5$1 = _applyDecoratedDescriptor(_class2$4.prototype, "anchorLifeTime", [_dec10$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor6$1 = _applyDecoratedDescriptor(_class2$4.prototype, "maxAnchorDistance", [_dec11$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 200;
        }
      }), _descriptor7$1 = _applyDecoratedDescriptor(_class2$4.prototype, "anchorBreakDistance", [_dec12$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor8$1 = _applyDecoratedDescriptor(_class2$4.prototype, "anchorBreakCheckInterval", [_dec13$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor9$1 = _applyDecoratedDescriptor(_class2$4.prototype, "rotateState", [_dec14$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return PlayerRotateStates.STOP;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "rotateSpeed", [_dec15$1], Object.getOwnPropertyDescriptor(_class2$4.prototype, "rotateSpeed"), _class2$4.prototype), _descriptor10$1 = _applyDecoratedDescriptor(_class2$4.prototype, "rotateCenter", [_dec16], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor11$1 = _applyDecoratedDescriptor(_class2$4.prototype, "rotateEdge", [_dec17], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor12$1 = _applyDecoratedDescriptor(_class2$4.prototype, "rotateCenterJoint", [_dec18], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor13 = _applyDecoratedDescriptor(_class2$4.prototype, "rotateCenterRigidBody", [_dec19], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "maxHealth", [_dec20], Object.getOwnPropertyDescriptor(_class2$4.prototype, "maxHealth"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "health", [_dec21], Object.getOwnPropertyDescriptor(_class2$4.prototype, "health"), _class2$4.prototype), _descriptor14 = _applyDecoratedDescriptor(_class2$4.prototype, "healthBar", [_dec22], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor15 = _applyDecoratedDescriptor(_class2$4.prototype, "healthRatioLabel", [_dec23], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "recoveryAdd", [_dec24], Object.getOwnPropertyDescriptor(_class2$4.prototype, "recoveryAdd"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "recoveryMultiply", [_dec25], Object.getOwnPropertyDescriptor(_class2$4.prototype, "recoveryMultiply"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "defenseMultiply", [_dec26], Object.getOwnPropertyDescriptor(_class2$4.prototype, "defenseMultiply"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "defenseAdd", [_dec27], Object.getOwnPropertyDescriptor(_class2$4.prototype, "defenseAdd"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "damageAdd", [_dec28], Object.getOwnPropertyDescriptor(_class2$4.prototype, "damageAdd"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "damageMultiply", [_dec29], Object.getOwnPropertyDescriptor(_class2$4.prototype, "damageMultiply"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "lineDamage", [_dec30], Object.getOwnPropertyDescriptor(_class2$4.prototype, "lineDamage"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "lineTotalDamage", [_dec31], Object.getOwnPropertyDescriptor(_class2$4.prototype, "lineTotalDamage"), _class2$4.prototype), _descriptor16 = _applyDecoratedDescriptor(_class2$4.prototype, "fanDuration", [_dec32], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 10;
        }
      }), _descriptor17 = _applyDecoratedDescriptor(_class2$4.prototype, "fanType", [_dec33], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return SectorAreaTag.Freeze;
        }
      }), _descriptor18 = _applyDecoratedDescriptor(_class2$4.prototype, "_level", [property$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "level", [_dec34], Object.getOwnPropertyDescriptor(_class2$4.prototype, "level"), _class2$4.prototype), _descriptor19 = _applyDecoratedDescriptor(_class2$4.prototype, "_exp", [property$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _applyDecoratedDescriptor(_class2$4.prototype, "exp", [_dec35], Object.getOwnPropertyDescriptor(_class2$4.prototype, "exp"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "nowLevelExp", [_dec36], Object.getOwnPropertyDescriptor(_class2$4.prototype, "nowLevelExp"), _class2$4.prototype), _descriptor20 = _applyDecoratedDescriptor(_class2$4.prototype, "levelExpArray", [_dec37], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];
        }
      }), _descriptor21 = _applyDecoratedDescriptor(_class2$4.prototype, "maxHealthAdd", [_dec38], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 50;
        }
      })), _class2$4)) || _class$e) || _class$e) || _class$e) || _class$e);
      cclegacy._RF.pop();
      var _dec$e, _dec2$e, _dec3$e, _dec4$b, _dec5$7, _dec6$5, _dec7$2, _dec8$2, _dec9$2, _dec10$2, _dec11$2, _dec12$2, _class$f, _class2$5, _descriptor$5, _descriptor2$5, _descriptor3$5, _descriptor4$3, _descriptor5$2, _descriptor6$2, _descriptor7$2, _descriptor8$2;
      cclegacy._RF.push({}, "6c734fk1ylLYo+Wib7n93Hf", "CircularProgressBar", undefined);
      var ccclass$e = _decorator.ccclass,
        menu$d = _decorator.menu,
        disallowMultiple$e = _decorator.disallowMultiple,
        property$6 = _decorator.property,
        executeInEditMode = _decorator.executeInEditMode;
      var CircularProgressBar = (_dec$e = ccclass$e('CircularProgressBar'), _dec2$e = menu$d('UI/CircularProgressBar'), _dec3$e = disallowMultiple$e(true), _dec4$b = executeInEditMode(true), _dec5$7 = property$6({
        displayName: 'Progress',
        tooltip: '进度值 (0-1)',
        range: [0, 1, 0.01],
        slide: true,
        visible: true
      }), _dec6$5 = property$6({
        displayName: 'Inner Radius',
        tooltip: '内半径',
        range: [0, 1, 0.01],
        slide: true,
        visible: true
      }), _dec7$2 = property$6({
        displayName: 'Outer Radius',
        tooltip: '外半径',
        range: [0, 1, 0.01],
        slide: true,
        visible: true
      }), _dec8$2 = property$6({
        displayName: 'Start Angle',
        tooltip: '起始角度',
        range: [0, 360, 1],
        slide: true,
        visible: true
      }), _dec9$2 = property$6({
        displayName: 'Ring Color',
        tooltip: '环形颜色',
        visible: true
      }), _dec10$2 = property$6({
        displayName: 'Smoothness',
        tooltip: '平滑度',
        range: [0, 0.4, 0.001],
        slide: true,
        visible: true
      }), _dec11$2 = property$6({
        displayName: 'Reverse',
        tooltip: '是否反向',
        visible: true
      }), _dec12$2 = property$6({
        displayName: 'Center',
        tooltip: '中心点',
        visible: true
      }), _dec$e(_class$f = _dec2$e(_class$f = _dec3$e(_class$f = _dec4$b(_class$f = (_class2$5 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(CircularProgressBar, _Component);
        function CircularProgressBar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "_progress", _descriptor$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_innerRadius", _descriptor2$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_outerRadius", _descriptor3$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_startAngle", _descriptor4$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_ringColor", _descriptor5$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_smoothness", _descriptor6$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_reverse", _descriptor7$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_center", _descriptor8$2, _assertThisInitialized(_this));
          // 材质属性
          _this.sprite = null;
          _this.material = null;
          _this.passIndex = 0;
          // Uniform 句柄属性
          _this.progressHandle = 0;
          _this.innerRadiusHandle = 0;
          _this.outerRadiusHandle = 0;
          _this.startAngleHandle = 0;
          _this.ringColorHandle = 0;
          _this.smoothnessHandle = 0;
          _this.reverseHandle = 0;
          _this.centerHandle = 0;
          return _this;
        }
        var _proto = CircularProgressBar.prototype;
        _proto.onLoad = function onLoad() {
          this.init();
        };
        _proto.onEnable = function onEnable() {
          this.init();

          // DEBUG_TEST: 简易测试，定时增长
          // this.schedule(
          //     () => {
          //         this.progress += 0.2;
          //         if (this.progress > 1) {
          //             this.progress = 0;
          //         }
          //     },
          //     0.5,
          //     6
          // );
          // // DEBUG_TEST: 简易测试，定时修改起始点
          // this.schedule(
          //     () => {
          //         this.startAngle += 40;
          //         if (this.startAngle > 360) {
          //             this.startAngle = 0;
          //         }
          //     },
          //     0.5,
          //     4
          // );
        };

        _proto.resetInEditor = function resetInEditor() {
          this.init();
        };
        _proto.init = function init() {
          this.sprite = this.getComponent(Sprite);
          // 假设材质一定存在，直接获取
          this.material = this.sprite.material;
          this.initUniformHandles();
          this.updateMaterialProperties();
        }

        /**
         * 初始化所有uniform句柄
         */;
        _proto.initUniformHandles = function initUniformHandles() {
          var _this$material;
          var pass = (_this$material = this.material) == null ? void 0 : _this$material.passes[this.passIndex];
          if (!pass) {
            return;
          }
          this.progressHandle = pass.getHandle('progress');
          this.innerRadiusHandle = pass.getHandle('innerRadius');
          this.outerRadiusHandle = pass.getHandle('outerRadius');
          this.startAngleHandle = pass.getHandle('startAngle');
          this.ringColorHandle = pass.getHandle('ringColor');
          this.smoothnessHandle = pass.getHandle('smoothness');
          this.reverseHandle = pass.getHandle('reverse');
          this.centerHandle = pass.getHandle('center');
        };
        _proto.updateMaterialProperties = function updateMaterialProperties() {
          var _this$material2;
          var pass = (_this$material2 = this.material) == null ? void 0 : _this$material2.passes[this.passIndex];
          if (!pass) {
            return;
          }
          pass.setUniform(this.progressHandle, this._progress);
          pass.setUniform(this.innerRadiusHandle, this._innerRadius);
          pass.setUniform(this.outerRadiusHandle, this._outerRadius);
          pass.setUniform(this.startAngleHandle, this._startAngle);
          pass.setUniform(this.ringColorHandle, this._ringColor);
          pass.setUniform(this.smoothnessHandle, this._smoothness);
          pass.setUniform(this.reverseHandle, this._reverse ? 1 : 0);
          pass.setUniform(this.centerHandle, this._center);
        }

        // Getters and setters to automatically update material when properties change
        ;

        _createClass(CircularProgressBar, [{
          key: "progress",
          get: function get() {
            return this._progress;
          },
          set: function set(value) {
            var _this$material3;
            this._progress = value;
            (_this$material3 = this.material) == null || _this$material3.passes[this.passIndex].setUniform(this.progressHandle, this._progress);
          }
        }, {
          key: "innerRadius",
          get: function get() {
            return this._innerRadius;
          },
          set: function set(value) {
            var _this$material4;
            this._innerRadius = value;
            (_this$material4 = this.material) == null || _this$material4.passes[this.passIndex].setUniform(this.innerRadiusHandle, this._innerRadius);
          }
        }, {
          key: "outerRadius",
          get: function get() {
            return this._outerRadius;
          },
          set: function set(value) {
            var _this$material5;
            this._outerRadius = value;
            (_this$material5 = this.material) == null || _this$material5.passes[this.passIndex].setUniform(this.outerRadiusHandle, this._outerRadius);
          }
        }, {
          key: "startAngle",
          get: function get() {
            return this._startAngle;
          },
          set: function set(value) {
            var _this$material6;
            this._startAngle = value;
            (_this$material6 = this.material) == null || _this$material6.passes[this.passIndex].setUniform(this.startAngleHandle, this._startAngle);
          }
        }, {
          key: "ringColor",
          get: function get() {
            return this._ringColor;
          },
          set: function set(value) {
            var _this$material7;
            this._ringColor = value;
            (_this$material7 = this.material) == null || _this$material7.passes[this.passIndex].setUniform(this.ringColorHandle, this._ringColor);
          }
        }, {
          key: "smoothness",
          get: function get() {
            return this._smoothness;
          },
          set: function set(value) {
            var _this$material8;
            this._smoothness = value;
            (_this$material8 = this.material) == null || _this$material8.passes[this.passIndex].setUniform(this.smoothnessHandle, this._smoothness);
          }
        }, {
          key: "reverse",
          get: function get() {
            return this._reverse;
          },
          set: function set(value) {
            var _this$material9;
            this._reverse = value;
            (_this$material9 = this.material) == null || _this$material9.passes[this.passIndex].setUniform(this.reverseHandle, this._reverse ? 1 : 0);
          }
        }, {
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(value) {
            var _this$material10;
            this._center = value;
            (_this$material10 = this.material) == null || _this$material10.passes[this.passIndex].setUniform(this.centerHandle, this._center);
          }
        }]);
        return CircularProgressBar;
      }(Component), (_descriptor$5 = _applyDecoratedDescriptor(_class2$5.prototype, "_progress", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor2$5 = _applyDecoratedDescriptor(_class2$5.prototype, "_innerRadius", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.3;
        }
      }), _descriptor3$5 = _applyDecoratedDescriptor(_class2$5.prototype, "_outerRadius", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.45;
        }
      }), _descriptor4$3 = _applyDecoratedDescriptor(_class2$5.prototype, "_startAngle", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor5$2 = _applyDecoratedDescriptor(_class2$5.prototype, "_ringColor", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return Color.WHITE.clone();
        }
      }), _descriptor6$2 = _applyDecoratedDescriptor(_class2$5.prototype, "_smoothness", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.02;
        }
      }), _descriptor7$2 = _applyDecoratedDescriptor(_class2$5.prototype, "_reverse", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor8$2 = _applyDecoratedDescriptor(_class2$5.prototype, "_center", [property$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec2(0.5, 0.5);
        }
      }), _applyDecoratedDescriptor(_class2$5.prototype, "progress", [_dec5$7], Object.getOwnPropertyDescriptor(_class2$5.prototype, "progress"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "innerRadius", [_dec6$5], Object.getOwnPropertyDescriptor(_class2$5.prototype, "innerRadius"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "outerRadius", [_dec7$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "outerRadius"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "startAngle", [_dec8$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "startAngle"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "ringColor", [_dec9$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "ringColor"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "smoothness", [_dec10$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "smoothness"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "reverse", [_dec11$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "reverse"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "center", [_dec12$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "center"), _class2$5.prototype)), _class2$5)) || _class$f) || _class$f) || _class$f) || _class$f);
      cclegacy._RF.pop();
      var _dec$f, _dec2$f, _dec3$f, _dec4$c, _dec5$8, _class$g, _class2$6, _descriptor$6, _descriptor2$6;
      cclegacy._RF.push({}, "df646oVIS1NrqANOA/msrs/", "NotificationPanel", undefined);
      // import { runAllTests } from '@/Test/NotificationPanel.test.ts';

      var ccclass$f = _decorator.ccclass,
        menu$e = _decorator.menu,
        disallowMultiple$f = _decorator.disallowMultiple,
        property$7 = _decorator.property;

      /**
       * 通知消息数据结构
       */

      /**
       * 活跃通知项数据（内部使用）
       */

      /**
       * 通知面板组件
       *
       * 用于在屏幕角落显示通知消息队列，支持显示时长控制、最大等待时间限制和富文本显示。
       *
       * ## 工作原理
       * 1. 新建通知时，在预定的节点池中查找可用的非活跃节点
       * 2. 找到可用节点后，设置富文本内容并激活该节点
       * 3. 将该通知插入到显示队列的末尾
       * 4. 建立对应的定时器，定时器结束时使节点失活，并尝试显示下一条待显示消息
       *
       * ## 核心参数
       * - `content`: 消息内容，支持富文本标签
       * - `displayTime`: 显示时长（秒），0表示不自动消失
       * - `maxWaitTime`: 最大等待时长（秒），消息在待显示队列中超过此时间将被移除，0表示无限制
       *
       * ## 富文本标签支持
       * - `<color=#hex>文本</color>` - 颜色设置
       * - `<size=数字>文本</size>` - 字体大小
       * - `<b>文本</b>` - 粗体
       * - `<i>文本</i>` - 斜体
       * - `<u>文本</u>` - 下划线
       * - `<br/>` - 换行
       * - `<img src='spriteframe名称' />` - 图片（需在ImageAtlas中配置）
       * - `<img src='spriteframe名称' width=50 height=50 />` - 指定尺寸的图片
       * - `<img src='spriteframe名称' align=center />` - 指定对齐方式的图片
       */
      var NotificationPanel = (_dec$f = ccclass$f('NotificationPanel'), _dec2$f = menu$e('UI/NotificationPanel'), _dec3$f = disallowMultiple$f(true), _dec4$c = property$7({
        visible: true,
        type: Node,
        tooltip: '消息列表容器节点（富文本行的父节点）'
      }), _dec5$8 = property$7({
        visible: true,
        tooltip: '最大同时显示的消息数量',
        min: 1
      }), _dec$f(_class$g = _dec2$f(_class$g = _dec3$f(_class$g = (_class2$6 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(NotificationPanel, _Component);
        function NotificationPanel() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          // ==================== 属性配置 ====================
          /**
           * 消息列表容器节点（富文本节点的父节点）
           */
          _initializerDefineProperty(_this, "_container", _descriptor$6, _assertThisInitialized(_this));
          /**
           * 最大同时显示的消息数量
           */
          _initializerDefineProperty(_this, "_maxDisplayCount", _descriptor2$6, _assertThisInitialized(_this));
          // ==================== 私有字段 ====================
          /**
           * 待显示消息队列（先进先出）
           */
          _this._pendingQueue = [];
          /**
           * 当前正在显示的通知项列表
           */
          _this._activeNotifications = [];
          /**
           * 通知ID生成计数器
           */
          _this._notificationIdCounter = 0;
          return _this;
        }
        var _proto = NotificationPanel.prototype;
        // ==================== 生命周期 ====================
        /**
         * 组件加载时初始化
         */
        _proto.onLoad = function onLoad() {
          this._initialize();
          // runAllTests(this);
        }

        // ==================== 初始化方法 ====================

        /**
         * 初始化通知面板组件
         */;
        _proto._initialize = function _initialize() {
          // 如果未配置容器节点，则使用当前节点作为容器
          if (!this._container) {
            this._container = this.node;
          }
        }

        // ==================== 公共API ====================

        /**
         * 添加通知消息到显示队列
         * @param messageData 消息数据（不包含id）
         * @returns 通知ID，可用于后续操作（如移除通知）
         */;
        _proto.addNotification = function addNotification(messageData) {
          var _this2 = this;
          // 生成唯一通知ID
          var notificationId = "notification_" + ++this._notificationIdCounter;
          var messageWithId = _extends({}, messageData, {
            id: notificationId
          });

          // 将消息添加到待显示队列
          this._pendingQueue.push(messageWithId);
          var maxWaitTimerFunc;
          // 如果设置了最大等待时间，创建销毁计时器
          if (messageData.maxWaitTime > 0) {
            maxWaitTimerFunc = function maxWaitTimerFunc() {
              _this2.destroyNotification(notificationId);
            };
            this.scheduleOnce(maxWaitTimerFunc, messageData.maxWaitTime);
          } else {
            maxWaitTimerFunc = undefined;
          }
          // 保存定时器引用以便后续取消
          messageWithId.maxWaitTimerFunc = maxWaitTimerFunc;

          // 尝试显示消息
          this._tryDisplayNextMessage();
          return notificationId;
        }

        // ==================== 私有方法 ====================

        /**
         * 尝试显示下一条待显示消息
         */;
        _proto._tryDisplayNextMessage = function _tryDisplayNextMessage() {
          // 如果待显示队列为空或已达到最大显示数量，无需处理
          if (this._pendingQueue.length === 0 || this._activeNotifications.length >= this._maxDisplayCount) {
            return;
          }

          // 取出队列中的第一条消息
          var messageData = this._pendingQueue.shift();
          if (!messageData) {
            return;
          }

          // 尝试创建并显示消息
          var displaySuccess = this._createAndDisplayNotification(messageData);
          if (!displaySuccess) {
            // 如果创建失败（没有可用节点），将消息重新放回队列开头
            this._pendingQueue.unshift(messageData);
          } else {
            // 如果创建成功，递归尝试显示下一条消息
            this._tryDisplayNextMessage();
          }
        }

        /**
         * 创建并显示通知项
         * @param messageData 消息数据
         * @returns 是否创建成功
         */;
        _proto._createAndDisplayNotification = function _createAndDisplayNotification(messageData) {
          var _this3 = this;
          // 查找可用的非活跃节点
          var availableNode = this._findAvailableNode();

          // 如果没有可用节点，返回false
          if (!availableNode) {
            return false;
          }

          // 获取富文本组件
          var richTextComponent = availableNode.getComponent(RichText);

          // 创建通知项
          var notificationItem = {
            id: messageData.id,
            node: availableNode,
            richText: richTextComponent,
            message: messageData,
            maxWaitTimerCallback: messageData.maxWaitTimerFunc
          };

          // 设置富文本内容
          notificationItem.richText.string = messageData.content;

          // 如果设置了显示时长，创建显示定时器
          if (messageData.displayTime > 0) {
            var displayTimerCallback = function displayTimerCallback() {
              return _this3.removeNotification(messageData.id);
            };
            this.scheduleOnce(displayTimerCallback, messageData.displayTime);
            notificationItem.displayTimerCallback = displayTimerCallback;
          }

          // 添加到活跃通知列表末尾
          this._activeNotifications.push(notificationItem);
          this._container.insertChild(availableNode, this._container.children.length);

          // 启用节点
          availableNode.active = true;
          return true;
        }

        /**
         * 查找可用的非活跃节点（从上到下遍历）
         * @returns 可用的节点，如果没有则返回undefined
         */;
        _proto._findAvailableNode = function _findAvailableNode() {
          return this._container.children.find(function (node) {
            return !node.active;
          });
        }

        /**
         * 取消通知的定时器
         * @param item 通知项
         */;
        _proto._cancelNotificationTimers = function _cancelNotificationTimers(item) {
          if (item.displayTimerCallback) {
            this.unschedule(item.displayTimerCallback);
          }
          if (item.maxWaitTimerCallback) {
            this.unschedule(item.maxWaitTimerCallback);
          }
        }

        // ==================== 公共API（续） ====================

        /**
         * 移除当前正在显示的通知
         * @param notificationId 通知ID
         */;
        _proto.removeNotification = function removeNotification(notificationId) {
          // 从活跃通知列表中查找指定ID的通知
          var itemIndex = this._activeNotifications.findIndex(function (item) {
            return item.id === notificationId;
          });
          if (itemIndex === -1) {
            return;
          }
          var notificationItem = this._activeNotifications[itemIndex];

          // 取消所有相关定时器
          this._cancelNotificationTimers(notificationItem);

          // 禁用对应节点
          if (notificationItem.node) {
            notificationItem.node.active = false;
          }

          // 从活跃通知列表中移除
          this._activeNotifications.splice(itemIndex, 1);

          // 尝试显示下一条待显示消息
          this._tryDisplayNextMessage();
        }

        /**
         * 销毁通知消息（不论是否正在显示）
         * @param notificationId 通知ID
         */;
        _proto.destroyNotification = function destroyNotification(notificationId) {
          // 首先尝试从待显示队列中移除
          var queueIndex = this._pendingQueue.findIndex(function (message) {
            return message.id === notificationId;
          });
          if (queueIndex !== -1) {
            // 从待显示队列中移除，并清除可能存在的定时器
            var messageData = this._pendingQueue[queueIndex];
            if (messageData.maxWaitTimerFunc) {
              this.unschedule(messageData.maxWaitTimerFunc);
            }
            this._pendingQueue.splice(queueIndex, 1);
            return;
          }

          // 如果不在待显示队列中，尝试从活跃通知中移除
          var activeIndex = this._activeNotifications.findIndex(function (item) {
            return item.id === notificationId;
          });
          if (activeIndex !== -1) {
            this.removeNotification(notificationId);
          }
        }

        /**
         * 清除所有通知消息（包括待显示和正在显示的）
         */;
        _proto.clearAllNotifications = function clearAllNotifications() {
          // 清除所有活跃通知的定时器
          for (var _iterator = _createForOfIteratorHelperLoose(this._activeNotifications), _step; !(_step = _iterator()).done;) {
            var notificationItem = _step.value;
            this._cancelNotificationTimers(notificationItem);
          }

          // 清空所有队列
          this._activeNotifications = [];
          this._pendingQueue = [];

          // 禁用所有容器节点
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._container.children), _step2; !(_step2 = _iterator2()).done;) {
            var node = _step2.value;
            node.active = false;
          }
        }

        /**
         * 获取当前正在显示的通知数量
         * @returns 当前活跃通知数量
         */;
        _proto.getNotificationCount = function getNotificationCount() {
          return this._activeNotifications.length;
        }

        /**
         * 组件禁用时的清理工作
         */;
        _proto.onDisable = function onDisable() {
          // 清除所有通知
          this.clearAllNotifications();
        };
        return NotificationPanel;
      }(Component), (_descriptor$6 = _applyDecoratedDescriptor(_class2$6.prototype, "_container", [_dec4$c], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$6 = _applyDecoratedDescriptor(_class2$6.prototype, "_maxDisplayCount", [_dec5$8], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      })), _class2$6)) || _class$g) || _class$g) || _class$g);
      cclegacy._RF.pop();
      var _dec$g, _class$h;
      cclegacy._RF.push({}, "e5a25hGMbRDDIUqUhge8Z+6", "VScrollViewItem", undefined);
      var ccclass$g = _decorator.ccclass;
      var hasSorting2d = Sorting2D !== undefined;
      if (!hasSorting2d) {
        console.warn("\u274C\u5F53\u524D\u5F15\u64CE\u7248\u672C\u4E0D\u652F\u6301Sorting2D\u7EC4\u4EF6\uFF0C\u5982\u679C\u9700\u8981\u8BF7\u5207\u6362\u52303.8.7\u53CA\u4EE5\u4E0A\u7248\u672C");
      }

      /**
       * 更改UI节点的渲染排序层级
       * @param sortingNode Node
       * @param sortingLayer number
       * @param sortingOrder number
       */
      function changeUISortingLayer(sortingNode, sortingLayer, sortingOrder) {
        if (!hasSorting2d) {
          return;
        }
        var sortingLayers = settings.querySettings('engine', 'sortingLayers');

        //编辑器bug,默认有default,但是读取出来没有,需要自己配置一个后才会有默认数据.
        if (!sortingLayers || sortingLayers.length === 0) {
          sortingLayers = [{
            id: 0,
            value: 0,
            name: 'default'
          }];
        }
        var result = sortingLayers.find(function (layer) {
          return layer.value === sortingLayer;
        });
        //如果没有找到对应的layer,则使用引擎内置默认层,并给出警告
        if (!result) {
          console.warn("\u274C\u672A\u627E\u5230\u5BF9\u5E94\u7684sortingLayer:" + sortingLayer + "\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u5DF2\u5728\u9879\u76EE\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u8BE5\u5C42\u7EA7\u3002\u5C06\u4F7F\u7528\u9ED8\u8BA4\u5C42\u7EA7\u4EE3\u66FF\u3002");
          sortingLayer = sortingLayers[0].value;
        }
        var sort2d = sortingNode.getComponent(Sorting2D) || sortingNode.addComponent(Sorting2D);
        if (sort2d) {
          //@ts-ignore
          sort2d.sortingLayer = sortingLayer;
          if (sortingOrder !== undefined) {
            //@ts-ignore
            sort2d.sortingOrder = sortingOrder;
          }
        }
      }

      /**
       * 挂载在每个 item 预制体的根节点上
       * 负责处理点击逻辑，通过回调通知父组件
       */
      var VScrollViewItem = (_dec$g = ccclass$g('VScrollViewItem'), _dec$g(_class$h = /*#__PURE__*/function (_Component) {
        _inheritsLoose(VScrollViewItem, _Component);
        function VScrollViewItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          /** 当前 item 对应的数据索引 */
          _this.dataIndex = -1;
          _this.useItemClickEffect = true;
          /** 点击回调（由 VirtualScrollView 注入） */
          _this.onClickCallback = null;
          /** 长按回调（由 VirtualScrollView 注入） */
          _this.onLongPressCallback = null;
          /** 长按触发时长（秒） */
          _this.longPressTime = 0.6;
          _this._touchStartNode = null;
          _this._isCanceled = false;
          _this._startPos = new Vec2();
          _this._moveThreshold = 40;
          // 滑动阈值
          _this._clickThreshold = 10;
          // 点击阈值
          _this._longPressTimer = 0;
          // 长按计时器
          _this._isLongPressed = false;
          return _this;
        }
        var _proto = VScrollViewItem.prototype;
        // 是否已触发长按
        _proto.onLoad = function onLoad() {
          // 一次性注册事件，生命周期内不变
          this.node.on(Node.EventType.TOUCH_START, this._onTouchStart, this);
          this.node.on(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.on(Node.EventType.TOUCH_END, this._onTouchEnd, this);
          this.node.on(Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
        };
        _proto.start = function start() {
          // this.onSortLayer();
        };
        _proto.onDestroy = function onDestroy() {
          // 清理事件
          this.node.off(Node.EventType.TOUCH_START, this._onTouchStart, this);
          this.node.off(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.off(Node.EventType.TOUCH_END, this._onTouchEnd, this);
          this.node.off(Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
        }

        /**
         * 将所有子节点的 Label 组件渲染单独排序在一起,并且item的每个lable组件都独立一个orderNumber,以免交错断合批
         * @param node
         */;
        _proto.onSortLayer = function onSortLayer() {
          var orderNumber = 1;
          var labels = this.node.getComponentsInChildren(Label);
          for (var i = 0; i < labels.length; i++) {
            changeUISortingLayer(labels[i].node, 0, orderNumber);
            orderNumber++;
          }
        }

        /** 关闭渲染分层 */;
        _proto.offSortLayer = function offSortLayer() {
          var orderNumber = 0;
          var labels = this.node.getComponentsInChildren(Label);
          for (var i = 0; i < labels.length; i++) {
            changeUISortingLayer(labels[i].node, 0, orderNumber);
            // const item = labels[i];
            // const sort2d = item.node.getComponent(Sorting2D);
            // sort2d && (sort2d.enabled = false);
            // orderNumber++;
          }
        }

        /** 外部调用：更新数据索引 */;
        _proto.setDataIndex = function setDataIndex(index) {
          this.dataIndex = index;
        };
        _proto.update = function update(dt) {
          // 如果正在触摸且未取消，累加长按计时
          if (this._touchStartNode && !this._isCanceled && !this._isLongPressed) {
            this._longPressTimer += dt;
            if (this._longPressTimer >= this.longPressTime) {
              this._triggerLongPress();
            }
          }
        };
        _proto._triggerLongPress = function _triggerLongPress() {
          this._isLongPressed = true;
          if (this.onLongPressCallback) {
            this.onLongPressCallback(this.dataIndex);
          }
          // 触发长按后恢复缩放
          this._restoreScale();
        };
        _proto._onTouchStart = function _onTouchStart(e) {
          // console.log("_onTouchStart");
          this._touchStartNode = this.node;
          this._isCanceled = false;
          this._isLongPressed = false;
          this._longPressTimer = 0;
          e.getLocation(this._startPos);

          // 缩放反馈（假设第一个子节点是内容容器）
          if (this.useItemClickEffect && this.node.children.length > 0) {
            this.node.setScale(0.95, 0.95);
          }
        };
        _proto._onTouchMove = function _onTouchMove(e) {
          if (this._isCanceled) return;
          var movePos = e.getLocation();
          var dx = movePos.x - this._startPos.x;
          var dy = movePos.y - this._startPos.y;
          var dist = Math.sqrt(dx * dx + dy * dy);

          // 超过阈值认为是滑动，取消点击和长按
          if (dist > this._moveThreshold) {
            this._isCanceled = true;
            this._restoreScale();
            this._touchStartNode = null;
          }
        };
        _proto._onTouchEnd = function _onTouchEnd(e) {
          if (this._isCanceled) {
            this._reset();
            return;
          }

          // 如果已经触发了长按，不再触发点击
          if (this._isLongPressed) {
            this._reset();
            return;
          }
          this._restoreScale();
          var endPos = e.getLocation();
          var dx = endPos.x - this._startPos.x;
          var dy = endPos.y - this._startPos.y;
          var dist = Math.sqrt(dx * dx + dy * dy);

          // 移动距离小于阈值才算点击
          if (dist < this._clickThreshold && this._touchStartNode === this.node) {
            if (this.onClickCallback) {
              this.onClickCallback(this.dataIndex);
            }
          }
          this._reset();
        };
        _proto._onTouchCancel = function _onTouchCancel(e) {
          this._restoreScale();
          this._reset();
        };
        _proto._restoreScale = function _restoreScale() {
          if (this.useItemClickEffect && this.node.children.length > 0) {
            this.node.setScale(1.0, 1.0);
          }
        };
        _proto._reset = function _reset() {
          this._touchStartNode = null;
          this._isCanceled = false;
          this._longPressTimer = 0;
          this._isLongPressed = false;
        };
        return VScrollViewItem;
      }(Component)) || _class$h);
      cclegacy._RF.pop();
      var _dec$h, _dec2$g, _dec3$g, _dec4$d, _dec5$9, _dec6$6, _dec7$3, _dec8$3, _dec9$3, _dec10$3, _dec11$3, _dec12$3, _dec13$2, _dec14$2, _dec15$2, _dec16$1, _dec17$1, _dec18$1, _dec19$1, _dec20$1, _dec21$1, _dec22$1, _dec23$1, _dec24$1, _dec25$1, _dec26$1, _dec27$1, _dec28$1, _dec29$1, _dec30$1, _dec31$1, _dec32$1, _dec33$1, _dec34$1, _dec35$1, _dec36$1, _dec37$1, _dec38$1, _dec39, _dec40, _dec41, _dec42, _class2$7, _class3, _descriptor$7, _descriptor2$7, _descriptor3$6, _descriptor4$4, _descriptor5$3, _descriptor6$3, _descriptor7$3, _descriptor8$3, _descriptor9$2, _descriptor10$2, _descriptor11$2, _descriptor12$2, _descriptor13$1, _descriptor14$1, _descriptor15$1, _descriptor16$1, _descriptor17$1, _descriptor18$1, _descriptor19$1, _descriptor20$1, _descriptor21$1, _descriptor22, _descriptor23, _descriptor24, _descriptor25, _descriptor26, _descriptor27, _descriptor28, _descriptor29, _descriptor30, _descriptor31, _descriptor32, _descriptor33, _descriptor34, _descriptor35, _descriptor36, _descriptor37, _descriptor38, _descriptor39, _descriptor40;
      cclegacy._RF.push({}, "544earF5qRLB4JTuTnSr11+", "VScrollView", undefined);
      var ccclass$h = _decorator.ccclass,
        property$8 = _decorator.property,
        menu$f = _decorator.menu;
      var InternalNodePool = /*#__PURE__*/function () {
        function InternalNodePool(prefabs, nodes) {
          this.pools = new Map();
          this.prefabs = [];
          this.nodes = [];
          this.useNodeMode = false;
          this.prefabs = prefabs;
          this.nodes = nodes || [];
          this.useNodeMode = nodes && nodes.length > 0;
          var count = this.useNodeMode ? nodes.length : prefabs.length;
          for (var i = 0; i < count; i++) {
            this.pools.set(i, []);
          }
        }
        var _proto = InternalNodePool.prototype;
        _proto.get = function get(typeIndex) {
          var pool = this.pools.get(typeIndex);
          if (!pool) {
            console.error("[VScrollView NodePool] \u7C7B\u578B " + typeIndex + " \u4E0D\u5B58\u5728");
            return null;
          }
          if (pool.length > 0) {
            var _node = pool.pop();
            _node.active = true;
            return _node;
          }
          var newNode;
          if (this.useNodeMode) {
            var sourceNode = this.nodes[typeIndex];
            if (!sourceNode) {
              console.error("[VScrollView NodePool] Node \u7C7B\u578B " + typeIndex + " \u6A21\u677F\u4E0D\u5B58\u5728");
              return null;
            }
            newNode = instantiate(sourceNode);
          } else {
            var sourcePrefab = this.prefabs[typeIndex];
            if (!sourcePrefab) {
              console.error("[VScrollView NodePool] Prefab \u7C7B\u578B " + typeIndex + " \u6A21\u677F\u4E0D\u5B58\u5728");
              return null;
            }
            newNode = instantiate(sourcePrefab);
          }
          return newNode;
        };
        _proto.put = function put(node, typeIndex) {
          if (!node) return;
          var pool = this.pools.get(typeIndex);
          if (!pool) {
            console.error("[VScrollView NodePool] \u7C7B\u578B " + typeIndex + " \u4E0D\u5B58\u5728");
            node.destroy();
            return;
          }
          node.active = false;
          node.removeFromParent();
          pool.push(node);
        };
        _proto.clear = function clear() {
          this.pools.forEach(function (pool) {
            pool.forEach(function (node) {
              return node.destroy();
            });
            pool.length = 0;
          });
          this.pools.clear();
        };
        _proto.getStats = function getStats() {
          var stats = {};
          this.pools.forEach(function (pool, type) {
            stats["type" + type] = pool.length;
          });
          return stats;
        };
        return InternalNodePool;
      }(); // 刷新状态回调
      // 加载更多状态回调
      // 分页吸附回调
      var ScrollDirection = /*#__PURE__*/function (ScrollDirection) {
        ScrollDirection[ScrollDirection["VERTICAL"] = 0] = "VERTICAL";
        ScrollDirection[ScrollDirection["HORIZONTAL"] = 1] = "HORIZONTAL";
        return ScrollDirection;
      }({});
      var ItemCreationMode = /*#__PURE__*/function (ItemCreationMode) {
        ItemCreationMode[ItemCreationMode["NODE"] = 0] = "NODE";
        ItemCreationMode[ItemCreationMode["PREFAB"] = 1] = "PREFAB";
        return ItemCreationMode;
      }({});

      // 添加刷新状态枚举
      var RefreshState = /*#__PURE__*/function (RefreshState) {
        RefreshState[RefreshState["IDLE"] = 0] = "IDLE";
        RefreshState[RefreshState["PULLING"] = 1] = "PULLING";
        RefreshState[RefreshState["READY"] = 2] = "READY";
        RefreshState[RefreshState["REFRESHING"] = 3] = "REFRESHING";
        RefreshState[RefreshState["COMPLETE"] = 4] = "COMPLETE";
        return RefreshState;
      }({}); // 刷新完成
      var LoadMoreState = /*#__PURE__*/function (LoadMoreState) {
        LoadMoreState[LoadMoreState["IDLE"] = 0] = "IDLE";
        LoadMoreState[LoadMoreState["PULLING"] = 1] = "PULLING";
        LoadMoreState[LoadMoreState["READY"] = 2] = "READY";
        LoadMoreState[LoadMoreState["LOADING"] = 3] = "LOADING";
        LoadMoreState[LoadMoreState["COMPLETE"] = 4] = "COMPLETE";
        LoadMoreState[LoadMoreState["NO_MORE"] = 5] = "NO_MORE";
        return LoadMoreState;
      }({}); // 没有更多数据
      var VirtualScrollView = (_dec$h = ccclass$h('VirtualScrollView'), _dec2$g = menu$f('2D/VirtualScrollView(虚拟滚动列表)'), _dec3$g = property$8({
        type: Node,
        displayName: '容器节点',
        tooltip: 'content 容器节点（在 Viewport 下）'
      }), _dec4$d = property$8({
        displayName: '启用虚拟列表',
        tooltip: '是否启用虚拟列表模式（关闭则仅提供滚动功能）'
      }), _dec5$9 = property$8({
        type: Enum(ScrollDirection),
        displayName: '滚动方向',
        tooltip: '滚动方向：纵向（向上）或横向（向左）'
      }), _dec6$6 = property$8({
        type: Enum(ItemCreationMode),
        displayName: '创建模式',
        tooltip: '使用 Node 或 Prefab 创建子项（默认 Prefab）',
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec7$3 = property$8({
        type: Node,
        displayName: '子项节点',
        tooltip: '可选：从 Node 创建 item（等大小模式）',
        visible: function visible() {
          return this.useVirtualList && !this.useDynamicSize && this.itemCreationMode === ItemCreationMode.NODE;
        }
      }), _dec8$3 = property$8({
        type: Prefab,
        displayName: '子项预制体',
        tooltip: '可选：从 Prefab 创建 item（等大小模式）',
        visible: function visible() {
          return this.useVirtualList && !this.useDynamicSize && this.itemCreationMode === ItemCreationMode.PREFAB;
        }
      }), _dec9$3 = property$8({
        displayName: '不等大小模式',
        tooltip: '启用不等大小模式',
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec10$3 = property$8({
        displayName: '自动居中布局',
        tooltip: '当子项数量少于行/列数时，自动居中显示（适用于等大小模式）',
        visible: function visible() {
          return this.useVirtualList && !this.useDynamicSize;
        }
      }), _dec11$3 = property$8({
        displayName: '启用分页吸附',
        tooltip: '滚动结束后自动吸附到最近的 item 位置'
      }), _dec12$3 = property$8({
        displayName: '===吸附动画时长',
        tooltip: '吸附动画的持续时间（秒）',
        range: [0.1, 1, 0.05],
        visible: function visible() {
          return this.enablePageSnap;
        }
      }), _dec13$2 = property$8({
        displayName: '===切页距离比例',
        tooltip: '滑动距离超过页面尺寸的此比例时翻页（0.1-0.5）',
        range: [0.1, 0.5, 0.05],
        visible: function visible() {
          return this.enablePageSnap;
        }
      }), _dec14$2 = property$8({
        displayName: '===吸附触发速度',
        tooltip: '惯性速度低于此值时触发吸附（越大越早吸附）',
        range: [50, 3000, 10],
        visible: function visible() {
          return this.enablePageSnap;
        }
      }), _dec15$2 = property$8({
        displayName: '不等高模式（已废弃,仅保持兼容）',
        tooltip: '启用不等高模式（已废弃,仅保持兼容,请使用 useDynamicSize ）'
      }), _dec16$1 = property$8({
        displayName: '列数（已废弃,仅保持兼容）',
        tooltip: '列数（已废弃,请使用 gridCount 替代，仅保持兼容）'
      }), _dec17$1 = property$8({
        displayName: '列间距（已废弃,仅保持兼容）',
        tooltip: '列间距（已废弃,请使用 gridSpacing 替代，仅保持兼容）'
      }), _dec18$1 = property$8({
        type: [Node],
        displayName: '子项节点数组',
        tooltip: '不等大小模式：预先提供的子项节点数组（可在编辑器拖入）',
        visible: function visible() {
          return this.useVirtualList && this.useDynamicSize && this.itemCreationMode === ItemCreationMode.NODE;
        }
      }), _dec19$1 = property$8({
        type: [Prefab],
        displayName: '子项预制体数组',
        tooltip: '不等大小模式：预先提供的子项预制体数组（可在编辑器拖入）',
        visible: function visible() {
          return this.useVirtualList && this.useDynamicSize && this.itemCreationMode === ItemCreationMode.PREFAB;
        }
      }), _dec20$1 = property$8({
        displayName: '行/列数',
        tooltip: '纵向模式为列数，横向模式为行数',
        range: [1, 10, 1],
        visible: function visible() {
          return this.useVirtualList && !this.useDynamicSize;
        }
      }), _dec21$1 = property$8({
        displayName: '副方向间距',
        tooltip: '主方向垂直方向的间距（像素）',
        range: [0, 1000, 1],
        visible: function visible() {
          return this.useVirtualList && !this.useDynamicSize;
        }
      }), _dec22$1 = property$8({
        displayName: '主方向间距',
        tooltip: '主方向的间距（像素）',
        range: [0, 1000, 1],
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec23$1 = property$8({
        displayName: '头部间距',
        tooltip: '列表头部的额外间距（纵向为顶部，横向为左侧）',
        range: [0, 1000, 1],
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec24$1 = property$8({
        displayName: '尾部间距',
        tooltip: '列表尾部的额外间距（纵向为底部，横向为右侧）',
        range: [0, 1000, 1],
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec25$1 = property$8({
        displayName: '总条数',
        tooltip: '总条数（可在运行时 setTotalCount 动态修改）',
        range: [0, 1000, 1],
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec26$1 = property$8({
        displayName: '额外缓冲',
        tooltip: '额外缓冲（可视区外多渲染几条，避免边缘复用闪烁）',
        range: [0, 10, 1],
        visible: function visible() {
          return this.useVirtualList;
        }
      }), _dec27$1 = property$8({
        displayName: '启用下拉刷新',
        tooltip: '是否启用下拉刷新功能'
      }), _dec28$1 = property$8({
        displayName: '===下拉触发距离',
        tooltip: '下拉多少距离触发刷新（像素）',
        range: [50, 500, 10],
        visible: function visible() {
          return this.enablePullRefresh;
        }
      }), _dec29$1 = property$8({
        displayName: '===下拉最大距离',
        tooltip: '下拉的最大阻尼距离（像素）',
        range: [100, 1000, 10],
        visible: function visible() {
          return this.enablePullRefresh;
        }
      }), _dec30$1 = property$8({
        displayName: '启用上拉加载',
        tooltip: '是否启用上拉加载更多功能'
      }), _dec31$1 = property$8({
        displayName: '===上拉触发距离',
        tooltip: '距离底部多少距离触发加载（像素）',
        range: [50, 500, 10],
        visible: function visible() {
          return this.enableLoadMore;
        }
      }), _dec32$1 = property$8({
        displayName: '===上拉最大距离',
        tooltip: '上拉的最大阻尼距离（像素）',
        range: [100, 1000, 10],
        visible: function visible() {
          return this.enableLoadMore;
        }
      }), _dec33$1 = property$8({
        displayName: '拉动阻尼系数',
        tooltip: '拉动时的阻尼系数（0-1），越小越难拉',
        range: [0.1, 1, 0.05],
        visible: function visible() {
          return this.enablePullRefresh || this.enableLoadMore;
        }
      }), _dec34$1 = property$8({
        displayName: '像素对齐',
        tooltip: '是否启用像素对齐'
      }), _dec35$1 = property$8({
        displayName: '禁用越界滚动',
        tooltip: '是否禁用越界滚动（开启后将无法滚动到边界之外）'
      }), _dec36$1 = property$8({
        displayName: '惯性阻尼系数',
        tooltip: '指数衰减系数，越大减速越快',
        range: [0, 10, 0.5]
      }), _dec37$1 = property$8({
        displayName: '弹簧刚度',
        tooltip: '越界弹簧刚度 K（建议 120–240）'
      }), _dec38$1 = property$8({
        displayName: '弹簧阻尼',
        tooltip: '越界阻尼 C（建议 22–32）'
      }), _dec39 = property$8({
        displayName: '速度阈值',
        tooltip: '速度阈值（像素/秒），低于即停止'
      }), _dec40 = property$8({
        displayName: '速度窗口',
        tooltip: '速度估计窗口（秒）'
      }), _dec41 = property$8({
        displayName: '最大惯性速度',
        tooltip: '最大惯性速度（像素/秒）'
      }), _dec42 = property$8({
        displayName: 'iOS减速曲线',
        tooltip: '是否使用 iOS 风格的减速曲线'
      }), _dec$h(_class2$7 = _dec2$g(_class2$7 = (_class3 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(VirtualScrollView, _Component);
        function VirtualScrollView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "content", _descriptor$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "useVirtualList", _descriptor2$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "direction", _descriptor3$6, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemCreationMode", _descriptor4$4, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemNode", _descriptor5$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemPrefab", _descriptor6$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "useDynamicSize", _descriptor7$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "autoCenter", _descriptor8$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enablePageSnap", _descriptor9$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pageSnapDuration", _descriptor10$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pageSnapDistanceRatio", _descriptor11$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pageSnapTriggerVelocity", _descriptor12$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "useDynamicHeight", _descriptor13$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "columns", _descriptor14$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "columnSpacing", _descriptor15$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemNodes", _descriptor16$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemPrefabs", _descriptor17$1, _assertThisInitialized(_this));
          _this.itemMainSize = 100;
          _this.itemCrossSize = 100;
          _initializerDefineProperty(_this, "gridCount", _descriptor18$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "gridSpacing", _descriptor19$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "spacing", _descriptor20$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "headerSpacing", _descriptor21$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "footerSpacing", _descriptor22, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "totalCount", _descriptor23, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "buffer", _descriptor24, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enablePullRefresh", _descriptor25, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pullRefreshThreshold", _descriptor26, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pullRefreshMaxOffset", _descriptor27, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enableLoadMore", _descriptor28, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "loadMoreThreshold", _descriptor29, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "loadMoreMaxOffset", _descriptor30, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pullDampingRate", _descriptor31, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pixelAlign", _descriptor32, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "disableBounce", _descriptor33, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "inertiaDampK", _descriptor34, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "springK", _descriptor35, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "springC", _descriptor36, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "velocitySnap", _descriptor37, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "velocityWindow", _descriptor38, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "maxVelocity", _descriptor39, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "useIOSDecelerationCurve", _descriptor40, _assertThisInitialized(_this));
          _this.renderItemFn = null;
          _this.provideNodeFn = null;
          _this.onItemClickFn = null;
          _this.onItemLongPressFn = null;
          _this.playItemAppearAnimationFn = null;
          _this.getItemHeightFn = null;
          _this.getItemTypeIndexFn = null;
          _this.onRefreshStateChangeFn = null;
          _this.onLoadMoreStateChangeFn = null;
          _this.onPageChangeFn = null;
          _this._viewportSize = 0;
          _this._contentSize = 0;
          _this._boundsMin = 0;
          _this._boundsMax = 0;
          _this._velocity = 0;
          _this._isTouching = false;
          _this._velSamples = [];
          _this._slotNodes = [];
          _this._slots = 0;
          _this._slotFirstIndex = 0;
          _this._itemSizes = [];
          _this._prefixPositions = [];
          _this._prefabSizeCache = new Map();
          _this._nodePool = null;
          _this._slotPrefabIndices = [];
          _this._needAnimateIndices = new Set();
          _this._initSortLayerFlag = true;
          _this._scrollTween = null;
          _this._tmpMoveVec2 = new Vec2();
          // 私有状态变量
          _this._refreshState = RefreshState.IDLE;
          _this._loadMoreState = LoadMoreState.IDLE;
          _this._pullOffset = 0;
          // 当前下拉偏移量
          _this._loadOffset = 0;
          // 当前上拉偏移量
          _this._isRefreshing = false;
          _this._isLoadingMore = false;
          _this._hasMore = true;
          // 是否还有更多数据
          // 分页吸附相关
          _this._currentPageIndex = 0;
          _this._pageStartPos = 0;
          // 记录触摸开始时的位置
          _this._touchStartPos = new Vec2();
          _this._hasDeterminedScrollDirection = false;
          _this._shouldBlockParent = false;
          _this._scrollDirectionThreshold = 15;
          // 滑动阈值（像素）
          _this._scrollAngleThreshold = 30;
          // 角度阈值（度）
          // 等大小模式下，从 content 子节点获取的模板节点
          _this._templateNode = null;
          return _this;
        }
        var _proto2 = VirtualScrollView.prototype;
        _proto2._getContentNode = function _getContentNode() {
          if (!this.content) {
            console.warn("[VirtualScrollView] :" + this.node.name + " \u8BF7\u5728\u5C5E\u6027\u9762\u677F\u7ED1\u5B9A content \u5BB9\u5668\u8282\u70B9");
            this.content = this.node.getChildByName('content');
          }
          return this.content;
        };
        _proto2._isVertical = function _isVertical() {
          return this.direction === ScrollDirection.VERTICAL;
        };
        _proto2._getViewportMainSize = function _getViewportMainSize() {
          return this._isVertical() ? this._viewportTf.height : this._viewportTf.width;
        };
        _proto2._getContentMainPos = function _getContentMainPos() {
          return this._isVertical() ? this.content.position.y : this.content.position.x;
        };
        _proto2._setContentMainPos = function _setContentMainPos(pos) {
          if (!Number.isFinite(pos)) return;
          if (this.pixelAlign) pos = Math.round(pos);
          var p = this.content.position;
          if (this._isVertical()) {
            if (pos === p.y) return;
            this.content.setPosition(p.x, pos, p.z);
          } else {
            if (pos === p.x) return;
            this.content.setPosition(pos, p.y, p.z);
          }
        };
        _proto2.start = /*#__PURE__*/function () {
          var _start = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
            var mask;
            return _regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  this.content = this._getContentNode();
                  if (this.content) {
                    _context.next = 3;
                    break;
                  }
                  return _context.abrupt("return");
                case 3:
                  mask = this.node.getComponent(Mask);
                  if (!mask) console.warn('[VirtualScrollView] 建议在视窗节点挂一个 Mask 组件用于裁剪');
                  this.gridCount = Math.max(1, Math.round(this.gridCount));
                  if (this.useVirtualList) {
                    _context.next = 13;
                    break;
                  }
                  this._viewportSize = this._getViewportMainSize();
                  this._contentSize = this._isVertical() ? this._contentTf.height : this._contentTf.width;
                  if (this._isVertical()) {
                    this._boundsMin = 0;
                    this._boundsMax = Math.max(0, this._contentSize - this._viewportSize);
                  } else {
                    this._boundsMin = -Math.max(0, this._contentSize - this._viewportSize);
                    this._boundsMax = 0;
                  }
                  this._bindTouch();
                  this._bindGlobalTouch();
                  return _context.abrupt("return");
                case 13:
                  // 等大小模式：如果没有预制体但 content 下有子节点，保存第一个子节点作为模板
                  if (!this.useDynamicSize && !this.itemPrefab && this.content.children.length > 0) {
                    this._templateNode = this.content.children[0];
                    this._templateNode.removeFromParent(); // 只移除，不销毁
                  }

                  this.content.removeAllChildren();
                  this._viewportSize = this._getViewportMainSize();
                  //兼容废弃属性
                  if (this.useDynamicHeight) {
                    this.useDynamicSize = true;
                  }

                  //兼容之前版本的参数
                  if (this.columns && this.direction === ScrollDirection.VERTICAL) {
                    this.gridCount = this.columns;
                  }
                  if (this.columnSpacing && this.direction === ScrollDirection.VERTICAL) {
                    this.gridSpacing = this.columnSpacing;
                  }
                  if (!this.useDynamicSize) {
                    _context.next = 24;
                    break;
                  }
                  _context.next = 22;
                  return this._initDynamicSizeMode();
                case 22:
                  _context.next = 26;
                  break;
                case 24:
                  _context.next = 26;
                  return this._initFixedSizeMode();
                case 26:
                  this._bindTouch();
                  this._bindGlobalTouch();
                case 28:
                case "end":
                  return _context.stop();
              }
            }, _callee, this);
          }));
          function start() {
            return _start.apply(this, arguments);
          }
          return start;
        }();
        _proto2.onEnable = function onEnable() {
          var _this2 = this;
          // 当节点激活时，重置组件状态，确保回弹等逻辑正常工作
          this._isTouching = false;
          this._velocity = 0;
          this._velSamples.length = 0;
          if (this._scrollTween) {
            this._scrollTween.stop();
            this._scrollTween = null;
          }
          // 如果位置超出边界，立即回弹到边界
          this.scheduleOnce(function () {
            if (_this2.content) {
              var pos = _this2._getContentMainPos();
              var minBound = Math.min(_this2._boundsMin, _this2._boundsMax);
              var maxBound = Math.max(_this2._boundsMin, _this2._boundsMax);
              if (pos < minBound || pos > maxBound) {
                var clampedPos = math$1.clamp(pos, minBound, maxBound);
                _this2._setContentMainPos(clampedPos);
                _this2._updateVisible(true);
              }
            }
          }, 0);
        };
        _proto2.onDisable = function onDisable() {
          // 当节点禁用时，清理触摸状态
          this._isTouching = false;
          if (this._scrollTween) {
            this._scrollTween.stop();
            this._scrollTween = null;
          }
        };
        _proto2.onDestroy = function onDestroy() {
          input.off(Input.EventType.TOUCH_END, this._onGlobalTouchEnd, this);
          input.off(Input.EventType.TOUCH_CANCEL, this._onGlobalTouchEnd, this);
          this.node.off(Node.EventType.TOUCH_START, this._onDown, this);
          this.node.off(Node.EventType.TOUCH_MOVE, this._onMove, this);
          this.node.off(Node.EventType.TOUCH_END, this._onUp, this);
          this.node.off(Node.EventType.TOUCH_CANCEL, this._onUp, this);
          if (this._nodePool) {
            this._nodePool.clear();
            this._nodePool = null;
          }

          // 销毁模板节点
          if (this._templateNode) {
            this._templateNode.destroy();
            this._templateNode = null;
          }
          if (this.itemNode) {
            this.itemNode.destroy();
            this.itemNode = null;
          }
          if (this.itemNodes) {
            for (var i = this.itemNodes.length - 1; i >= 0; i--) {
              this.itemNodes[i].destroy();
              this.itemNodes[i] = null;
            }
          }
        };
        _proto2._bindTouch = function _bindTouch() {
          this.node.on(Node.EventType.TOUCH_START, this._onDown, this);
          this.node.on(Node.EventType.TOUCH_MOVE, this._onMove, this);
          this.node.on(Node.EventType.TOUCH_END, this._onUp, this);
          this.node.on(Node.EventType.TOUCH_CANCEL, this._onUp, this);
        };
        _proto2._bindGlobalTouch = function _bindGlobalTouch() {
          input.on(Input.EventType.TOUCH_END, this._onGlobalTouchEnd, this);
          input.on(Input.EventType.TOUCH_CANCEL, this._onGlobalTouchEnd, this);
        };
        _proto2._onGlobalTouchEnd = function _onGlobalTouchEnd(event) {
          if (this._isTouching) {
            console.log('[VScrollView] Global touch end detected');
            this._onUp(event);
          }
        };
        _proto2._initFixedSizeMode = /*#__PURE__*/function () {
          var _initFixedSizeMode2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
            var _this3 = this;
            var item_pre, uit, stride, visibleLines, i, n, itf;
            return _regeneratorRuntime().wrap(function _callee2$(_context2) {
              while (1) switch (_context2.prev = _context2.next) {
                case 0:
                  if (!this.provideNodeFn) {
                    this.provideNodeFn = function (index) {
                      // Node 模式
                      if (_this3.itemCreationMode === ItemCreationMode.NODE) {
                        if (_this3.itemNode) return instantiate(_this3.itemNode);
                        if (_this3._templateNode) return instantiate(_this3._templateNode);
                      }
                      // Prefab 模式
                      if (_this3.itemCreationMode === ItemCreationMode.PREFAB) {
                        if (_this3.itemPrefab) return instantiate(_this3.itemPrefab);
                      }
                      // 兼容旧版本：如果没有设置模式，尝试 itemPrefab 或模板节点
                      if (_this3.itemPrefab) return instantiate(_this3.itemPrefab);
                      if (_this3._templateNode) return instantiate(_this3._templateNode);
                      // 都没有则警告并创建默认节点
                      console.warn('[VirtualScrollView] 没有提供 itemNode/itemPrefab 或模板节点');
                      var n = new Node('item-auto-create');
                      var size = _this3._isVertical() ? _this3._viewportTf.width : _this3._viewportTf.height;
                      n.addComponent(UITransform).setContentSize(_this3._isVertical() ? size : _this3.itemMainSize, _this3._isVertical() ? _this3.itemMainSize : size);
                      return n;
                    };
                  }
                  item_pre = this.provideNodeFn(0);
                  if (!(item_pre instanceof Promise)) {
                    _context2.next = 6;
                    break;
                  }
                  _context2.next = 5;
                  return item_pre;
                case 5:
                  item_pre = _context2.sent;
                case 6:
                  uit = item_pre.getComponent(UITransform);
                  if (this._isVertical()) {
                    this.itemMainSize = uit.height;
                    this.itemCrossSize = uit.width;
                  } else {
                    this.itemMainSize = uit.width;
                    this.itemCrossSize = uit.height;
                  }
                  this._recomputeContentSize();
                  stride = this.itemMainSize + this.spacing;
                  visibleLines = Math.ceil(this._viewportSize / stride);
                  this._slots = Math.max(1, (visibleLines + this.buffer + 2) * this.gridCount);
                  for (i = 0; i < this._slots; i++) {
                    n = instantiate(item_pre);
                    n.parent = this.content;
                    itf = n.getComponent(UITransform);
                    if (itf) {
                      if (this._isVertical()) {
                        itf.width = this.itemCrossSize;
                        itf.height = this.itemMainSize;
                      } else {
                        itf.width = this.itemMainSize;
                        itf.height = this.itemCrossSize;
                      }
                    }
                    this._slotNodes.push(n);
                  }
                  this._slotFirstIndex = 0;
                  this._layoutSlots(this._slotFirstIndex, true);
                case 15:
                case "end":
                  return _context2.stop();
              }
            }, _callee2, this);
          }));
          function _initFixedSizeMode() {
            return _initFixedSizeMode2.apply(this, arguments);
          }
          return _initFixedSizeMode;
        }();
        _proto2._initDynamicSizeMode = /*#__PURE__*/function () {
          var _initDynamicSizeMode2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
            var i, useNodeMode, hasNodes, hasPrefabs, templates, modeName, _i, template, sampleNode, uit, size, _i2, typeIndex, _size;
            return _regeneratorRuntime().wrap(function _callee3$(_context3) {
              while (1) switch (_context3.prev = _context3.next) {
                case 0:
                  if (!this.getItemHeightFn) {
                    _context3.next = 24;
                    break;
                  }
                  console.log('[VirtualScrollView] 使用外部提供的 getItemHeightFn');
                  this._itemSizes = [];
                  for (i = 0; i < this.totalCount; i++) {
                    this._itemSizes.push(this.getItemHeightFn(i));
                  }
                  this._buildPrefixSum();
                  // Node 模式
                  if (!(this.itemCreationMode === ItemCreationMode.NODE && this.itemNodes.length > 0)) {
                    _context3.next = 10;
                    break;
                  }
                  console.log('[VirtualScrollView] 初始化节点池（Node 模式）');
                  this._nodePool = new InternalNodePool([], this.itemNodes);
                  _context3.next = 22;
                  break;
                case 10:
                  if (!(this.itemCreationMode === ItemCreationMode.PREFAB && this.itemPrefabs.length > 0)) {
                    _context3.next = 15;
                    break;
                  }
                  console.log('[VirtualScrollView] 初始化节点池（Prefab 模式）');
                  this._nodePool = new InternalNodePool(this.itemPrefabs);
                  _context3.next = 22;
                  break;
                case 15:
                  if (!(this.itemPrefabs.length > 0)) {
                    _context3.next = 20;
                    break;
                  }
                  console.log('[VirtualScrollView] 初始化节点池（兼容模式）');
                  this._nodePool = new InternalNodePool(this.itemPrefabs);
                  _context3.next = 22;
                  break;
                case 20:
                  console.error('[VirtualScrollView] 需要至少一个 itemNode 或 itemPrefab');
                  return _context3.abrupt("return");
                case 22:
                  this._initDynamicSlots();
                  return _context3.abrupt("return");
                case 24:
                  // Node 模式
                  useNodeMode = this.itemCreationMode === ItemCreationMode.NODE;
                  hasNodes = this.itemNodes.length > 0;
                  hasPrefabs = this.itemPrefabs.length > 0;
                  if (!(useNodeMode && !hasNodes && !hasPrefabs || !useNodeMode && !hasPrefabs || !this.getItemTypeIndexFn)) {
                    _context3.next = 30;
                    break;
                  }
                  console.error('[VirtualScrollView] 不等大小模式必须提供以下之一：\n1. getItemHeightFn 回调函数\n2. itemNodes/itemPrefabs 数组 + getItemTypeIndexFn 回调函数');
                  return _context3.abrupt("return");
                case 30:
                  // 根据模式选择模板源
                  templates = useNodeMode && hasNodes ? this.itemNodes : this.itemPrefabs;
                  modeName = useNodeMode && hasNodes ? 'Node' : 'Prefab';
                  console.log("[VirtualScrollView] \u4F7F\u7528\u91C7\u6837\u6A21\u5F0F\uFF08\u4ECE " + modeName + " \u91C7\u6837\u5C3A\u5BF8\uFF09");

                  // 初始化节点池
                  if (useNodeMode && hasNodes) {
                    this._nodePool = new InternalNodePool([], this.itemNodes);
                  } else {
                    this._nodePool = new InternalNodePool(this.itemPrefabs);
                  }
                  this._prefabSizeCache.clear();
                  for (_i = 0; _i < templates.length; _i++) {
                    template = templates[_i];
                    sampleNode = instantiate(template);
                    uit = sampleNode.getComponent(UITransform);
                    size = this._isVertical() ? (uit == null ? void 0 : uit.height) || 100 : (uit == null ? void 0 : uit.width) || 100;
                    this._prefabSizeCache.set(_i, size);
                    sampleNode.destroy();
                    console.log("[VirtualScrollView] " + modeName + "[" + _i + "] \u91C7\u6837\u5C3A\u5BF8: " + size);
                  }
                  this._itemSizes = [];
                  for (_i2 = 0; _i2 < this.totalCount; _i2++) {
                    typeIndex = this.getItemTypeIndexFn(_i2);
                    _size = this._prefabSizeCache.get(typeIndex);
                    if (_size !== undefined) {
                      this._itemSizes.push(_size);
                    } else {
                      console.warn("[VirtualScrollView] \u7D22\u5F15 " + _i2 + " \u7684\u7C7B\u578B\u7D22\u5F15 " + typeIndex + " \u65E0\u6548\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5C3A\u5BF8");
                      this._itemSizes.push(this._prefabSizeCache.get(0) || 100);
                    }
                  }
                  this._buildPrefixSum();
                  this._initDynamicSlots();
                case 40:
                case "end":
                  return _context3.stop();
              }
            }, _callee3, this);
          }));
          function _initDynamicSizeMode() {
            return _initDynamicSizeMode2.apply(this, arguments);
          }
          return _initDynamicSizeMode;
        }();
        _proto2._initDynamicSlots = function _initDynamicSlots() {
          var avgSize = this._contentSize / this.totalCount || 100;
          var visibleCount = Math.ceil(this._viewportSize / avgSize);
          var neededSlots = visibleCount + this.buffer * 2 + 4;
          var minSlots = Math.ceil(this._viewportSize / 80) + this.buffer * 2;
          neededSlots = Math.max(neededSlots, minSlots);
          var maxSlots = Math.ceil(this._viewportSize / 50) + this.buffer * 4;
          neededSlots = Math.min(neededSlots, maxSlots);
          this._slots = Math.min(neededSlots, Math.max(this.totalCount, minSlots));
          this._slotNodes = new Array(this._slots).fill(null);
          this._slotPrefabIndices = new Array(this._slots).fill(-1);
          this._slotFirstIndex = 0;
          this._layoutSlots(this._slotFirstIndex, true);
          console.log("[VScrollView] \u521D\u59CB\u5316\u69FD\u4F4D: " + this._slots + " (\u603B\u6570\u636E: " + this.totalCount + ", \u89C6\u53E3\u5C3A\u5BF8: " + this._viewportSize + ")");
        };
        _proto2._buildPrefixSum = function _buildPrefixSum() {
          var n = this._itemSizes.length;
          this._prefixPositions = new Array(n);
          // 从 headerSpacing 开始
          var acc = this.headerSpacing;
          for (var i = 0; i < n; i++) {
            this._prefixPositions[i] = acc;
            acc += this._itemSizes[i] + this.spacing;
          }
          // 内容总大小 = 最后一个位置 + 最后一项大小 - spacing + footerSpacing
          this._contentSize = acc - this.spacing + this.footerSpacing;
          if (this._contentSize < 0) this._contentSize = 0;
          if (this._isVertical()) this._contentTf.height = Math.max(this._contentSize, this._viewportSize);else this._contentTf.width = Math.max(this._contentSize, this._viewportSize);
          if (this._isVertical()) {
            this._boundsMin = 0;
            this._boundsMax = Math.max(0, this._contentSize - this._viewportSize);
          } else {
            this._boundsMin = -Math.max(0, this._contentSize - this._viewportSize);
            this._boundsMax = 0;
          }
        };
        _proto2._posToFirstIndex = function _posToFirstIndex(pos) {
          // _prefixPositions 已经包含了 headerSpacing，直接查找即可
          if (pos <= this.headerSpacing) return 0; // 修改：如果在 header 区域内，返回 0

          var l = 0,
            r = this._prefixPositions.length - 1,
            ans = this._prefixPositions.length;
          while (l <= r) {
            var m = l + r >> 1;
            if (this._prefixPositions[m] > pos) {
              ans = m;
              r = m - 1;
            } else {
              l = m + 1;
            }
          }
          return Math.max(0, ans - 1);
        };
        _proto2._calcVisibleRange = function _calcVisibleRange(scrollPos) {
          var n = this._prefixPositions.length;
          if (n === 0) return {
            start: 0,
            end: 0
          };
          var start = this._posToFirstIndex(scrollPos);
          var endPos = scrollPos + this._viewportSize;
          var end = start;

          // 找到第一个起始位置超出可视区域的 item
          while (end < n) {
            if (this._prefixPositions[end] >= endPos) break; // 恢复原来的逻辑
            end++;
          }
          return {
            start: Math.max(0, start - this.buffer),
            end: Math.min(n, end + this.buffer)
          };
        };
        _proto2.update = function update(dt) {
          if (!this.content || this._isTouching || this._scrollTween) return;
          var pos = this._getContentMainPos();
          var a = 0;
          var minBound = Math.min(this._boundsMin, this._boundsMax);
          var maxBound = Math.max(this._boundsMin, this._boundsMax);

          // 处理刷新/加载状态
          if (this._isRefreshing && this._refreshState === RefreshState.REFRESHING) {
            // 刷新中，保持在刷新位置
            var refreshPos = this._isVertical() ? -this.pullRefreshThreshold : this.pullRefreshThreshold;
            a = -this.springK * (pos - refreshPos) - this.springC * this._velocity;
          } else if (this._isLoadingMore && this._loadMoreState === LoadMoreState.LOADING) {
            // 加载中，保持在加载位置
            var loadPos = this._isVertical() ? this._boundsMax + this.loadMoreThreshold : this._boundsMin - this.loadMoreThreshold;
            a = -this.springK * (pos - loadPos) - this.springC * this._velocity;
          } else if (pos < minBound) {
            // 如果禁用越界滚动，直接限制位置并停止速度
            if (this.disableBounce) {
              this._setContentMainPos(minBound);
              this._velocity = 0;
              return;
            }
            a = -this.springK * (pos - minBound) - this.springC * this._velocity;
          } else if (pos > maxBound) {
            // 如果禁用越界滚动，直接限制位置并停止速度
            if (this.disableBounce) {
              this._setContentMainPos(maxBound);
              this._velocity = 0;
              return;
            }
            a = -this.springK * (pos - maxBound) - this.springC * this._velocity;
          } else {
            if (this.useIOSDecelerationCurve) {
              var speed = Math.abs(this._velocity);
              if (speed > 2000) this._velocity *= Math.exp(-this.inertiaDampK * 0.7 * dt);else if (speed > 500) this._velocity *= Math.exp(-this.inertiaDampK * dt);else this._velocity *= Math.exp(-this.inertiaDampK * 1.3 * dt);
            } else {
              this._velocity *= Math.exp(-this.inertiaDampK * dt);
            }
          }
          this._velocity += a * dt;

          // 分页吸附模式：使用单独的速度阈值
          if (this.enablePageSnap && Math.abs(this._velocity) < this.pageSnapTriggerVelocity && a === 0) {
            this._velocity = 0;
            this._performPageSnap();
            return;
          }
          if (Math.abs(this._velocity) < this.velocitySnap && a === 0) this._velocity = 0;
          if (this._velocity !== 0) {
            pos += this._velocity * dt;

            // 如果禁用越界滚动，限制位置在边界内
            if (this.disableBounce) {
              pos = math$1.clamp(pos, minBound, maxBound);
            }
            if (this.pixelAlign) pos = Math.round(pos);
            this._setContentMainPos(pos);
            if (this.useVirtualList) this._updateVisible(false);
          }
        };
        _proto2.updateItemHeight = function updateItemHeight(index, newSize) {
          if (!this.useDynamicSize) {
            console.warn('[VScrollView] 只有不等大小模式支持 updateItemHeight');
            return;
          }
          if (index < 0 || index >= this.totalCount) {
            console.warn("[VScrollView] \u7D22\u5F15 " + index + " \u8D85\u51FA\u8303\u56F4");
            return;
          }
          var size = newSize;
          if (size === undefined) {
            if (this.getItemHeightFn) {
              size = this.getItemHeightFn(index);
            } else {
              console.error('[VScrollView] 没有提供 newSize 参数，且未设置 getItemHeightFn');
              return;
            }
          }
          if (this._itemSizes[index] === size) return;
          this._itemSizes[index] = size;
          this._rebuildPrefixSumFrom(index);
          this._updateVisible(true);
        };
        _proto2._rebuildPrefixSumFrom = function _rebuildPrefixSumFrom(startIndex) {
          if (startIndex === 0) {
            this._buildPrefixSum();
            return;
          }
          var acc = this._prefixPositions[startIndex - 1] + this._itemSizes[startIndex - 1] + this.spacing;
          for (var i = startIndex; i < this._itemSizes.length; i++) {
            this._prefixPositions[i] = acc;
            acc += this._itemSizes[i] + this.spacing;
          }
          this._contentSize = acc - this.spacing + this.footerSpacing;
          if (this._contentSize < 0) this._contentSize = 0;
          if (this._isVertical()) this._contentTf.height = Math.max(this._contentSize, this._viewportSize);else this._contentTf.width = Math.max(this._contentSize, this._viewportSize);
          if (this._isVertical()) {
            this._boundsMin = 0;
            this._boundsMax = Math.max(0, this._contentSize - this._viewportSize);
          } else {
            this._boundsMin = -Math.max(0, this._contentSize - this._viewportSize);
            this._boundsMax = 0;
          }
        };
        _proto2.updateItemHeights = function updateItemHeights(updates) {
          if (!this.useDynamicSize) {
            console.warn('[VScrollView] 只有不等大小模式支持 updateItemHeights');
            return;
          }
          if (updates.length === 0) return;
          var minIndex = this.totalCount;
          var hasChange = false;
          for (var _iterator = _createForOfIteratorHelperLoose(updates), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              _index = _step$value.index,
              height = _step$value.height;
            if (_index < 0 || _index >= this.totalCount) continue;
            if (this._itemSizes[_index] !== height) {
              this._itemSizes[_index] = height;
              minIndex = Math.min(minIndex, _index);
              hasChange = true;
            }
          }
          if (!hasChange) return;
          this._rebuildPrefixSumFrom(minIndex);
          this._updateVisible(true);
        };
        _proto2.refreshList = function refreshList(data) {
          if (!this.useVirtualList) {
            console.warn('[VirtualScrollView] 简单滚动模式不支持 refreshList');
            return;
          }
          if (typeof data === 'number') this.setTotalCount(data);else this.setTotalCount(data.length);
        };
        _proto2.setTotalCount = function setTotalCount(count) {
          this._getContentNode();
          if (!this.useVirtualList) {
            console.warn('[VScrollView] 非虚拟列表模式，不支持 setTotalCount');
            return;
          }
          this._upWidgetAlignment();
          var oldCount = this.totalCount;
          this.totalCount = Math.max(0, count | 0);
          if (this.totalCount > oldCount) {
            for (var i = oldCount; i < this.totalCount; i++) {
              this._needAnimateIndices.add(i);
            }
          }
          if (this.useDynamicSize) {
            var oldLength = this._itemSizes.length;
            if (this.totalCount > oldLength) {
              for (var _i3 = oldLength; _i3 < this.totalCount; _i3++) {
                var size = 100;
                if (this.getItemHeightFn) {
                  size = this.getItemHeightFn(_i3);
                } else if (this.getItemTypeIndexFn && this._prefabSizeCache.size > 0) {
                  var typeIndex = this.getItemTypeIndexFn(_i3);
                  size = this._prefabSizeCache.get(typeIndex) || 100;
                }
                this._itemSizes.push(size);
              }
            } else if (this.totalCount < oldLength) {
              this._itemSizes.length = this.totalCount;
            }
            this._buildPrefixSum();
            if (this.totalCount > oldCount) this._expandSlotsIfNeeded();
          } else {
            this._recomputeContentSize();
          }
          this._slotFirstIndex = math$1.clamp(this._slotFirstIndex, 0, Math.max(0, this.totalCount - 1));
          if (!this.useDynamicSize) {
            this._layoutSlots(this._slotFirstIndex, true);
          }
          this._updateVisible(true);
        };
        _proto2._upWidgetAlignment = function _upWidgetAlignment() {
          var _this$content, _this$node;
          (_this$content = this.content) == null || _this$content.getComponent == null || (_this$content = _this$content.getComponent(Widget)) == null || _this$content.updateAlignment == null || _this$content.updateAlignment();
          (_this$node = this.node) == null || _this$node.getComponent == null || (_this$node = _this$node.getComponent(Widget)) == null || _this$node.updateAlignment == null || _this$node.updateAlignment();
        };
        _proto2._expandSlotsIfNeeded = function _expandSlotsIfNeeded() {
          var neededSlots = 0;
          var pos = 0;
          var endPos = this._viewportSize;
          for (var i = 0; i < this.totalCount; i++) {
            if (pos >= endPos) break;
            neededSlots++;
            pos += this._itemSizes[i] + this.spacing;
          }
          neededSlots += this.buffer * 2 + 4;
          var minSlots = Math.ceil(this._viewportSize / 80) + this.buffer * 2;
          neededSlots = Math.max(neededSlots, minSlots);
          var maxSlots = Math.ceil(this._viewportSize / 50) + this.buffer * 4;
          neededSlots = Math.min(neededSlots, maxSlots);
          if (neededSlots > this._slots) {
            var oldSlots = this._slots;
            this._slots = neededSlots;
            for (var _i4 = oldSlots; _i4 < this._slots; _i4++) {
              this._slotNodes.push(null);
              this._slotPrefabIndices.push(-1);
            }
            console.log("[VScrollView] \u69FD\u4F4D\u6269\u5C55: " + oldSlots + " -> " + this._slots + " (\u603B\u6570\u636E: " + this.totalCount + ")");
          }
        };
        _proto2._scrollToPosition = function _scrollToPosition(targetPos, animate, duration) {
          var _this4 = this;
          if (animate === void 0) {
            animate = false;
          }
          targetPos = math$1.clamp(targetPos, this._boundsMin, this._boundsMax);
          if (this._scrollTween) {
            this._scrollTween.stop();
            this._scrollTween = null;
          }
          this._velocity = 0;
          this._isTouching = false;
          this._velSamples.length = 0;
          if (!animate) {
            this._setContentMainPos(this.pixelAlign ? Math.round(targetPos) : targetPos);
            this._updateVisible(true);
          } else {
            var currentPos = this._getContentMainPos();
            var distance = Math.abs(targetPos - currentPos);
            // 如果提供了 duration 则使用，否则根据距离自动计算
            var finalDuration = duration !== undefined ? duration : Math.max(0.2, distance / 3000);
            var targetVec = this._isVertical() ? new Vec3(0, targetPos, 0) : new Vec3(targetPos, 0, 0);
            this._scrollTween = tween(this.content).to(finalDuration, {
              position: targetVec
            }, {
              easing: 'smooth',
              onUpdate: function onUpdate() {
                _this4._updateVisible(false);
              }
            }).call(function () {
              _this4._updateVisible(true);
              _this4._scrollTween = null;
              _this4._velocity = 0;
            }).start();
          }
        };
        _proto2.scrollToTop = function scrollToTop(animate, duration) {
          if (animate === void 0) {
            animate = false;
          }
          var target = this._isVertical() ? this._boundsMin : this._boundsMax;
          this._scrollToPosition(target, animate, duration);
        };
        _proto2.scrollToBottom = function scrollToBottom(animate, duration) {
          if (animate === void 0) {
            animate = false;
          }
          var target = this._isVertical() ? this._boundsMax : this._boundsMin;
          this._scrollToPosition(target, animate, duration);
        };
        _proto2.scrollToIndex = function scrollToIndex(index, animate, duration) {
          if (animate === void 0) {
            animate = false;
          }
          index = math$1.clamp(index | 0, 0, Math.max(0, this.totalCount - 1));
          var targetPos = 0;
          if (this.useDynamicSize) {
            // 不等大小模式：_prefixPositions 已经包含了 headerSpacing
            targetPos = this._prefixPositions[index] || 0;
          } else {
            // 等大小模式：需要手动加上 headerSpacing
            var line = Math.floor(index / this.gridCount);
            targetPos = this.headerSpacing + line * (this.itemMainSize + this.spacing);
          }

          // 横向模式：滚动方向相反，取负值
          if (!this._isVertical()) {
            targetPos = -targetPos;
          }
          this._scrollToPosition(targetPos, animate, duration);
        };
        _proto2.onOffSortLayer = function onOffSortLayer(onoff) {
          this._initSortLayerFlag = onoff;
          this._onOffSortLayerOperation();
        };
        _proto2._onOffSortLayerOperation = function _onOffSortLayerOperation() {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._slotNodes), _step2; !(_step2 = _iterator2()).done;) {
            var element = _step2.value;
            var sitem = element == null ? void 0 : element.getComponent(VScrollViewItem);
            if (sitem) {
              if (this._initSortLayerFlag) sitem.onSortLayer();else sitem.offSortLayer();
            }
          }
        };
        _proto2._flashToPosition = function _flashToPosition(targetPos) {
          targetPos = math$1.clamp(targetPos, this._boundsMin, this._boundsMax);
          if (this._scrollTween) {
            this._scrollTween.stop();
            this._scrollTween = null;
          }
          this._velocity = 0;
          this._isTouching = false;
          this._velSamples.length = 0;
          this._setContentMainPos(this.pixelAlign ? Math.round(targetPos) : targetPos);
          this._updateVisible(true);
        };
        _proto2.flashToTop = function flashToTop() {
          var target = this._isVertical() ? this._boundsMin : this._boundsMax;
          this._flashToPosition(target);
        };
        _proto2.flashToBottom = function flashToBottom() {
          var target = this._isVertical() ? this._boundsMax : this._boundsMin;
          this._flashToPosition(target);
        };
        _proto2.flashToIndex = function flashToIndex(index) {
          if (!this.useVirtualList) {
            console.warn('[VirtualScrollView] 简单滚动模式不支持 flashToIndex');
            return;
          }
          index = math$1.clamp(index | 0, 0, Math.max(0, this.totalCount - 1));
          var targetPos = 0;
          if (this.useDynamicSize) {
            // 不等大小模式：_prefixPositions 已经包含了 headerSpacing
            targetPos = this._prefixPositions[index] || 0;
          } else {
            // 等大小模式：需要手动加上 headerSpacing
            var line = Math.floor(index / this.gridCount);
            targetPos = this.headerSpacing + line * (this.itemMainSize + this.spacing);
          }
          if (!this._isVertical()) {
            targetPos = -targetPos;
          }
          this._flashToPosition(targetPos);
        };
        _proto2.refreshIndex = function refreshIndex(index) {
          if (!this.useVirtualList) {
            console.warn('[VirtualScrollView] 简单滚动模式不支持 refreshIndex');
            return;
          }
          var first = this._slotFirstIndex;
          var last = first + this._slots - 1;
          if (index < first || index > last) return;
          var slot = index - first;
          var node = this._slotNodes[slot];
          if (node && this.renderItemFn) this.renderItemFn(node, index);
        };
        _proto2._stopTouchEvent = function _stopTouchEvent(e) {
          if (!e) return;

          // 如果已经确定要阻止父级，直接阻止
          if (this._shouldBlockParent) {
            e.propagationStopped = true;
          }
        };
        _proto2._onDown = function _onDown(e) {
          // 记录触摸起始位置
          var uiPos = e.getUILocation(this._touchStartPos);
          this._touchStartPos.set(uiPos);
          this._hasDeterminedScrollDirection = false;
          this._shouldBlockParent = false;

          // 分页模式：记录触摸开始时的内容位置
          if (this.enablePageSnap) {
            this._pageStartPos = this._getContentMainPos();
          }
          this._stopTouchEvent(e);
          this._isTouching = true;
          this._velocity = 0;
          this._velSamples.length = 0;
          if (this._scrollTween) {
            this._scrollTween.stop();
            this._scrollTween = null;
          }
        };
        _proto2._onMove = function _onMove(e) {
          if (!this._isTouching) return;
          var uiDelta = e.getUIDelta(this._tmpMoveVec2);
          var currentPos = e.getUILocation();

          // 第一次移动时判断滑动方向
          if (!this._hasDeterminedScrollDirection) {
            var deltaX = currentPos.x - this._touchStartPos.x;
            var deltaY = currentPos.y - this._touchStartPos.y;
            var totalDelta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

            // 超过距离阈值才判断方向
            if (totalDelta > this._scrollDirectionThreshold) {
              this._hasDeterminedScrollDirection = true;

              // 计算滑动角度（相对于水平方向）
              var angle = Math.abs(Math.atan2(deltaY, deltaX) * 180 / Math.PI);

              // 判断是否为纵向滑动：角度在 [90° - 阈值, 90° + 阈值] 范围内
              var isVerticalScroll = angle > 90 - this._scrollAngleThreshold && angle < 90 + this._scrollAngleThreshold;

              // 判断是否为横向滑动：角度在 [0°, 阈值] 或 [180° - 阈值, 180°] 范围内
              var isHorizontalScroll = angle < this._scrollAngleThreshold || angle > 180 - this._scrollAngleThreshold;
              var isListVertical = this._isVertical();

              // 方向一致时才考虑拦截
              if (isListVertical && isVerticalScroll || !isListVertical && isHorizontalScroll) {
                // 检查是否在边界
                var _pos = this._getContentMainPos();
                var _minBound = Math.min(this._boundsMin, this._boundsMax);
                var _maxBound = Math.max(this._boundsMin, this._boundsMax);
                var _delta = this._isVertical() ? uiDelta.y : uiDelta.x;

                // 判断滑动方向
                var scrollingToStart = this._isVertical() ? _delta > 0 : _delta < 0;
                var scrollingToEnd = this._isVertical() ? _delta < 0 : _delta > 0;

                // 只有在非边界位置，或者在边界但向内滑动时才拦截
                var atStartBound = this._isVertical() ? _pos <= _minBound : _pos >= _maxBound;
                var atEndBound = this._isVertical() ? _pos >= _maxBound : _pos <= _minBound;
                if (!atStartBound && !atEndBound || atStartBound && scrollingToEnd || atEndBound && scrollingToStart) {
                  this._shouldBlockParent = true;
                }
              }
            }
          }
          this._stopTouchEvent(e);
          // const uiDelta = e.getUIDelta(this._tmpMoveVec2);
          var delta = this._isVertical() ? uiDelta.y : uiDelta.x;
          var pos = this._getContentMainPos();
          var minBound = Math.min(this._boundsMin, this._boundsMax);
          var maxBound = Math.max(this._boundsMin, this._boundsMax);

          // 计算是否需要下拉刷新或上拉加载
          var finalDelta = delta;

          // console.log(`delta: ${delta}, pos: ${pos}, minBound: ${minBound}, maxBound: ${maxBound}`);

          if (this.enablePullRefresh && !this._isRefreshing) {
            // 纵向：顶部下拉（pos < minBound 且向下拉）
            // 横向：左侧右拉（pos > maxBound 且向右拉）
            var atTopBound = this._isVertical() ? pos <= minBound : pos >= maxBound;
            var pullingDown = this._isVertical() ? delta < 0 : delta > 0;
            if (atTopBound && pullingDown) {
              var overOffset = this._isVertical() ? minBound - pos : pos - maxBound;
              var resistance = 1 - Math.min(overOffset / this.pullRefreshMaxOffset, 1) * (1 - this.pullDampingRate);
              finalDelta = delta * resistance;
              this._pullOffset = Math.min(overOffset + Math.abs(finalDelta), this.pullRefreshMaxOffset);
              // console.log(`[VScrollView] 下拉偏移: ${this._pullOffset}`);

              // 更新刷新状态
              if (this._pullOffset >= this.pullRefreshThreshold) {
                this._updateRefreshState(RefreshState.READY, this._pullOffset);
              } else {
                this._updateRefreshState(RefreshState.PULLING, this._pullOffset);
              }
            }
          }
          if (this.enableLoadMore && !this._isLoadingMore && this._hasMore) {
            // 纵向：底部上拉（pos > maxBound 且向上拉）
            // 横向：右侧左拉（pos < minBound 且向左拉）
            var atBottomBound = this._isVertical() ? pos >= maxBound : pos <= minBound;
            var pullingUp = this._isVertical() ? delta > 0 : delta < 0;
            if (atBottomBound && pullingUp) {
              var _overOffset = this._isVertical() ? pos - maxBound : minBound - pos;
              var _resistance = 1 - Math.min(_overOffset / this.loadMoreMaxOffset, 1) * (1 - this.pullDampingRate);
              finalDelta = delta * _resistance;
              this._loadOffset = Math.min(_overOffset + Math.abs(finalDelta), this.loadMoreMaxOffset);

              // console.log(`[VScrollView] 上拉偏移: ${this._loadOffset}`);
              // 更新加载状态
              if (this._loadOffset >= this.loadMoreThreshold) {
                this._updateLoadMoreState(LoadMoreState.READY, this._loadOffset);
              } else {
                this._updateLoadMoreState(LoadMoreState.PULLING, this._loadOffset);
              }
            }
          }

          // 如果禁用越界滚动，限制位置在边界内
          if (this.disableBounce) {
            var newPos = pos + finalDelta;
            // 不允许越界，直接限制在边界范围内
            if (newPos < minBound) {
              finalDelta = minBound - pos;
            } else if (newPos > maxBound) {
              finalDelta = maxBound - pos;
            }
          }

          // 应用位置变化
          pos += finalDelta;
          if (this.pixelAlign) pos = Math.round(pos);
          this._setContentMainPos(pos);

          // 记录速度采样
          var t = performance.now() / 1000;
          this._velSamples.push({
            t: t,
            delta: finalDelta
          });
          var t0 = t - this.velocityWindow;
          while (this._velSamples.length && this._velSamples[0].t < t0) this._velSamples.shift();
          if (this.useVirtualList) this._updateVisible(false);
        };
        _proto2._onUp = function _onUp(e) {
          // 重置方向判断标志
          this._hasDeterminedScrollDirection = false;
          this._shouldBlockParent = false;
          this._stopTouchEvent(e);
          if (!this._isTouching) return;
          this._isTouching = false;

          // 检查是否触发刷新
          if (this._refreshState === RefreshState.READY && !this._isRefreshing) {
            this._triggerRefresh();
            this._velSamples.length = 0;
            return;
          }

          // 检查是否触发加载
          if (this._loadMoreState === LoadMoreState.READY && !this._isLoadingMore) {
            this._triggerLoadMore();
            this._velSamples.length = 0;
            return;
          }

          // 重置状态
          if (this._refreshState !== RefreshState.REFRESHING) {
            this._pullOffset = 0;
            this._updateRefreshState(RefreshState.IDLE, 0);
          }
          if (this._loadMoreState !== LoadMoreState.LOADING) {
            this._loadOffset = 0;
            this._updateLoadMoreState(LoadMoreState.IDLE, 0);
          }

          // 计算速度
          if (this._velSamples.length >= 2) {
            var sum = 0;
            var dtSum = 0;
            var sampleCount = Math.min(this._velSamples.length, 5);
            var startIndex = this._velSamples.length - sampleCount;
            for (var i = startIndex + 1; i < this._velSamples.length; i++) {
              sum += this._velSamples[i].delta;
              dtSum += this._velSamples[i].t - this._velSamples[i - 1].t;
            }
            if (dtSum > 0.001) {
              this._velocity = sum / dtSum;
              this._velocity = math$1.clamp(this._velocity, -this.maxVelocity, this.maxVelocity);
            } else {
              this._velocity = this._velSamples.length > 0 ? math$1.clamp(this._velSamples[this._velSamples.length - 1].delta * 60, -this.maxVelocity, this.maxVelocity) : 0;
            }
          } else if (this._velSamples.length === 1) {
            this._velocity = math$1.clamp(this._velSamples[0].delta * 60, -this.maxVelocity, this.maxVelocity);
          } else {
            this._velocity = 0;
          }
          this._velSamples.length = 0;

          // 分页吸附模式：根据滑动距离判断翻页
          if (this.enablePageSnap) {
            this._performPageSnapByDistance();
          }
        }

        // 更新刷新状态
        ;

        _proto2._updateRefreshState = function _updateRefreshState(state, offset) {
          if (this._refreshState === state) return;
          this._refreshState = state;
          if (this.onRefreshStateChangeFn) {
            this.onRefreshStateChangeFn(state, offset);
          }
        }

        // 更新加载状态
        ;

        _proto2._updateLoadMoreState = function _updateLoadMoreState(state, offset) {
          if (this._loadMoreState === state) return;
          this._loadMoreState = state;
          if (this.onLoadMoreStateChangeFn) {
            this.onLoadMoreStateChangeFn(state, offset);
          }
        }

        // 触发刷新
        ;

        _proto2._triggerRefresh = function _triggerRefresh() {
          this._isRefreshing = true;
          this._velocity = 0;
          this._updateRefreshState(RefreshState.REFRESHING, this.pullRefreshThreshold);
        }

        // 触发加载更多
        ;

        _proto2._triggerLoadMore = function _triggerLoadMore() {
          this._isLoadingMore = true;
          this._velocity = 0;
          this._updateLoadMoreState(LoadMoreState.LOADING, this.loadMoreThreshold);
        }

        /**
         * 完成刷新（外部调用）
         * @param success 是否刷新成功
         */;
        _proto2.finishRefresh = function finishRefresh(success) {
          var _this5 = this;
          if (success === void 0) {
            success = true;
          }
          if (!this._isRefreshing) return;
          this._isRefreshing = false;
          this._pullOffset = 0;
          this._updateRefreshState(success ? RefreshState.COMPLETE : RefreshState.IDLE, 0);

          // 延迟重置到 IDLE 状态
          this.scheduleOnce(function () {
            if (_this5._refreshState === RefreshState.COMPLETE) {
              _this5._updateRefreshState(RefreshState.IDLE, 0);
            }
          }, 0.3);
        }

        /**
         * 完成加载更多（外部调用）
         * @param hasMore 是否还有更多数据
         */;
        _proto2.finishLoadMore = function finishLoadMore(hasMore) {
          var _this6 = this;
          if (hasMore === void 0) {
            hasMore = true;
          }
          if (!this._isLoadingMore) return;
          this._isLoadingMore = false;
          this._loadOffset = 0;
          this._hasMore = hasMore;
          if (!hasMore) {
            this._updateLoadMoreState(LoadMoreState.NO_MORE, 0);
          } else {
            this._updateLoadMoreState(LoadMoreState.COMPLETE, 0);
            // 延迟重置到 IDLE 状态
            this.scheduleOnce(function () {
              if (_this6._loadMoreState === LoadMoreState.COMPLETE) {
                _this6._updateLoadMoreState(LoadMoreState.IDLE, 0);
              }
            }, 0.3);
          }
        }

        /**
         * 重置加载更多状态（当数据清空或重新加载时调用）
         */;
        _proto2.resetLoadMoreState = function resetLoadMoreState() {
          this._hasMore = true;
          this._isLoadingMore = false;
          this._loadOffset = 0;
          this._updateLoadMoreState(LoadMoreState.IDLE, 0);
        };
        _proto2._updateVisible = function _updateVisible(force) {
          if (!this.useVirtualList) return;
          var scrollPos = this._getContentMainPos();
          var searchPos;
          if (this._isVertical()) {
            searchPos = math$1.clamp(scrollPos, 0, this._contentSize);
          } else {
            searchPos = math$1.clamp(-scrollPos, 0, this._contentSize);
          }
          var newFirst = 0;
          if (this.useDynamicSize) {
            var range = this._calcVisibleRange(searchPos);
            newFirst = range.start;
          } else {
            var stride = this.itemMainSize + this.spacing;
            // 减去 headerSpacing 后再计算行号
            var adjustedPos = Math.max(0, searchPos - this.headerSpacing);
            var firstLine = Math.floor(adjustedPos / stride);
            var first = firstLine * this.gridCount;
            newFirst = math$1.clamp(first, 0, Math.max(0, this.totalCount - 1));
          }
          if (this.totalCount < this._slots) newFirst = 0;
          if (force) {
            this._slotFirstIndex = newFirst;
            this._layoutSlots(this._slotFirstIndex, true);
            return;
          }
          var diff = newFirst - this._slotFirstIndex;
          if (diff === 0) return;
          if (Math.abs(diff) >= this._slots) {
            this._slotFirstIndex = newFirst;
            this._layoutSlots(this._slotFirstIndex, true);
            return;
          }
          var absDiff = Math.abs(diff);
          if (diff > 0) {
            var _this$_slotNodes;
            var moved = this._slotNodes.splice(0, absDiff);
            (_this$_slotNodes = this._slotNodes).push.apply(_this$_slotNodes, moved);
            if (this.useDynamicSize && this._slotPrefabIndices.length > 0) {
              var _this$_slotPrefabIndi;
              var movedIndices = this._slotPrefabIndices.splice(0, absDiff);
              (_this$_slotPrefabIndi = this._slotPrefabIndices).push.apply(_this$_slotPrefabIndi, movedIndices);
            }
            this._slotFirstIndex = newFirst;
            for (var i = 0; i < absDiff; i++) {
              var slot = this._slots - absDiff + i;
              var idx = this._slotFirstIndex + slot;
              if (idx >= this.totalCount) {
                var _node2 = this._slotNodes[slot];
                if (_node2) _node2.active = false;
              } else {
                this._layoutSingleSlot(this._slotNodes[slot], idx, slot);
              }
            }
          } else {
            var _this$_slotNodes2;
            var _moved = this._slotNodes.splice(this._slotNodes.length + diff, absDiff);
            (_this$_slotNodes2 = this._slotNodes).unshift.apply(_this$_slotNodes2, _moved);
            if (this.useDynamicSize && this._slotPrefabIndices.length > 0) {
              var _this$_slotPrefabIndi2;
              var _movedIndices = this._slotPrefabIndices.splice(this._slotPrefabIndices.length + diff, absDiff);
              (_this$_slotPrefabIndi2 = this._slotPrefabIndices).unshift.apply(_this$_slotPrefabIndi2, _movedIndices);
            }
            this._slotFirstIndex = newFirst;
            for (var _i5 = 0; _i5 < absDiff; _i5++) {
              var _idx = this._slotFirstIndex + _i5;
              if (_idx >= this.totalCount) {
                var _node3 = this._slotNodes[_i5];
                if (_node3) _node3.active = false;
              } else {
                this._layoutSingleSlot(this._slotNodes[_i5], _idx, _i5);
              }
            }
          }
        };
        _proto2._layoutSingleSlot = /*#__PURE__*/function () {
          var _layoutSingleSlot2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(node, idx, slot) {
            var targetPrefabIndex, currentPrefabIndex, newNode, expectedSize, _uit, actualSize, uit, size, itemStart, _uit$anchorY, anchorY, anchorOffsetY, nodeY, y, _uit$anchorX, anchorX, anchorOffsetX, nodeX, x, stride, line, gridPos, _uit2, _itemStart, globalOffset, shouldAutoCenter, totalLines, totalContentSize, _uit2$anchorY, _anchorY, _anchorOffsetY, _nodeY, _y, actualCountInLine, startIdxOfLine, endIdxOfLine, totalWidth, _x4, _uit2$anchorX, _anchorX, _anchorOffsetX, _nodeX, _x5, _actualCountInLine, _startIdxOfLine, _endIdxOfLine, totalHeight, _y2;
            return _regeneratorRuntime().wrap(function _callee4$(_context4) {
              while (1) switch (_context4.prev = _context4.next) {
                case 0:
                  if (this.useVirtualList) {
                    _context4.next = 2;
                    break;
                  }
                  return _context4.abrupt("return");
                case 2:
                  if (!this.useDynamicSize) {
                    _context4.next = 44;
                    break;
                  }
                  targetPrefabIndex = this.getItemTypeIndexFn(idx);
                  currentPrefabIndex = this._slotPrefabIndices[slot];
                  newNode = null;
                  if (!(currentPrefabIndex === targetPrefabIndex && this._slotNodes[slot])) {
                    _context4.next = 10;
                    break;
                  }
                  newNode = this._slotNodes[slot];
                  _context4.next = 19;
                  break;
                case 10:
                  if (this._slotNodes[slot] && this._nodePool && currentPrefabIndex >= 0) {
                    this._nodePool.put(this._slotNodes[slot], currentPrefabIndex);
                  }
                  if (!this._nodePool) {
                    _context4.next = 19;
                    break;
                  }
                  newNode = this._nodePool.get(targetPrefabIndex);
                  if (newNode) {
                    _context4.next = 16;
                    break;
                  }
                  console.error("[VScrollView] \u65E0\u6CD5\u83B7\u53D6\u7C7B\u578B " + targetPrefabIndex + " \u7684\u8282\u70B9");
                  return _context4.abrupt("return");
                case 16:
                  newNode.parent = this.content;
                  this._slotNodes[slot] = newNode;
                  this._slotPrefabIndices[slot] = targetPrefabIndex;
                case 19:
                  if (newNode) {
                    _context4.next = 22;
                    break;
                  }
                  console.error("[VScrollView] \u69FD\u4F4D " + slot + " \u8282\u70B9\u4E3A\u7A7A\uFF0C\u7D22\u5F15 " + idx);
                  return _context4.abrupt("return");
                case 22:
                  newNode.active = true;
                  this._updateItemClickHandler(newNode, idx);
                  if (this.renderItemFn) this.renderItemFn(newNode, idx);
                  if (!this.getItemHeightFn) {
                    _context4.next = 32;
                    break;
                  }
                  expectedSize = this.getItemHeightFn(idx);
                  if (!(this._itemSizes[idx] !== expectedSize)) {
                    _context4.next = 30;
                    break;
                  }
                  this.updateItemHeight(idx, expectedSize);
                  return _context4.abrupt("return");
                case 30:
                  _context4.next = 37;
                  break;
                case 32:
                  _uit = newNode.getComponent(UITransform);
                  actualSize = this._isVertical() ? (_uit == null ? void 0 : _uit.height) || 100 : (_uit == null ? void 0 : _uit.width) || 100;
                  if (!(Math.abs(this._itemSizes[idx] - actualSize) > 1)) {
                    _context4.next = 37;
                    break;
                  }
                  this.updateItemHeight(idx, actualSize);
                  return _context4.abrupt("return");
                case 37:
                  uit = newNode.getComponent(UITransform);
                  size = this._itemSizes[idx];
                  itemStart = this._prefixPositions[idx];
                  if (this._isVertical()) {
                    anchorY = (_uit$anchorY = uit == null ? void 0 : uit.anchorY) != null ? _uit$anchorY : 0.5;
                    anchorOffsetY = size * (1 - anchorY);
                    nodeY = itemStart + anchorOffsetY;
                    y = -nodeY;
                    newNode.setPosition(0, this.pixelAlign ? Math.round(y) : y);
                  } else {
                    // 修改：横向模式下，itemStart 是正值，但 content.x 是负值
                    // 所以 item 的 x 位置应该直接使用 itemStart（因为 content 整体向左移动）
                    anchorX = (_uit$anchorX = uit == null ? void 0 : uit.anchorX) != null ? _uit$anchorX : 0.5;
                    anchorOffsetX = size * anchorX;
                    nodeX = itemStart + anchorOffsetX; // 不需要取负，因为 content 本身已经是负值了
                    x = nodeX;
                    newNode.setPosition(this.pixelAlign ? Math.round(x) : x, 0);
                  }
                  if (this._needAnimateIndices.has(idx)) {
                    if (this.playItemAppearAnimationFn) this.playItemAppearAnimationFn(newNode, idx);else this._playDefaultItemAppearAnimation(newNode, idx);
                    this._needAnimateIndices.delete(idx);
                  }
                  _context4.next = 59;
                  break;
                case 44:
                  if (node) {
                    _context4.next = 46;
                    break;
                  }
                  return _context4.abrupt("return");
                case 46:
                  node.active = true;
                  stride = this.itemMainSize + this.spacing;
                  line = Math.floor(idx / this.gridCount);
                  gridPos = idx % this.gridCount;
                  _uit2 = node.getComponent(UITransform); // 1. 计算基础位置（包含 headerSpacing）
                  _itemStart = this.headerSpacing + line * stride; // 2. 计算全局偏移（视口居中）- 只在内容小于视口时生效
                  globalOffset = 0;
                  shouldAutoCenter = false; // 是否应该居中
                  if (this.autoCenter) {
                    totalLines = Math.ceil(this.totalCount / this.gridCount);
                    totalContentSize = this.headerSpacing + totalLines * stride - this.spacing + this.footerSpacing; // 只有当内容小于视口时才居中
                    if (totalContentSize < this._viewportSize) {
                      shouldAutoCenter = true;
                      globalOffset = (this._viewportSize - totalContentSize) / 2;
                    }
                  }
                  if (this._isVertical()) {
                    // 纵向模式：主方向是 Y，副方向是 X
                    _anchorY = (_uit2$anchorY = _uit2 == null ? void 0 : _uit2.anchorY) != null ? _uit2$anchorY : 0.5;
                    _anchorOffsetY = this.itemMainSize * (1 - _anchorY);
                    _nodeY = _itemStart + _anchorOffsetY + globalOffset;
                    _y = -_nodeY; // 3. 计算当前行的实际子项数量（行内居中）- 只在启用居中且内容小于视口时生效
                    actualCountInLine = this.gridCount;
                    if (shouldAutoCenter) {
                      startIdxOfLine = line * this.gridCount;
                      endIdxOfLine = Math.min(startIdxOfLine + this.gridCount, this.totalCount);
                      actualCountInLine = endIdxOfLine - startIdxOfLine;
                    }

                    // 根据实际数量计算总宽度和位置
                    totalWidth = actualCountInLine * this.itemCrossSize + (actualCountInLine - 1) * this.gridSpacing;
                    _x4 = gridPos * (this.itemCrossSize + this.gridSpacing) - totalWidth / 2 + this.itemCrossSize / 2;
                    node.setPosition(this.pixelAlign ? Math.round(_x4) : _x4, this.pixelAlign ? Math.round(_y) : _y);
                    if (_uit2) {
                      _uit2.width = this.itemCrossSize;
                      _uit2.height = this.itemMainSize;
                    }
                  } else {
                    // 横向模式：主方向是 X，副方向是 Y
                    _anchorX = (_uit2$anchorX = _uit2 == null ? void 0 : _uit2.anchorX) != null ? _uit2$anchorX : 0.5;
                    _anchorOffsetX = this.itemMainSize * _anchorX;
                    _nodeX = _itemStart + _anchorOffsetX + globalOffset;
                    _x5 = _nodeX; // 3. 计算当前列的实际子项数量（列内居中）- 只在启用居中且内容小于视口时生效
                    _actualCountInLine = this.gridCount;
                    if (shouldAutoCenter) {
                      _startIdxOfLine = line * this.gridCount;
                      _endIdxOfLine = Math.min(_startIdxOfLine + this.gridCount, this.totalCount);
                      _actualCountInLine = _endIdxOfLine - _startIdxOfLine;
                    }

                    // 根据实际数量计算总高度和位置
                    totalHeight = _actualCountInLine * this.itemCrossSize + (_actualCountInLine - 1) * this.gridSpacing;
                    _y2 = totalHeight / 2 - gridPos * (this.itemCrossSize + this.gridSpacing) - this.itemCrossSize / 2;
                    node.setPosition(this.pixelAlign ? Math.round(_x5) : _x5, this.pixelAlign ? Math.round(_y2) : _y2);
                    if (_uit2) {
                      _uit2.width = this.itemMainSize;
                      _uit2.height = this.itemCrossSize;
                    }
                  }
                  this._updateItemClickHandler(node, idx);
                  if (this.renderItemFn) this.renderItemFn(node, idx);
                  if (this._needAnimateIndices.has(idx)) {
                    if (this.playItemAppearAnimationFn) this.playItemAppearAnimationFn(node, idx);else this._playDefaultItemAppearAnimation(node, idx);
                    this._needAnimateIndices.delete(idx);
                  }
                case 59:
                case "end":
                  return _context4.stop();
              }
            }, _callee4, this);
          }));
          function _layoutSingleSlot(_x, _x2, _x3) {
            return _layoutSingleSlot2.apply(this, arguments);
          }
          return _layoutSingleSlot;
        }();
        _proto2._playDefaultItemAppearAnimation = function _playDefaultItemAppearAnimation(node, index) {};
        _proto2._updateItemClickHandler = function _updateItemClickHandler(node, index) {
          var _this7 = this;
          if (!this.useVirtualList) return;
          var itemScript = node.getComponent(VScrollViewItem);
          if (!itemScript) itemScript = node.addComponent(VScrollViewItem);
          this._initSortLayerFlag ? itemScript.onSortLayer() : itemScript.offSortLayer();
          itemScript.useItemClickEffect = this.onItemClickFn ? true : false;
          if (!itemScript.onClickCallback) {
            itemScript.onClickCallback = function (idx) {
              if (_this7.onItemClickFn) _this7.onItemClickFn(node, idx);
            };
          }
          if (!itemScript.onLongPressCallback) {
            itemScript.onLongPressCallback = function (idx) {
              if (_this7.onItemLongPressFn) _this7.onItemLongPressFn(node, idx);
            };
          }
          itemScript.setDataIndex(index);
        };
        _proto2._layoutSlots = function _layoutSlots(firstIndex, forceRender) {
          if (!this.useVirtualList) return;
          for (var s = 0; s < this._slots; s++) {
            var idx = firstIndex + s;
            var _node4 = this._slotNodes[s];
            if (idx >= this.totalCount) {
              if (_node4) _node4.active = false;
            } else {
              this._layoutSingleSlot(_node4, idx, s);
            }
          }
        };
        _proto2._recomputeContentSize = function _recomputeContentSize() {
          if (!this.useVirtualList) {
            this._contentSize = this._isVertical() ? this._contentTf.height : this._contentTf.width;
            if (this._isVertical()) {
              this._boundsMin = 0;
              this._boundsMax = Math.max(0, this._contentSize - this._viewportSize);
            } else {
              this._boundsMin = -Math.max(0, this._contentSize - this._viewportSize);
              this._boundsMax = 0;
            }
            return;
          }
          if (this.useDynamicSize) return;
          var stride = this.itemMainSize + this.spacing;
          var totalLines = Math.ceil(this.totalCount / this.gridCount);
          // 添加 headerSpacing 和 footerSpacing
          this._contentSize = totalLines > 0 ? this.headerSpacing + totalLines * stride - this.spacing + this.footerSpacing : 0;
          if (this._isVertical()) this._contentTf.height = Math.max(this._contentSize, this._viewportSize);else this._contentTf.width = Math.max(this._contentSize, this._viewportSize);
          if (this._isVertical()) {
            this._boundsMin = 0;
            this._boundsMax = Math.max(0, this._contentSize - this._viewportSize);
          } else {
            this._boundsMin = -Math.max(0, this._contentSize - this._viewportSize);
            this._boundsMax = 0;
          }
        }

        /**
         * 获取当前页索引
         */;
        _proto2.getCurrentPageIndex = function getCurrentPageIndex() {
          return this._currentPageIndex;
        }

        /**
         * 滚动到指定页
         */;
        _proto2.scrollToPage = function scrollToPage(pageIndex, animate) {
          if (animate === void 0) {
            animate = true;
          }
          if (!this.enablePageSnap) {
            console.warn('[VScrollView] 未启用分页吸附模式');
            return;
          }
          var maxPage = this._getMaxPageIndex();
          pageIndex = math$1.clamp(pageIndex, 0, maxPage);
          var targetPos = this._getPagePosition(pageIndex);
          this._scrollToPosition(targetPos, animate, this.pageSnapDuration);
          this._updateCurrentPage(pageIndex);
        }

        /**
         * 获取最大页索引
         */;
        _proto2._getMaxPageIndex = function _getMaxPageIndex() {
          if (this.useDynamicSize) {
            return Math.max(0, this.totalCount - 1);
          } else {
            var totalLines = Math.ceil(this.totalCount / this.gridCount);
            return Math.max(0, totalLines - 1);
          }
        }

        /**
         * 根据当前位置计算最近的页索引
         */;
        _proto2._getNearestPageIndex = function _getNearestPageIndex() {
          var pos = this._getContentMainPos();
          var searchPos = this._isVertical() ? pos : -pos;
          if (this.useDynamicSize) {
            // 不等大小模式：根据 item 的中心位置判断
            var nearestIdx = 0;
            var minDist = Infinity;
            for (var i = 0; i < this.totalCount; i++) {
              var itemStart = this._prefixPositions[i];
              var itemSize = this._itemSizes[i];
              var dist = Math.abs(searchPos - itemStart);
              if (dist < minDist) {
                minDist = dist;
                nearestIdx = i;
              }
            }
            return nearestIdx;
          } else {
            // 等大小模式：根据行/列计算
            var stride = this.itemMainSize + this.spacing;
            var adjustedPos = Math.max(0, searchPos - this.headerSpacing);
            var line = Math.round(adjustedPos / stride);
            return math$1.clamp(line, 0, this._getMaxPageIndex());
          }
        }

        /**
         * 根据页索引计算目标位置
         */;
        _proto2._getPagePosition = function _getPagePosition(pageIndex) {
          var targetPos = 0;
          if (this.useDynamicSize) {
            targetPos = this._prefixPositions[pageIndex] || 0;
          } else {
            targetPos = this.headerSpacing + pageIndex * (this.itemMainSize + this.spacing);
          }

          // 横向模式取负值
          if (!this._isVertical()) {
            targetPos = -targetPos;
          }

          // 限制在边界范围内
          return math$1.clamp(targetPos, this._boundsMin, this._boundsMax);
        }

        /**
         * 更新当前页并触发回调
         */;
        _proto2._updateCurrentPage = function _updateCurrentPage(pageIndex) {
          if (this._currentPageIndex !== pageIndex) {
            this._currentPageIndex = pageIndex;
            if (this.onPageChangeFn) {
              this.onPageChangeFn(pageIndex);
            }
          }
        }

        /**
         * 执行分页吸附
         */;
        _proto2._performPageSnap = function _performPageSnap() {
          if (!this.enablePageSnap) return;

          // 如果正在 tween 吸附中，不重复执行
          if (this._scrollTween) return;
          var nearestPage = this._getNearestPageIndex();
          var targetPage = math$1.clamp(nearestPage, 0, this._getMaxPageIndex());
          var targetPos = this._getPagePosition(targetPage);
          var currentPos = this._getContentMainPos();

          // 如果已经在目标位置，只更新页码
          if (Math.abs(targetPos - currentPos) < 1) {
            this._updateCurrentPage(targetPage);
            return;
          }
          this._velocity = 0;
          this._scrollToPosition(targetPos, true, this.pageSnapDuration);
          this._updateCurrentPage(targetPage);
        }
        /**
         * 根据滑动距离执行分页吸附
         */;
        _proto2._performPageSnapByDistance = function _performPageSnapByDistance() {
          if (!this.enablePageSnap) return;
          if (this._scrollTween) return;
          var currentPos = this._getContentMainPos();
          var dragDistance = currentPos - this._pageStartPos; // 滑动距离

          // 获取当前页的尺寸
          var pageSize = this._getCurrentPageSize();

          // 判断翻页的距离阈值
          var threshold = pageSize * this.pageSnapDistanceRatio;

          // 基于当前页索引计算目标页
          var targetPage = this._currentPageIndex;
          var maxPage = this._getMaxPageIndex();
          if (this._isVertical()) {
            // 纵向：dragDistance > 0 表示向下滑（看上一页），< 0 表示向上滑（看下一页）
            if (dragDistance > threshold) {
              targetPage = this._currentPageIndex + 1;
            } else if (dragDistance < -threshold) {
              targetPage = this._currentPageIndex - 1;
            }
          } else {
            // 横向：dragDistance < 0 表示向左滑（看下一页），> 0 表示向右滑（看上一页）
            if (dragDistance < -threshold) {
              targetPage = this._currentPageIndex + 1;
            } else if (dragDistance > threshold) {
              targetPage = this._currentPageIndex - 1;
            }
          }

          // 限制范围
          targetPage = math$1.clamp(targetPage, 0, maxPage);
          var targetPos = this._getPagePosition(targetPage);

          // 如果已经在目标位置，只更新页码
          if (Math.abs(targetPos - currentPos) < 1) {
            this._updateCurrentPage(targetPage);
            this._velocity = 0;
            return;
          }
          this._velocity = 0;
          this._scrollToPosition(targetPos, true, this.pageSnapDuration);
          this._updateCurrentPage(targetPage);
        }

        /**
         * 获取当前页的尺寸
         */;
        _proto2._getCurrentPageSize = function _getCurrentPageSize() {
          if (this.useDynamicSize) {
            var _pageIndex = math$1.clamp(this._currentPageIndex, 0, this.totalCount - 1);
            return this._itemSizes[_pageIndex] || 100;
          } else {
            return this.itemMainSize + this.spacing;
          }
        }

        /**
         * 根据位置计算页索引
         */;
        _proto2._getPageIndexByPosition = function _getPageIndexByPosition(pos) {
          var searchPos = this._isVertical() ? pos : -pos;
          if (this.useDynamicSize) {
            return this._posToFirstIndex(searchPos);
          } else {
            var stride = this.itemMainSize + this.spacing;
            var adjustedPos = Math.max(0, searchPos - this.headerSpacing);
            var line = Math.floor(adjustedPos / stride);
            return math$1.clamp(line, 0, this._getMaxPageIndex());
          }
        };
        _createClass(VirtualScrollView, [{
          key: "_contentTf",
          get: function get() {
            this.content = this._getContentNode();
            return this.content.getComponent(UITransform);
          }
        }, {
          key: "_viewportTf",
          get: function get() {
            return this.node.getComponent(UITransform);
          }
        }]);
        return VirtualScrollView;
      }(Component), (_descriptor$7 = _applyDecoratedDescriptor(_class3.prototype, "content", [_dec3$g], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$7 = _applyDecoratedDescriptor(_class3.prototype, "useVirtualList", [_dec4$d], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      }), _descriptor3$6 = _applyDecoratedDescriptor(_class3.prototype, "direction", [_dec5$9], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return ScrollDirection.VERTICAL;
        }
      }), _descriptor4$4 = _applyDecoratedDescriptor(_class3.prototype, "itemCreationMode", [_dec6$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return ItemCreationMode.PREFAB;
        }
      }), _descriptor5$3 = _applyDecoratedDescriptor(_class3.prototype, "itemNode", [_dec7$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor6$3 = _applyDecoratedDescriptor(_class3.prototype, "itemPrefab", [_dec8$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor7$3 = _applyDecoratedDescriptor(_class3.prototype, "useDynamicSize", [_dec9$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor8$3 = _applyDecoratedDescriptor(_class3.prototype, "autoCenter", [_dec10$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor9$2 = _applyDecoratedDescriptor(_class3.prototype, "enablePageSnap", [_dec11$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor10$2 = _applyDecoratedDescriptor(_class3.prototype, "pageSnapDuration", [_dec12$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.15;
        }
      }), _descriptor11$2 = _applyDecoratedDescriptor(_class3.prototype, "pageSnapDistanceRatio", [_dec13$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.15;
        }
      }), _descriptor12$2 = _applyDecoratedDescriptor(_class3.prototype, "pageSnapTriggerVelocity", [_dec14$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 600;
        }
      }), _descriptor13$1 = _applyDecoratedDescriptor(_class3.prototype, "useDynamicHeight", [_dec15$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor14$1 = _applyDecoratedDescriptor(_class3.prototype, "columns", [_dec16$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor15$1 = _applyDecoratedDescriptor(_class3.prototype, "columnSpacing", [_dec17$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor16$1 = _applyDecoratedDescriptor(_class3.prototype, "itemNodes", [_dec18$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      }), _descriptor17$1 = _applyDecoratedDescriptor(_class3.prototype, "itemPrefabs", [_dec19$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      }), _descriptor18$1 = _applyDecoratedDescriptor(_class3.prototype, "gridCount", [_dec20$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor19$1 = _applyDecoratedDescriptor(_class3.prototype, "gridSpacing", [_dec21$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor20$1 = _applyDecoratedDescriptor(_class3.prototype, "spacing", [_dec22$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor21$1 = _applyDecoratedDescriptor(_class3.prototype, "headerSpacing", [_dec23$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor22 = _applyDecoratedDescriptor(_class3.prototype, "footerSpacing", [_dec24$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor23 = _applyDecoratedDescriptor(_class3.prototype, "totalCount", [_dec25$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 50;
        }
      }), _descriptor24 = _applyDecoratedDescriptor(_class3.prototype, "buffer", [_dec26$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor25 = _applyDecoratedDescriptor(_class3.prototype, "enablePullRefresh", [_dec27$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor26 = _applyDecoratedDescriptor(_class3.prototype, "pullRefreshThreshold", [_dec28$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor27 = _applyDecoratedDescriptor(_class3.prototype, "pullRefreshMaxOffset", [_dec29$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 150;
        }
      }), _descriptor28 = _applyDecoratedDescriptor(_class3.prototype, "enableLoadMore", [_dec30$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor29 = _applyDecoratedDescriptor(_class3.prototype, "loadMoreThreshold", [_dec31$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor30 = _applyDecoratedDescriptor(_class3.prototype, "loadMoreMaxOffset", [_dec32$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 150;
        }
      }), _descriptor31 = _applyDecoratedDescriptor(_class3.prototype, "pullDampingRate", [_dec33$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor32 = _applyDecoratedDescriptor(_class3.prototype, "pixelAlign", [_dec34$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      }), _descriptor33 = _applyDecoratedDescriptor(_class3.prototype, "disableBounce", [_dec35$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor34 = _applyDecoratedDescriptor(_class3.prototype, "inertiaDampK", [_dec36$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor35 = _applyDecoratedDescriptor(_class3.prototype, "springK", [_dec37$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 150.0;
        }
      }), _descriptor36 = _applyDecoratedDescriptor(_class3.prototype, "springC", [_dec38$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 26.0;
        }
      }), _descriptor37 = _applyDecoratedDescriptor(_class3.prototype, "velocitySnap", [_dec39], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor38 = _applyDecoratedDescriptor(_class3.prototype, "velocityWindow", [_dec40], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.08;
        }
      }), _descriptor39 = _applyDecoratedDescriptor(_class3.prototype, "maxVelocity", [_dec41], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 6000;
        }
      }), _descriptor40 = _applyDecoratedDescriptor(_class3.prototype, "useIOSDecelerationCurve", [_dec42], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      })), _class3)) || _class2$7) || _class2$7);
      cclegacy._RF.pop();
      var __defProp = Object.defineProperty;
      var __defNormalProp = function __defNormalProp(obj, key, value) {
        return key in obj ? __defProp(obj, key, {
          enumerable: true,
          configurable: true,
          writable: true,
          value: value
        }) : obj[key] = value;
      };
      var __publicField = function __publicField(obj, key, value) {
        return __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
      };

      // src/rng.ts
      var RNG = function RNG() {};

      // src/generators/function.ts
      var FunctionRNG = /*#__PURE__*/function (_RNG) {
        _inheritsLoose(_FunctionRNG, _RNG);
        function _FunctionRNG(rngFn) {
          var _this;
          var _a;
          _this = _RNG.call(this) || this;
          __publicField(_assertThisInitialized(_this), "_name");
          __publicField(_assertThisInitialized(_this), "_rngFn");
          _this._name = (_a = rngFn.name) != null ? _a : "function";
          _this._rngFn = rngFn;
          return _this;
        }
        var _proto = _FunctionRNG.prototype;
        _proto.next = function next() {
          return this._rngFn();
        };
        _proto.clone = function clone() {
          return new _FunctionRNG(this._rngFn);
        };
        _createClass(_FunctionRNG, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }]);
        return _FunctionRNG;
      }(RNG);

      // src/utils.ts
      function createRNG(seedOrRNG) {
        switch (typeof seedOrRNG) {
          case "object":
            if (seedOrRNG instanceof RNG) {
              return seedOrRNG;
            }
            break;
          case "function":
            return new FunctionRNG(seedOrRNG);
          default:
            return new ARC4RNG(seedOrRNG);
        }
        throw new Error("invalid RNG seed or instance \"" + seedOrRNG + "\"");
      }
      function mixKey(seed, key) {
        var _a;
        var seedStr = "" + seed;
        var smear = 0;
        var j = 0;
        while (j < seedStr.length) {
          key[255 & j] = 255 & (smear ^= ((_a = key[255 & j]) != null ? _a : 0) * 19) + seedStr.charCodeAt(j++);
        }
        if (!key.length) {
          return [0];
        }
        return key;
      }
      function shuffleInPlace(gen, array) {
        for (var i = array.length - 1; i > 0; i -= 1) {
          var j = Math.floor(gen.next() * (i + 1));
          var tmp = array[i];
          array[i] = array[j];
          array[j] = tmp;
        }
      }
      function sparseFisherYates(gen, array, k) {
        var _a, _b;
        var H = /* @__PURE__ */new Map();
        var lastIndex = array.length - 1;
        var result = Array.from({
          length: k
        });
        for (var i = 0; i < k; i++) {
          var remaining = lastIndex - i + 1;
          var r = Math.floor(gen.next() * remaining);
          result[i] = array[(_a = H.get(r)) != null ? _a : r];
          H.set(r, (_b = H.get(lastIndex - i)) != null ? _b : lastIndex - i);
        }
        return result;
      }

      // src/generators/arc4.ts
      var _arc4_startdenom = 281474976710656;
      var _arc4_significance = 4503599627370496;
      var _arc4_overflow = 9007199254740992;
      var ARC4RNG = /*#__PURE__*/function (_RNG2) {
        _inheritsLoose(_ARC4RNG, _RNG2);
        function _ARC4RNG(seed) {
          var _this2;
          if (seed === void 0) {
            seed = crypto.randomUUID();
          }
          _this2 = _RNG2.call(this) || this;
          __publicField(_assertThisInitialized(_this2), "_seed");
          __publicField(_assertThisInitialized(_this2), "i");
          __publicField(_assertThisInitialized(_this2), "j");
          __publicField(_assertThisInitialized(_this2), "S");
          _this2._seed = seed;
          var key = mixKey(seed, []);
          var S = [];
          var keylen = key.length;
          _this2.i = 0;
          _this2.j = 0;
          _this2.S = S;
          var i = 0;
          while (i <= 255) {
            S[i] = i++;
          }
          for (var i2 = 0, j = 0; i2 <= 255; i2++) {
            var t = S[i2];
            j = 255 & j + key[i2 % keylen] + t;
            S[i2] = S[j];
            S[j] = t;
          }
          _this2.g(256);
          return _this2;
        }
        var _proto2 = _ARC4RNG.prototype;
        _proto2.next = function next() {
          var n = this.g(6);
          var d = _arc4_startdenom;
          var x = 0;
          while (n < _arc4_significance) {
            n = (n + x) * 256;
            d *= 256;
            x = this.g(1);
          }
          while (n >= _arc4_overflow) {
            n /= 2;
            d /= 2;
            x >>>= 1;
          }
          return (n + x) / d;
        };
        _proto2.g = function g(count) {
          var S = this.S;
          var i = this.i,
            j = this.j;
          var r = 0;
          while (count--) {
            i = 255 & i + 1;
            var t = S[i];
            S[j] = t;
            j = 255 & j + t;
            S[i] = S[j];
            r = r * 256 + S[255 & S[i] + t];
          }
          this.i = i;
          this.j = j;
          return r;
        };
        _proto2.clone = function clone() {
          return new _ARC4RNG(this._seed);
        };
        _createClass(_ARC4RNG, [{
          key: "name",
          get: function get() {
            return "arc4";
          }
        }]);
        return _ARC4RNG;
      }(RNG);

      // src/generators/math-random.ts
      var MathRandomRNG = /*#__PURE__*/function (_RNG3) {
        _inheritsLoose(_MathRandomRNG, _RNG3);
        function _MathRandomRNG() {
          return _RNG3.apply(this, arguments) || this;
        }
        var _proto3 = _MathRandomRNG.prototype;
        _proto3.next = function next() {
          return Math.random();
        };
        _proto3.clone = function clone() {
          return new _MathRandomRNG();
        };
        _createClass(_MathRandomRNG, [{
          key: "name",
          get: function get() {
            return "Math.random";
          }
        }]);
        return _MathRandomRNG;
      }(RNG);

      // src/validation.ts
      function numberValidator(num) {
        return new NumberValidator(num);
      }
      var NumberValidator = function NumberValidator(num) {
        var _this4 = this;
        __publicField(this, "n");
        __publicField(this, "isInt", function () {
          if (Number.isInteger(_this4.n)) {
            return _this4;
          }
          throw new Error("Expected number to be an integer, got " + _this4.n);
        });
        __publicField(this, "isPositive", function () {
          if (_this4.n > 0) {
            return _this4;
          }
          throw new Error("Expected number to be positive, got " + _this4.n);
        });
        __publicField(this, "lessThan", function (v) {
          if (_this4.n < v) {
            return _this4;
          }
          throw new Error("Expected number to be less than " + v + ", got " + _this4.n);
        });
        __publicField(this, "lessThanOrEqual", function (v) {
          if (_this4.n <= v) {
            return _this4;
          }
          throw new Error("Expected number to be less than or equal to " + v + ", got " + _this4.n);
        });
        __publicField(this, "greaterThanOrEqual", function (v) {
          if (_this4.n >= v) {
            return _this4;
          }
          throw new Error("Expected number to be greater than or equal to " + v + ", got " + _this4.n);
        });
        __publicField(this, "greaterThan", function (v) {
          if (_this4.n > v) {
            return _this4;
          }
          throw new Error("Expected number to be greater than " + v + ", got " + _this4.n);
        });
        this.n = num;
      };

      // src/distributions/bates.ts
      function _bates(random, n) {
        if (n === void 0) {
          n = 1;
        }
        numberValidator(n).isInt().isPositive();
        var irwinHall2 = random.irwinHall(n);
        return function () {
          return irwinHall2() / n;
        };
      }

      // src/distributions/bernoulli.ts
      function _bernoulli(random, p) {
        if (p === void 0) {
          p = 0.5;
        }
        numberValidator(p).greaterThanOrEqual(0).lessThanOrEqual(1);
        return function () {
          return Math.min(1, Math.floor(random.next() + p));
        };
      }

      // src/distributions/binomial.ts
      function _binomial(random, n, p) {
        if (n === void 0) {
          n = 1;
        }
        if (p === void 0) {
          p = 0.5;
        }
        numberValidator(n).isInt().isPositive();
        numberValidator(p).greaterThanOrEqual(0).lessThan(1);
        return function () {
          var i = 0;
          var x = 0;
          while (i++ < n) {
            if (random.next() < p) {
              x++;
            }
          }
          return x;
        };
      }

      // src/distributions/exponential.ts
      function _exponential(random, lambda) {
        if (lambda === void 0) {
          lambda = 1;
        }
        numberValidator(lambda).isPositive();
        return function () {
          return -Math.log(1 - random.next()) / lambda;
        };
      }

      // src/distributions/geometric.ts
      function _geometric(random, p) {
        if (p === void 0) {
          p = 0.5;
        }
        numberValidator(p).greaterThan(0).lessThan(1);
        var invLogP = 1 / Math.log(1 - p);
        return function () {
          return Math.floor(1 + Math.log(random.next()) * invLogP);
        };
      }

      // src/distributions/irwin-hall.ts
      function _irwinHall(random, n) {
        if (n === void 0) {
          n = 1;
        }
        numberValidator(n).isInt().greaterThanOrEqual(0);
        return function () {
          var sum = 0;
          for (var i = 0; i < n; ++i) {
            sum += random.next();
          }
          return sum;
        };
      }

      // src/distributions/log-normal.ts
      function _logNormal(random, mu, sigma) {
        if (mu === void 0) {
          mu = 0;
        }
        if (sigma === void 0) {
          sigma = 1;
        }
        var normal2 = random.normal(mu, sigma);
        return function () {
          return Math.exp(normal2());
        };
      }

      // src/distributions/normal.ts
      function _normal(random, mu, sigma) {
        if (mu === void 0) {
          mu = 0;
        }
        if (sigma === void 0) {
          sigma = 1;
        }
        return function () {
          var x, y, r;
          do {
            x = random.next() * 2 - 1;
            y = random.next() * 2 - 1;
            r = x * x + y * y;
          } while (!r || r > 1);
          return mu + sigma * y * Math.sqrt(-2 * Math.log(r) / r);
        };
      }

      // src/distributions/pareto.ts
      function _pareto(random, alpha) {
        if (alpha === void 0) {
          alpha = 1;
        }
        numberValidator(alpha).greaterThanOrEqual(0);
        var invAlpha = 1 / alpha;
        return function () {
          return 1 / Math.pow(1 - random.next(), invAlpha);
        };
      }

      // src/distributions/poisson.ts
      var logFactorialTable = [0, 0, 0.6931471805599453, 1.791759469228055, 3.1780538303479458, 4.787491742782046, 6.579251212010101, 8.525161361065415, 10.60460290274525, 12.801827480081469];
      var logFactorial = function logFactorial(k) {
        return logFactorialTable[k];
      };
      var logSqrt2PI = 0.9189385332046727;
      function _poisson(random, lambda) {
        if (lambda === void 0) {
          lambda = 1;
        }
        numberValidator(lambda).isPositive();
        if (lambda < 10) {
          var expMean = Math.exp(-lambda);
          return function () {
            var p = expMean;
            var x = 0;
            var u = random.next();
            while (u > p) {
              u = u - p;
              p = lambda * p / ++x;
            }
            return x;
          };
        } else {
          var smu = Math.sqrt(lambda);
          var b = 0.931 + 2.53 * smu;
          var a = -0.059 + 0.02483 * b;
          var invAlpha = 1.1239 + 1.1328 / (b - 3.4);
          var vR = 0.9277 - 3.6224 / (b - 2);
          return function () {
            var _a;
            while (true) {
              var u = void 0;
              var v = random.next();
              if (v <= 0.86 * vR) {
                u = v / vR - 0.43;
                return Math.floor((2 * a / (0.5 - Math.abs(u)) + b) * u + lambda + 0.445);
              }
              if (v >= vR) {
                u = random.next() - 0.5;
              } else {
                u = v / vR - 0.93;
                u = (u < 0 ? -0.5 : 0.5) - u;
                v = random.next() * vR;
              }
              var us = 0.5 - Math.abs(u);
              if (us < 0.013 && v > us) {
                continue;
              }
              var k = Math.floor((2 * a / us + b) * u + lambda + 0.445);
              v = v * invAlpha / (a / (us * us) + b);
              if (k >= 10) {
                var t = (k + 0.5) * Math.log(lambda / k) - lambda - logSqrt2PI + k - (1 / 12 - (1 / 360 - 1 / (1260 * k * k)) / (k * k)) / k;
                if (Math.log(v * smu) <= t) {
                  return k;
                }
              } else if (k >= 0) {
                var f = (_a = logFactorial(k)) != null ? _a : 0;
                if (Math.log(v) <= k * Math.log(lambda) - lambda - f) {
                  return k;
                }
              }
            }
          };
        }
      }

      // src/distributions/uniform.ts
      function _uniform(random, min, max) {
        if (min === void 0) {
          min = 0;
        }
        if (max === void 0) {
          max = 1;
        }
        return function () {
          return random.next() * (max - min) + min;
        };
      }

      // src/distributions/uniform-boolean.ts
      function _uniformBoolean(random) {
        return function () {
          return random.next() >= 0.5;
        };
      }

      // src/distributions/uniform-int.ts
      function _uniformInt(random, min, max) {
        if (min === void 0) {
          min = 0;
        }
        if (max === void 0) {
          max = 1;
        }
        if (max === void 0) {
          max = min === void 0 ? 1 : min;
          min = 0;
        }
        numberValidator(min).isInt();
        numberValidator(max).isInt();
        return function () {
          return Math.floor(random.next() * (max - min + 1) + min);
        };
      }

      // src/distributions/weibull.ts
      function _weibull(random, lambda, k) {
        numberValidator(lambda).greaterThan(0);
        numberValidator(k).greaterThan(0);
        return function () {
          var u = 1 - random.next();
          return lambda * Math.pow(-Math.log(u), 1 / k);
        };
      }

      // src/random.ts
      var Random = /*#__PURE__*/function () {
        function _Random(seedOrRNG) {
          if (seedOrRNG === void 0) {
            seedOrRNG = new MathRandomRNG();
          }
          __publicField(this, "_rng");
          __publicField(this, "_cache", {});
          this._rng = createRNG(seedOrRNG);
        }
        /**
         * @member {RNG} rng - Underlying pseudo-random number generator.
         */
        var _proto5 = _Random.prototype;
        /**
         * Creates a new `Random` instance, optionally specifying parameters to
         * set a new seed.
         */
        _proto5.clone = function clone(seedOrRNG) {
          if (seedOrRNG === void 0) {
            seedOrRNG = this.rng.clone();
          }
          return new _Random(seedOrRNG);
        }
        /**
         * Sets the underlying pseudorandom number generator.
         *
         * @example
         * ```ts
         * import random from 'random'
         *
         * random.use('example-seed')
         * // or
         * random.use(Math.random)
         * ```
         */;
        _proto5.use = function use(seedOrRNG) {
          this._rng = createRNG(seedOrRNG);
          this._cache = {};
        }
        // --------------------------------------------------------------------------
        // Uniform utility functions
        // --------------------------------------------------------------------------
        /**
         * Convenience wrapper around `this.rng.next()`
         *
         * Returns a floating point number in [0, 1).
         *
         * @return {number}
         */;
        _proto5.next = function next() {
          return this._rng.next();
        }
        /**
         * Samples a uniform random floating point number, optionally specifying
         * lower and upper bounds.
         *
         * Convenience wrapper around `random.uniform()`
         *
         * @param {number} [min=0] - Lower bound (float, inclusive)
         * @param {number} [max=1] - Upper bound (float, exclusive)
         */;
        _proto5.float = function float(min, max) {
          return this.uniform(min, max)();
        }
        /**
         * Samples a uniform random integer, optionally specifying lower and upper
         * bounds.
         *
         * Convenience wrapper around `random.uniformInt()`
         *
         * @param {number} [min=0] - Lower bound (integer, inclusive)
         * @param {number} [max=1] - Upper bound (integer, inclusive)
         */;
        _proto5.int = function int(min, max) {
          return this.uniformInt(min, max)();
        }
        /**
         * Samples a uniform random integer, optionally specifying lower and upper
         * bounds.
         *
         * Convenience wrapper around `random.uniformInt()`
         *
         * @alias `random.int`
         *
         * @param {number} [min=0] - Lower bound (integer, inclusive)
         * @param {number} [max=1] - Upper bound (integer, inclusive)
         */;
        _proto5.integer = function integer(min, max) {
          return this.uniformInt(min, max)();
        }
        /**
         * Samples a uniform random boolean value.
         *
         * Convenience wrapper around `random.uniformBoolean()`
         *
         * @alias `random.boolean`
         */;
        _proto5.bool = function bool() {
          return this.uniformBoolean()();
        }
        /**
         * Samples a uniform random boolean value.
         *
         * Convenience wrapper around `random.uniformBoolean()`
         */;
        _proto5.boolean = function boolean() {
          return this.uniformBoolean()();
        }
        /**
         * Returns an item chosen uniformly at random from the given array.
         *
         * Convenience wrapper around `random.uniformInt()`
         *
         * @param {Array<T>} [array] - Input array
         */;
        _proto5.choice = function choice(array) {
          if (!Array.isArray(array)) {
            throw new TypeError("Random.choice expected input to be an array, got " + typeof array);
          }
          var length = array.length;
          if (length > 0) {
            var index = this.uniformInt(0, length - 1)();
            return array[index];
          } else {
            return void 0;
          }
        }
        /**
         * Returns a random subset of k items from the given array (without replacement).
         *
         * @param {Array<T>} [array] - Input array
         */;
        _proto5.sample = function sample(array, k) {
          if (!Array.isArray(array)) {
            throw new TypeError("Random.sample expected input to be an array, got " + typeof array);
          }
          if (k < 0 || k > array.length) {
            throw new Error("Random.sample: k must be between 0 and array.length (" + array.length + "), got " + k);
          }
          return sparseFisherYates(this.rng, array, k);
        }
        /**
         * Generates a thunk which returns samples of size k from the given array.
         *
         * This is for convenience only; there is no gain in efficiency.
         *
         * @param {Array<T>} [array] - Input array
         */;
        _proto5.sampler = function sampler(array, k) {
          if (!Array.isArray(array)) {
            throw new TypeError("Random.sampler expected input to be an array, got " + typeof array);
          }
          if (k < 0 || k > array.length) {
            throw new Error("Random.sampler: k must be between 0 and array.length (" + array.length + "), got " + k);
          }
          var gen = this.rng;
          return function () {
            return sparseFisherYates(gen, array, k);
          };
        }
        /**
         * Returns a shuffled copy of the given array.
         *
         * @param {Array<T>} [array] - Input array
         */;
        _proto5.shuffle = function shuffle(array) {
          if (!Array.isArray(array)) {
            throw new TypeError("Random.shuffle expected input to be an array, got " + typeof array);
          }
          var copy = [].concat(array);
          shuffleInPlace(this.rng, copy);
          return copy;
        }
        /**
         * Generates a thunk which returns shuffled copies of the given array.
         *
         * @param {Array<T>} [array] - Input array
         */;
        _proto5.shuffler = function shuffler(array) {
          if (!Array.isArray(array)) {
            throw new TypeError("Random.shuffler expected input to be an array, got " + typeof array);
          }
          var gen = this.rng;
          var copy = [].concat(array);
          return function () {
            shuffleInPlace(gen, copy);
            return [].concat(copy);
          };
        }
        // --------------------------------------------------------------------------
        // Uniform distributions
        // --------------------------------------------------------------------------
        /**
         * Generates a [Continuous uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)).
         *
         * @param {number} [min=0] - Lower bound (float, inclusive)
         * @param {number} [max=1] - Upper bound (float, exclusive)
         */;
        _proto5.uniform = function uniform(min, max) {
          return this._memoize("uniform", _uniform, min, max);
        }
        /**
         * Generates a [Discrete uniform distribution](https://en.wikipedia.org/wiki/Discrete_uniform_distribution).
         *
         * @param {number} [min=0] - Lower bound (integer, inclusive)
         * @param {number} [max=1] - Upper bound (integer, inclusive)
         */;
        _proto5.uniformInt = function uniformInt(min, max) {
          return this._memoize("uniformInt", _uniformInt, min, max);
        }
        /**
         * Generates a [Discrete uniform distribution](https://en.wikipedia.org/wiki/Discrete_uniform_distribution),
         * with two possible outcomes, `true` or `false.
         *
         * This method is analogous to flipping a coin.
         */;
        _proto5.uniformBoolean = function uniformBoolean() {
          return this._memoize("uniformBoolean", _uniformBoolean);
        }
        // --------------------------------------------------------------------------
        // Normal distributions
        // --------------------------------------------------------------------------
        /**
         * Generates a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution).
         *
         * @param {number} [mu=0] - Mean
         * @param {number} [sigma=1] - Standard deviation
         */;
        _proto5.normal = function normal(mu, sigma) {
          return _normal(this, mu, sigma);
        }
        /**
         * Generates a [Log-normal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution).
         *
         * @param {number} [mu=0] - Mean of underlying normal distribution
         * @param {number} [sigma=1] - Standard deviation of underlying normal distribution
         */;
        _proto5.logNormal = function logNormal(mu, sigma) {
          return _logNormal(this, mu, sigma);
        }
        // --------------------------------------------------------------------------
        // Bernoulli distributions
        // --------------------------------------------------------------------------
        /**
         * Generates a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution).
         *
         * @param {number} [p=0.5] - Success probability of each trial.
         */;
        _proto5.bernoulli = function bernoulli(p) {
          return _bernoulli(this, p);
        }
        /**
         * Generates a [Binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution).
         *
         * @param {number} [n=1] - Number of trials.
         * @param {number} [p=0.5] - Success probability of each trial.
         */;
        _proto5.binomial = function binomial(n, p) {
          return _binomial(this, n, p);
        }
        /**
         * Generates a [Geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution).
         *
         * @param {number} [p=0.5] - Success probability of each trial.
         */;
        _proto5.geometric = function geometric(p) {
          return _geometric(this, p);
        }
        // --------------------------------------------------------------------------
        // Poisson distributions
        // --------------------------------------------------------------------------
        /**
         * Generates a [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution).
         *
         * @param {number} [lambda=1] - Mean (lambda > 0)
         */;
        _proto5.poisson = function poisson(lambda) {
          return _poisson(this, lambda);
        }
        /**
         * Generates an [Exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution).
         *
         * @param {number} [lambda=1] - Inverse mean (lambda > 0)
         */;
        _proto5.exponential = function exponential(lambda) {
          return _exponential(this, lambda);
        }
        // --------------------------------------------------------------------------
        // Misc distributions
        // --------------------------------------------------------------------------
        /**
         * Generates an [Irwin Hall distribution](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution).
         *
         * @param {number} [n=1] - Number of uniform samples to sum (n >= 0)
         */;
        _proto5.irwinHall = function irwinHall(n) {
          return _irwinHall(this, n);
        }
        /**
         * Generates a [Bates distribution](https://en.wikipedia.org/wiki/Bates_distribution).
         *
         * @param {number} [n=1] - Number of uniform samples to average (n >= 1)
         */;
        _proto5.bates = function bates(n) {
          return _bates(this, n);
        }
        /**
         * Generates a [Pareto distribution](https://en.wikipedia.org/wiki/Pareto_distribution).
         *
         * @param {number} [alpha=1] - Alpha
         */;
        _proto5.pareto = function pareto(alpha) {
          return _pareto(this, alpha);
        }
        /**
         * Generates a [Weibull distribution](https://en.wikipedia.org/wiki/Weibull_distribution).
         *
         * @param {number} [lambda] - Lambda, the scale parameter
         * @param {number} [k] - k, the shape parameter
         */;
        _proto5.weibull = function weibull(lambda, k) {
          return _weibull(this, lambda, k);
        }
        // --------------------------------------------------------------------------
        // Internal
        // --------------------------------------------------------------------------
        /**
         * Memoizes distributions to ensure they're only created when necessary.
         *
         * Returns a thunk which that returns independent, identically distributed
         * samples from the specified distribution.
         *
         * @internal
         *
         * @param {string} label - Name of distribution
         * @param {function} getter - Function which generates a new distribution
         * @param {...*} args - Distribution-specific arguments
         */;
        _proto5._memoize = function _memoize(label, getter) {
          for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            args[_key - 2] = arguments[_key];
          }
          var key = "" + args.join(";");
          var value = this._cache[label];
          if (value === void 0 || value.key !== key) {
            value = {
              key: key,
              distribution: getter.apply(void 0, [this].concat(args))
            };
            this._cache[label] = value;
          }
          return value.distribution;
        };
        _createClass(_Random, [{
          key: "rng",
          get: function get() {
            return this._rng;
          }
        }]);
        return _Random;
      }();
      var random_default = new Random();
      cclegacy._RF.push({}, "ab896VQB4RBv6/oHmTB1iOj", "Random", undefined);
      function findMinIndexBy(items, randomValue, getWeight) {
        // 根据权重找到对应的项
        var weightSum = 0;
        for (var _iterator2 = _createForOfIteratorHelperLoose(items), _step2; !(_step2 = _iterator2()).done;) {
          var _item2 = _step2.value;
          weightSum += getWeight(_item2);
          if (randomValue <= weightSum) {
            return _item2;
          }
        }
        // 理论上不会执行到这里
        throw new Error("randomValue: " + randomValue + " is out of range");
      }

      /**
       * 加权随机选择函数
       * 根据给定选项的权重随机选择一个选项
       *
       * @param rng - Random实例
       * @param items - 包含值和权重的对象数组
       * @returns 选中的项
       */
      function weightedRandomBy(rng, items, getWeight) {
        // 计算总权重
        var totalWeight = sumBy(items, getWeight);

        // 生成一个0到总权重之间的随机数
        var randomValue = rng.float(0, totalWeight);

        // 根据权重找到对应的项
        return findMinIndexBy(items, randomValue, getWeight);
      }
      cclegacy._RF.pop();
      var _dec$i, _dec2$h, _dec3$h, _dec4$e, _class$i, _class2$8, _descriptor$8, _descriptor2$8, _descriptor3$7, _dec5$a, _dec6$7, _dec7$4, _dec8$4, _dec9$4, _dec10$4, _dec11$4, _dec12$4, _dec13$3, _dec14$3, _class4$1, _class5$1, _descriptor4$5, _descriptor5$4, _descriptor6$4, _descriptor7$4, _descriptor8$4, _descriptor9$3, _descriptor10$3;
      cclegacy._RF.push({}, "e1b83B+qA9EuL3klaCaknMR", "PrefabSpawner", undefined);
      var ccclass$i = _decorator.ccclass,
        property$9 = _decorator.property,
        menu$g = _decorator.menu,
        disallowMultiple$g = _decorator.disallowMultiple;
      var ItemInfo = (_dec$i = ccclass$i('ItemInfo'), _dec2$h = property$9({
        type: Prefab,
        displayName: '预制体',
        tooltip: '需要生成的预制体'
      }), _dec3$h = property$9({
        displayName: '权重',
        tooltip: '预制体的权重，用于计算概率'
      }), _dec4$e = property$9({
        type: Node,
        displayName: '容器',
        tooltip: '创建后挂载的父节点'
      }), _dec$i(_class$i = (_class2$8 = function ItemInfo() {
        _initializerDefineProperty(this, "prefab", _descriptor$8, this);
        _initializerDefineProperty(this, "weight", _descriptor2$8, this);
        _initializerDefineProperty(this, "container", _descriptor3$7, this);
      }, (_descriptor$8 = _applyDecoratedDescriptor(_class2$8.prototype, "prefab", [_dec2$h], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$8 = _applyDecoratedDescriptor(_class2$8.prototype, "weight", [_dec3$h], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor3$7 = _applyDecoratedDescriptor(_class2$8.prototype, "container", [_dec4$e], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: null
      })), _class2$8)) || _class$i);
      var PrefabSpawner = (_dec5$a = ccclass$i('PrefabSpawner'), _dec6$7 = menu$g('Utils/PrefabSpawner'), _dec7$4 = disallowMultiple$g(true), _dec8$4 = property$9({
        type: [ItemInfo],
        tooltip: '包含预制体和对应权重的预制体池'
      }), _dec9$4 = property$9({
        tooltip: '至少生成的预制体数量'
      }), _dec10$4 = property$9({
        tooltip: '最多生成的预制体数量'
      }), _dec11$4 = property$9({
        tooltip: '额外生成预制体的二项分布概率（0-1之间）',
        range: [0, 1]
      }), _dec12$4 = property$9({
        tooltip: '预制体生成的范围半径（出现负数范围会自动翻转）'
      }), _dec13$3 = property$9({
        tooltip: '预制体生成的范围内圈半径'
      }), _dec14$3 = property$9({
        type: Node,
        tooltip: '默认预制体的容器节点'
      }), _dec5$a(_class4$1 = _dec6$7(_class4$1 = _dec7$4(_class4$1 = (_class5$1 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PrefabSpawner, _Component);
        function PrefabSpawner() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.log = new LogBuilder();
          /**
           * 预制体池，包含预制体和对应的权重
           */
          _initializerDefineProperty(_this, "itemPool", _descriptor4$5, _assertThisInitialized(_this));
          /**
           * 最小生成数量
           */
          _initializerDefineProperty(_this, "minDropCount", _descriptor5$4, _assertThisInitialized(_this));
          /**
           * 最大生成数量
           */
          _initializerDefineProperty(_this, "maxDropCount", _descriptor6$4, _assertThisInitialized(_this));
          /**
           * 二项分布概率
           */
          _initializerDefineProperty(_this, "binomialProbability", _descriptor7$4, _assertThisInitialized(_this));
          /**
           * 生成半径，决定预制体在多大范围内随机生成
           */
          _initializerDefineProperty(_this, "dropRadius", _descriptor8$4, _assertThisInitialized(_this));
          /**
           * 生成内径，决定预制体在多大范围外才能生成
           */
          _initializerDefineProperty(_this, "dropInnerRadius", _descriptor9$3, _assertThisInitialized(_this));
          /**
           * Random实例，用于生成随机数
           */
          _this.rng = new Random();
          /**
           * 预制体容器
           */
          _initializerDefineProperty(_this, "itemContainer", _descriptor10$3, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = PrefabSpawner.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
        }

        /**
         * 触发生成事件，在指定位置周围随机生成预制体
         * @param center 生成中心点
         * @param minDropCount 最小生成数量
         * @param maxDropCount 最大生成数量
         */;
        _proto.spawnPrefab = function spawnPrefab(center, minDropCount, maxDropCount) {
          if (minDropCount === void 0) {
            minDropCount = this.minDropCount;
          }
          if (maxDropCount === void 0) {
            maxDropCount = this.maxDropCount;
          }
          this.log.Method('spawnPrefab');
          if (this.itemPool.length === 0) {
            this.log.warn('预制体池为空，无法生成预制体');
            return;
          }

          // 确保最小生成数量不少于0
          var minCount = Math.max(0, minDropCount);
          // 确保最大生成数量不小于最小生成数量
          var maxCount = Math.max(minCount, maxDropCount);
          // 先生成最小数量的预制体
          var dropCount = minCount;
          // 计算额外可能生成的数量（最大数量-最小数量）
          var extraPossibleCount = maxCount - minCount;
          // 使用二项分布生成额外的预制体数量
          if (extraPossibleCount > 0) {
            var extraCount = this.rng.binomial(extraPossibleCount, this.binomialProbability)();
            dropCount += extraCount;
          }
          this.log.info("\u5728" + vec2ToString(center) + "\u5468\u56F4\u751F\u6210" + dropCount + "\u4E2A\u9884\u5236\u4F53");

          // 生成指定数量的预制体
          var nodes = [];
          var now_center = {
            x: center.x,
            y: center.y
          };
          for (var _ in range(dropCount)) {
            nodes.push(this.spawnSinglePrefab(now_center));
          }
          return nodes;
        }

        /**
         * 生成单个预制体
         */;
        _proto.spawnSinglePrefab = function spawnSinglePrefab(center) {
          var _selectedItem$contain;
          // 使用加权随机选择一个预制体
          var selectedItem = weightedRandomBy(this.rng, this.itemPool, function (item) {
            return item.weight;
          });

          // 计算随机位置（在指定位置周围的圆形区域内）
          var randomAngle = this.rng.float(0, 2 * Math.PI);
          var randomDistance = this.rng.float(this.dropInnerRadius, this.dropRadius);
          var offsetX = randomDistance * Math.cos(randomAngle);
          var offsetY = randomDistance * Math.sin(randomAngle);

          // 创建预制体实例
          var itemInstance = instantiate(selectedItem.prefab);

          // 设置预制体位置
          itemInstance.setWorldPosition(center.x + offsetX, center.y + offsetY, 0);

          // 将预制体添加到场景中（作为当前节点的子节点）
          var parent = (_selectedItem$contain = selectedItem.container) != null ? _selectedItem$contain : this.itemContainer;
          itemInstance.setParent(parent, true);
          return itemInstance;
        };
        return PrefabSpawner;
      }(Component), (_descriptor4$5 = _applyDecoratedDescriptor(_class5$1.prototype, "itemPool", [_dec8$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      }), _descriptor5$4 = _applyDecoratedDescriptor(_class5$1.prototype, "minDropCount", [_dec9$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor6$4 = _applyDecoratedDescriptor(_class5$1.prototype, "maxDropCount", [_dec10$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor7$4 = _applyDecoratedDescriptor(_class5$1.prototype, "binomialProbability", [_dec11$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor8$4 = _applyDecoratedDescriptor(_class5$1.prototype, "dropRadius", [_dec12$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor9$3 = _applyDecoratedDescriptor(_class5$1.prototype, "dropInnerRadius", [_dec13$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 100;
        }
      }), _descriptor10$3 = _applyDecoratedDescriptor(_class5$1.prototype, "itemContainer", [_dec14$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class5$1)) || _class4$1) || _class4$1) || _class4$1);
      cclegacy._RF.pop();
      var _dec$j, _dec2$i, _dec3$i, _dec4$f, _dec5$b, _dec6$8, _dec7$5, _dec8$5, _dec9$5, _dec10$5, _dec11$5, _dec12$5, _dec13$4, _dec14$4, _dec15$3, _dec16$2, _dec17$2, _dec18$2, _dec19$2, _dec20$2, _dec21$2, _dec22$2, _dec23$2, _dec24$2, _dec25$2, _dec26$2, _dec27$2, _dec28$2, _dec29$2, _dec30$2, _dec31$2, _dec32$2, _dec33$2, _dec34$2, _dec35$2, _dec36$2, _dec37$2, _dec38$2, _dec39$1, _dec40$1, _dec41$1, _dec42$1, _class$j, _class2$9, _descriptor$9, _descriptor2$9, _descriptor3$8, _descriptor4$6, _descriptor5$5, _descriptor6$5, _descriptor7$5, _descriptor8$5, _descriptor9$4, _descriptor10$4, _descriptor11$3, _descriptor12$3, _descriptor13$2, _descriptor14$2, _descriptor15$2, _descriptor16$2, _descriptor17$2, _descriptor18$2, _descriptor19$2, _descriptor20$2, _descriptor21$2, _descriptor22$1, _descriptor23$1, _descriptor24$1, _descriptor25$1, _descriptor26$1, _descriptor27$1, _descriptor28$1, _descriptor29$1, _descriptor30$1, _descriptor31$1, _descriptor32$1, _descriptor33$1, _descriptor34$1, _descriptor35$1, _descriptor36$1, _descriptor37$1, _descriptor38$1;
      cclegacy._RF.push({}, "26362XaRTJJYJHb6z+EMkT8", "GameVar", undefined);
      var ccclass$j = _decorator.ccclass,
        property$a = _decorator.property,
        menu$h = _decorator.menu;
      var GameVar = (_dec$j = ccclass$j('GameVar'), _dec2$i = menu$h('Game/GameVar'), _dec3$i = property$a(pOpt1(Prefab, '玩家', '预制体', '绑定')), _dec4$f = property$a(pOpt1(Node, '玩家', '玩家', '绑定')), _dec5$b = property$a(pOpt1(LineEventCmp, '玩家线事件', '玩家', '绑定')), _dec6$8 = property$a(pOpt1(Node, '子弹生成容器', '工具', '绑定')), _dec7$5 = property$a(pOpt1(Prefab, '锚点', '预制体', '绑定')), _dec8$5 = property$a(pOpt1(Node, '锚点生成容器', '工具', '绑定')), _dec9$5 = property$a(pOpt2('锚点生命周期', '锚点', '控制')), _dec10$5 = property$a(pOpt1(PrefabSpawner, '道具生成器', '工具', '绑定')), _dec11$5 = property$a(pOpt1(PrefabSpawner, '怪物预制体生成器', '工具', '绑定')), _dec12$5 = property$a(pOpt1(Prefab, '环形进度条', '预制体', '绑定')), _dec13$4 = property$a(pOpt1(Prefab, '扇形预制体', '扇形区域', '绑定')), _dec14$4 = property$a(pOpt1(Node, '扇形容器', '扇形区域', '绑定')), _dec15$3 = property$a(pOpt1(Node, 'Canvas', '工具', '绑定')), _dec16$2 = property$a(pOpt1(Node, '普通ui', '工具', '绑定')), _dec17$2 = property$a(pOpt2('是否在暂停中', '暂停', '状态')), _dec18$2 = property$a(pOpt1(Node, '暂停界面', '暂停', '绑定')), _dec19$2 = property$a(pOpt1(VirtualScrollView, '说明界面列表', '暂停', '绑定')), _dec20$2 = property$a(pOpt1(NotificationPanel, '侧边通知栏', '工具', '绑定')), _dec21$2 = property$a(pOpt1(NotificationPanel, '主通知栏', '工具', '绑定')), _dec22$2 = property$a(pOpt1(Node, '墙容器', '工具', '绑定')), _dec23$2 = property$a(_extends({}, pOpt2('UI玩家经验进度最大值', '角色面板', '控制'), {
        range: [0, 1, 0.01],
        slide: true
      })), _dec24$2 = property$a(pOpt1(Label, '攻击伤害数据条', '数据面板', '绑定')), _dec25$2 = property$a(pOpt1(Label, '恢复系数数据条', '数据面板', '绑定')), _dec26$2 = property$a(pOpt1(Label, '减伤系数数据条', '数据面板', '绑定')), _dec27$2 = property$a(pOpt1(Label, '冷却缩减数据条', '数据面板', '绑定')), _dec28$2 = property$a(pOpt1(Label, '移动速度数据条', '数据面板', '绑定')), _dec29$2 = property$a(pOpt1(Label, '旋转速度数据条', '数据面板', '绑定')), _dec30$2 = property$a(pOpt1(ProgressBar, 'UI玩家血量进度条', '角色面板', '绑定')), _dec31$2 = property$a(pOpt1(Label, 'UI玩家血量百分比数据条', '角色面板', '绑定')), _dec32$2 = property$a(pOpt1(CircularProgressBar, 'UI玩家经验进度条', '角色面板', '绑定')), _dec33$2 = property$a(pOpt1(Label, 'UI玩家等级数据条', '角色面板', '绑定')), _dec34$2 = property$a(pOpt1(Node, '怪物容器', '怪物', '绑定')), _dec35$2 = property$a(pOpt2('怪物波次', '怪物', '状态')), _dec36$2 = property$a(pOpt2('当前剩余怪物数量', '怪物', '状态')), _dec37$2 = property$a(pOpt2('总击杀怪物数量', '怪物', '状态')), _dec38$2 = property$a(pOpt2('怪物波次剩余数量', '怪物', '状态')), _dec39$1 = property$a(pOpt2('同时最大怪物数量', '怪物', '状态')), _dec40$1 = property$a(pOpt2('怪物初始生成数量', '怪物', '控制')), _dec41$1 = property$a(pOpt2('怪物波次间隔', '怪物', '控制')), _dec42$1 = property$a(pOpt2('怪物波次数量乘数', '怪物', '控制')), _dec$j(_class$j = _dec2$i(_class$j = (_class2$9 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(GameVar, _Component);
        function GameVar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "playerPrefab", _descriptor$9, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "player", _descriptor2$9, _assertThisInitialized(_this));
          _this.playerEvent = null;
          _this.gameEvent = null;
          _this.playerCollider = null;
          _this.playerState = null;
          _initializerDefineProperty(_this, "playerLineEvent", _descriptor3$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletContainer", _descriptor4$6, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorPrefab", _descriptor5$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorContainer", _descriptor6$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "anchorLifeTime", _descriptor7$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemSpawner", _descriptor8$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemySpawner", _descriptor9$4, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "circleProgressBarPrefab", _descriptor10$4, _assertThisInitialized(_this));
          // 扇形区域相关
          _initializerDefineProperty(_this, "sectorPrefab", _descriptor11$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "sectorContainer", _descriptor12$3, _assertThisInitialized(_this));
          // 主canvas
          _initializerDefineProperty(_this, "canvas", _descriptor13$2, _assertThisInitialized(_this));
          // 普通ui
          _initializerDefineProperty(_this, "uiCimmond", _descriptor14$2, _assertThisInitialized(_this));
          // 是否暂停
          _initializerDefineProperty(_this, "isPaused", _descriptor15$2, _assertThisInitialized(_this));
          // 暂停界面
          _initializerDefineProperty(_this, "pausePanel", _descriptor16$2, _assertThisInitialized(_this));
          // 说明界面列表组件
          _initializerDefineProperty(_this, "explainPanelList", _descriptor17$2, _assertThisInitialized(_this));
          // 通知栏
          _initializerDefineProperty(_this, "sideNotifPanel", _descriptor18$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "mainNotifPanel", _descriptor19$2, _assertThisInitialized(_this));
          // 墙
          _initializerDefineProperty(_this, "wallContainer", _descriptor20$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "UIplagerExpMaxValue", _descriptor21$2, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "attackDamageLabel", _descriptor22$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "healMultiplyLabel", _descriptor23$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "healReduceMultiplyLabel", _descriptor24$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "coolDownReduceLabel", _descriptor25$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "moveSpeedLabel", _descriptor26$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "rotateSpeedLabel", _descriptor27$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "UIplagerHealthProgressBar", _descriptor28$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "UIplagerHealthRatioLabel", _descriptor29$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "UIplagerExpProgressBar", _descriptor30$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "UIplagerLevelLabel", _descriptor31$1, _assertThisInitialized(_this));
          // 怪物相关
          _initializerDefineProperty(_this, "enemyContainer", _descriptor32$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemyWave", _descriptor33$1, _assertThisInitialized(_this));
          // 当前剩余怪物数量
          _this._enemyRemainCount = null;
          // 总击杀怪物数量
          _this._enemyTotalKillCount = null;
          _initializerDefineProperty(_this, "enemyWaveRemainCount", _descriptor34$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemyMaxOnWaveCount", _descriptor35$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemyInitCount", _descriptor36$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemyWaveInterval", _descriptor37$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "enemyWaveCountMultiply", _descriptor38$1, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = GameVar.prototype;
        _proto.onLoad = function onLoad() {
          // 初始化可监听变量
          this._enemyRemainCount = atom(0);
          this._enemyTotalKillCount = atom(0);

          // 初始化
          this.playerEvent = this.player.getComponent(PlayerEventCmp);
          this.gameEvent = this.getComponent(GameEventCmp);
          this.playerCollider = this.player.getComponent(ColliderAble);
          this.playerState = this.player.getComponent(PlayerState);
        };
        _proto.start = function start() {
          // 通知变量刷新
          this._enemyRemainCount.notify();
          this._enemyTotalKillCount.notify();
        };
        _createClass(GameVar, [{
          key: "enemyRemainCount",
          get: function get() {
            return this._enemyRemainCount.get();
          },
          set: function set(value) {
            this._enemyRemainCount.set(value);
          }
        }, {
          key: "enemyTotalKillCount",
          get: function get() {
            return this._enemyTotalKillCount.get();
          },
          set: function set(value) {
            this._enemyTotalKillCount.set(value);
          }
        }]);
        return GameVar;
      }(Component), (_descriptor$9 = _applyDecoratedDescriptor(_class2$9.prototype, "playerPrefab", [_dec3$i], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$9 = _applyDecoratedDescriptor(_class2$9.prototype, "player", [_dec4$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor3$8 = _applyDecoratedDescriptor(_class2$9.prototype, "playerLineEvent", [_dec5$b], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor4$6 = _applyDecoratedDescriptor(_class2$9.prototype, "bulletContainer", [_dec6$8], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor5$5 = _applyDecoratedDescriptor(_class2$9.prototype, "anchorPrefab", [_dec7$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor6$5 = _applyDecoratedDescriptor(_class2$9.prototype, "anchorContainer", [_dec8$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor7$5 = _applyDecoratedDescriptor(_class2$9.prototype, "anchorLifeTime", [_dec9$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor8$5 = _applyDecoratedDescriptor(_class2$9.prototype, "itemSpawner", [_dec10$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor9$4 = _applyDecoratedDescriptor(_class2$9.prototype, "enemySpawner", [_dec11$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor10$4 = _applyDecoratedDescriptor(_class2$9.prototype, "circleProgressBarPrefab", [_dec12$5], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor11$3 = _applyDecoratedDescriptor(_class2$9.prototype, "sectorPrefab", [_dec13$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor12$3 = _applyDecoratedDescriptor(_class2$9.prototype, "sectorContainer", [_dec14$4], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor13$2 = _applyDecoratedDescriptor(_class2$9.prototype, "canvas", [_dec15$3], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor14$2 = _applyDecoratedDescriptor(_class2$9.prototype, "uiCimmond", [_dec16$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor15$2 = _applyDecoratedDescriptor(_class2$9.prototype, "isPaused", [_dec17$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor16$2 = _applyDecoratedDescriptor(_class2$9.prototype, "pausePanel", [_dec18$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor17$2 = _applyDecoratedDescriptor(_class2$9.prototype, "explainPanelList", [_dec19$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor18$2 = _applyDecoratedDescriptor(_class2$9.prototype, "sideNotifPanel", [_dec20$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor19$2 = _applyDecoratedDescriptor(_class2$9.prototype, "mainNotifPanel", [_dec21$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor20$2 = _applyDecoratedDescriptor(_class2$9.prototype, "wallContainer", [_dec22$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor21$2 = _applyDecoratedDescriptor(_class2$9.prototype, "UIplagerExpMaxValue", [_dec23$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor22$1 = _applyDecoratedDescriptor(_class2$9.prototype, "attackDamageLabel", [_dec24$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor23$1 = _applyDecoratedDescriptor(_class2$9.prototype, "healMultiplyLabel", [_dec25$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor24$1 = _applyDecoratedDescriptor(_class2$9.prototype, "healReduceMultiplyLabel", [_dec26$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor25$1 = _applyDecoratedDescriptor(_class2$9.prototype, "coolDownReduceLabel", [_dec27$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor26$1 = _applyDecoratedDescriptor(_class2$9.prototype, "moveSpeedLabel", [_dec28$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor27$1 = _applyDecoratedDescriptor(_class2$9.prototype, "rotateSpeedLabel", [_dec29$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor28$1 = _applyDecoratedDescriptor(_class2$9.prototype, "UIplagerHealthProgressBar", [_dec30$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor29$1 = _applyDecoratedDescriptor(_class2$9.prototype, "UIplagerHealthRatioLabel", [_dec31$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor30$1 = _applyDecoratedDescriptor(_class2$9.prototype, "UIplagerExpProgressBar", [_dec32$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor31$1 = _applyDecoratedDescriptor(_class2$9.prototype, "UIplagerLevelLabel", [_dec33$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor32$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyContainer", [_dec34$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor33$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyWave", [_dec35$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _applyDecoratedDescriptor(_class2$9.prototype, "enemyRemainCount", [_dec36$2], Object.getOwnPropertyDescriptor(_class2$9.prototype, "enemyRemainCount"), _class2$9.prototype), _applyDecoratedDescriptor(_class2$9.prototype, "enemyTotalKillCount", [_dec37$2], Object.getOwnPropertyDescriptor(_class2$9.prototype, "enemyTotalKillCount"), _class2$9.prototype), _descriptor34$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyWaveRemainCount", [_dec38$2], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      }), _descriptor35$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyMaxOnWaveCount", [_dec39$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor36$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyInitCount", [_dec40$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor37$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyWaveInterval", [_dec41$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor38$1 = _applyDecoratedDescriptor(_class2$9.prototype, "enemyWaveCountMultiply", [_dec42$1], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      })), _class2$9)) || _class$j) || _class$j);

      // 创建全局访问器
      var gmVar = cache$1(function () {
        return find$1('GameManager').getComponent(GameVar);
      });
      cclegacy._RF.pop();
      var _dec$k, _dec2$j, _class$k, _class2$a, _descriptor$a, _descriptor2$a, _dec3$j, _dec4$g, _dec5$c, _dec6$9, _class4$2;
      cclegacy._RF.push({}, "4b1ffpyD+RBlqgJO50NKMrU", "LineDraw", undefined);
      var ccclass$k = _decorator.ccclass,
        menu$i = _decorator.menu,
        requireComponent$3 = _decorator.requireComponent,
        disallowMultiple$h = _decorator.disallowMultiple,
        property$b = _decorator.property;

      /**
       * 线条标签颜色配置
       */
      var LineTagColor = (_dec$k = ccclass$k('LineTagColor'), _dec2$j = property$b({
        type: SectorAreaTag
      }), _dec$k(_class$k = (_class2$a = function LineTagColor() {
        _initializerDefineProperty(this, "tag", _descriptor$a, this);
        _initializerDefineProperty(this, "color", _descriptor2$a, this);
      }, (_descriptor$a = _applyDecoratedDescriptor(_class2$a.prototype, "tag", [_dec2$j], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return SectorAreaTag.Freeze;
        }
      }), _descriptor2$a = _applyDecoratedDescriptor(_class2$a.prototype, "color", [property$b], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$a)) || _class$k);
      var LineDraw = (_dec3$j = ccclass$k('LineDraw'), _dec4$g = menu$i('Line/LineDraw'), _dec5$c = requireComponent$3(Graphics), _dec6$9 = disallowMultiple$h(true), _dec3$j(_class4$2 = _dec4$g(_class4$2 = _dec5$c(_class4$2 = _dec6$9(_class4$2 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(LineDraw, _Component);
        function LineDraw() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          /**
           * 绘制线条
           */
          _this.drawLine = function () {
            var _this$State$startNode, _this$State$endNode, _this$State$tagColors, _this$State$tagColors2;
            if (!((_this$State$startNode = _this.State.startNode) != null && _this$State$startNode.isValid) || !((_this$State$endNode = _this.State.endNode) != null && _this$State$endNode.isValid)) {
              return;
            }
            var startPoint = _this.State.startNode.worldPosition.toVec2();
            var endPoint = _this.State.endNode.worldPosition.toVec2();

            // 绘制线条，外蓝内白
            _this.State.graphics.moveTo(startPoint.x, startPoint.y);
            _this.State.graphics.lineTo(endPoint.x, endPoint.y);

            // 外侧 - 使用 tagColors 中的颜色，如果没有则使用默认颜色
            var outerColor = (_this$State$tagColors = (_this$State$tagColors2 = _this.State.tagColors.find(function (tagColor) {
              return tagColor.tag === _this.State.drawTag;
            })) == null ? void 0 : _this$State$tagColors2.color) != null ? _this$State$tagColors : _this.State.defaultOuterColor;
            _this.State.graphics.strokeColor = outerColor;
            _this.State.graphics.lineWidth = 4;
            _this.State.graphics.stroke();

            // 内侧 - 默认白色
            _this.State.graphics.strokeColor = Color.WHITE;
            _this.State.graphics.lineWidth = 2;
            _this.State.graphics.stroke();
          };
          return _this;
        }
        var _proto = LineDraw.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(LineState);
        };
        _proto.update = function update(_deltaTime) {
          // 清除之前的绘制内容
          this.State.graphics.clear();

          // 绘制线条
          if (this.State.canDraw) {
            this.drawLine();
          } else {
            // 推测Cocos Creator 的 渲染优化机制：
            // - 如果某帧只有 clear() 没有绘制命令，会标记为"空"
            // - 连续多帧"空"状态可能导致渲染管线优化掉本次渲染
            // - 着色器材质可能被禁用或重置
            // 解决方案：即使不绘制内容，也调用一次 stroke() 来保持渲染管线激活
            this.State.graphics.stroke();
          }
        };
        return LineDraw;
      }(Component)) || _class4$2) || _class4$2) || _class4$2) || _class4$2);
      cclegacy._RF.pop();
      var _dec$l, _dec2$k, _dec3$k, _dec4$h, _dec5$d, _dec6$a, _dec7$6, _dec8$6, _dec9$6, _dec10$6, _dec11$6, _class$l, _class2$b, _descriptor$b, _descriptor2$b, _descriptor3$9, _descriptor4$7, _descriptor5$6, _descriptor6$6, _descriptor7$6, _descriptor8$6;
      cclegacy._RF.push({}, "b9beeH/DSlKbboLy3gnAjMW", "LineState", undefined);
      var ccclass$l = _decorator.ccclass,
        menu$j = _decorator.menu,
        property$c = _decorator.property,
        disallowMultiple$i = _decorator.disallowMultiple;
      var LineState = (_dec$l = ccclass$l('LineState'), _dec2$k = menu$j('Line/LineState'), _dec3$k = disallowMultiple$i(true), _dec4$h = property$c({
        type: Node,
        tooltip: '起点'
      }), _dec5$d = property$c({
        type: Node,
        tooltip: '终点'
      }), _dec6$a = property$c({
        tooltip: '碰撞分组'
      }), _dec7$6 = property$c({
        type: SectorAreaTag,
        tooltip: '绘制标签'
      }), _dec8$6 = property$c({
        tooltip: '是否能绘制'
      }), _dec9$6 = property$c({
        type: Graphics,
        tooltip: 'Graphics组件'
      }), _dec10$6 = property$c({
        type: [LineTagColor],
        serializable: true
      }), _dec11$6 = property$c({
        tooltip: '默认外侧颜色',
        serializable: true
      }), _dec$l(_class$l = _dec2$k(_class$l = _dec3$k(_class$l = (_class2$b = /*#__PURE__*/function (_Component) {
        _inheritsLoose(LineState, _Component);
        function LineState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "startNode", _descriptor$b, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "endNode", _descriptor2$b, _assertThisInitialized(_this));
          /* -------------------- 碰撞 -------------------------- */
          _initializerDefineProperty(_this, "colliderGroup", _descriptor3$9, _assertThisInitialized(_this));
          /* -------------------- 绘制 -------------------------- */
          _initializerDefineProperty(_this, "drawTag", _descriptor4$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "canDraw", _descriptor5$6, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "graphics", _descriptor6$6, _assertThisInitialized(_this));
          /** 线条标签颜色列表 */
          _initializerDefineProperty(_this, "tagColors", _descriptor7$6, _assertThisInitialized(_this));
          /** 默认外侧颜色（如果 tagColors 为空） */
          _initializerDefineProperty(_this, "defaultOuterColor", _descriptor8$6, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = LineState.prototype;
        _proto.onLoad = function onLoad() {
          // 初始化节点坐标到世界原点
          this.node.setWorldPosition(Vec3.ZERO.clone());
        };
        return LineState;
      }(Component), (_descriptor$b = _applyDecoratedDescriptor(_class2$b.prototype, "startNode", [_dec4$h], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$b = _applyDecoratedDescriptor(_class2$b.prototype, "endNode", [_dec5$d], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor3$9 = _applyDecoratedDescriptor(_class2$b.prototype, "colliderGroup", [_dec6$a], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0xffffffff;
        }
      }), _descriptor4$7 = _applyDecoratedDescriptor(_class2$b.prototype, "drawTag", [_dec7$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return SectorAreaTag.Freeze;
        }
      }), _descriptor5$6 = _applyDecoratedDescriptor(_class2$b.prototype, "canDraw", [_dec8$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      }), _descriptor6$6 = _applyDecoratedDescriptor(_class2$b.prototype, "graphics", [_dec9$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor7$6 = _applyDecoratedDescriptor(_class2$b.prototype, "tagColors", [_dec10$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      }), _descriptor8$6 = _applyDecoratedDescriptor(_class2$b.prototype, "defaultOuterColor", [_dec11$6], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return Color.BLUE;
        }
      })), _class2$b)) || _class$l) || _class$l) || _class$l);
      cclegacy._RF.pop();
      var _dec$m, _dec2$l, _dec3$l, _class$m;
      cclegacy._RF.push({}, "c1733HBkzRDToV2X+Iv0uZJ", "PlayerHealth", undefined);
      var ccclass$m = _decorator.ccclass,
        menu$k = _decorator.menu,
        disallowMultiple$j = _decorator.disallowMultiple;
      var PlayerHealth = (_dec$m = ccclass$m('PlayerHealth'), _dec2$l = menu$k('Player/PlayerHealth'), _dec3$l = disallowMultiple$j(true), _dec$m(_class$m = _dec2$l(_class$m = _dec3$l(_class$m = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerHealth, _Component);
        function PlayerHealth() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          return _this;
        }
        var _proto = PlayerHealth.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(PlayerState);
        };
        _proto.onEnable = function onEnable() {
          this.State.event.on('damage.damage', this.handleDamage, this);
          this.State.event.on('damage.heal', this.handleHeal, this);
        };
        _proto.onDisable = function onDisable() {
          this.State.event.off('damage.damage', this.handleDamage, this);
          this.State.event.off('damage.heal', this.handleHeal, this);
        }

        // 响应伤害
        ;

        _proto.handleDamage = function handleDamage(damage) {
          var nowDamage = -this.State.defenseAdd + damage * (1 - this.State.defenseMultiply);
          this.State.health -= nowDamage;
        }
        // 响应治疗
        ;

        _proto.handleHeal = function handleHeal(heal) {
          var nowHeal = this.State.recoveryAdd + heal * this.State.recoveryMultiply;
          this.State.health = Math.min(this.State.maxHealth, this.State.health + nowHeal);
        };
        return PlayerHealth;
      }(Component)) || _class$m) || _class$m) || _class$m);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "9236bcSGchPSaCy9ZprOWMV", "FunctionBuilder", undefined);

      // 包装器组合函数
      function wrapAll(wrappers, fn) {
        return wrappers.reduceRight(function (acc, wrapper) {
          return wrapper(acc);
        }, fn);
      }

      // 确保函数同一时间只执行一次 异步版本
      function withAsyncSingleRunner(fn) {
        var lock = false;
        return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
          var _args = arguments;
          return _regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                if (lock) {
                  _context.next = 9;
                  break;
                }
                lock = true;
                _context.prev = 2;
                _context.next = 5;
                return fn.apply(void 0, _args);
              case 5:
                return _context.abrupt("return", _context.sent);
              case 6:
                _context.prev = 6;
                lock = false;
                return _context.finish(6);
              case 9:
              case "end":
                return _context.stop();
            }
          }, _callee, null, [[2,, 6, 9]]);
        }));
      }

      // 检查条件是否满足
      function withChecker(checker) {
        return function (fn) {
          return function () {
            return checker.apply(void 0, arguments) ? fn.apply(void 0, arguments) : undefined;
          };
        };
      }
      cclegacy._RF.pop();
      var _dec$n, _dec2$m, _dec3$m, _class$n, _class2$c, _descriptor$c;
      cclegacy._RF.push({}, "7d4d1LornpFaZRaDL6ih6du", "MinimapItem", undefined);
      var ccclass$n = _decorator.ccclass,
        property$d = _decorator.property,
        menu$l = _decorator.menu;
      var MinimapUpdateType = /*#__PURE__*/function (MinimapUpdateType) {
        MinimapUpdateType["STATIC"] = "static";
        MinimapUpdateType["DYNAMIC"] = "dynamic";
        return MinimapUpdateType;
      }({});
      Enum(MinimapUpdateType);
      /**
       * 小地图项组件，表示小地图上的一个标记点
       */
      var MinimapItem = (_dec$n = ccclass$n('MinimapItem'), _dec2$m = menu$l('UI/MinimapItem'), _dec3$m = property$d(Sprite), _dec$n(_class$n = _dec2$m(_class$n = (_class2$c = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MinimapItem, _Component);
        function MinimapItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "iconSprite", _descriptor$c, _assertThisInitialized(_this));
          _this.targetNode = null;
          _this.updateType = MinimapUpdateType.STATIC;
          return _this;
        }
        var _proto = MinimapItem.prototype;
        _proto.onLoad = function onLoad() {
          this.iconSprite = this.node.getComponent(Sprite);
        }

        /**
         * 初始化小地图项
         */;
        _proto.init = function init(config) {
          var targetNode = config.targetNode,
            _config$updateType = config.updateType,
            updateType = _config$updateType === void 0 ? MinimapUpdateType.DYNAMIC : _config$updateType,
            iconSprite = config.iconSprite;
          this.targetNode = targetNode;
          this.updateType = updateType;
          if (this.iconSprite && iconSprite) {
            this.iconSprite.spriteFrame = iconSprite;
          } else if (!iconSprite && this.targetNode) {
            this.copyTargetTexture();
          }
          this.updateAll();
        }

        /**
         * 更新小地图项位置、缩放和旋转
         */;
        _proto.updateAll = function updateAll() {
          if (!this.targetNode || !this.targetNode.isValid) {
            minimap().unregister(this.node);
            return;
          }
          var minimapPos = minimap().worldToMinimap(this.targetNode.getWorldPosition());
          this.node.setPosition(minimapPos);
          this.node.setScale(minimap().iconScale, minimap().iconScale);
          this.node.setRotation(this.targetNode.getWorldRotation());
        }

        /**
         * 复制目标节点的纹理和尺寸
         */;
        _proto.copyTargetTexture = function copyTargetTexture() {
          if (!this.targetNode) return;
          var sprite = this.targetNode.getComponent(Sprite);
          if (sprite && sprite.spriteFrame) {
            if (this.iconSprite) {
              this.iconSprite.spriteFrame = sprite.spriteFrame;
            }
          }
          var targetUITransform = this.targetNode.getComponent(UITransform);
          var uiTransform = this.node.getComponent(UITransform);
          if (uiTransform && targetUITransform) {
            var size = targetUITransform.contentSize.clone();
            size.x *= minimap().scaleFactor;
            size.y *= minimap().scaleFactor;
            uiTransform.setContentSize(size);
          }
        };
        return MinimapItem;
      }(Component), _descriptor$c = _applyDecoratedDescriptor(_class2$c.prototype, "iconSprite", [_dec3$m], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _class2$c)) || _class$n) || _class$n);
      cclegacy._RF.pop();
      var _dec$o, _dec2$n, _dec3$n, _dec4$i, _dec5$e, _dec6$b, _dec7$7, _dec8$7, _dec9$7, _dec10$7, _class$o, _class2$d, _descriptor$d, _descriptor2$c, _descriptor3$a, _descriptor4$8, _descriptor5$7, _descriptor6$7, _descriptor7$7, _descriptor8$7, _class3$1;
      cclegacy._RF.push({}, "aaeaa9iiUVDo6ZC2cHcY63l", "Minimap", undefined);
      var ccclass$o = _decorator.ccclass,
        property$e = _decorator.property,
        menu$m = _decorator.menu;
      /**
       * 小地图管理器
       * 单例模式，提供全局访问的小地图注册和管理功能
       * 包含对象池管理小地图项，减少频繁创建销毁带来的性能开销
       */
      var Minimap = (_dec$o = ccclass$o('Minimap'), _dec2$n = menu$m('UI/Minimap'), _dec3$n = property$e(Camera), _dec4$i = property$e({
        type: Node,
        tooltip: '小地图容器节点'
      }), _dec5$e = property$e({
        tooltip: '世界空间可见区域尺寸'
      }), _dec6$b = property$e({
        tooltip: '缩放系数'
      }), _dec7$7 = property$e({
        tooltip: '图标缩放系数'
      }), _dec8$7 = property$e({
        tooltip: '动态更新间隔（秒）'
      }), _dec9$7 = property$e({
        tooltip: '对象池初始大小'
      }), _dec10$7 = property$e({
        type: Prefab,
        tooltip: '小地图图标预制体'
      }), _dec$o(_class$o = _dec2$n(_class$o = (_class2$d = (_class3$1 = /*#__PURE__*/function (_Component) {
        _inheritsLoose(Minimap, _Component);
        function Minimap() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.log = new LogBuilder();
          _initializerDefineProperty(_this, "mainCamera", _descriptor$d, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "content", _descriptor2$c, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "worldVisibleSpace", _descriptor3$a, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "scaleFactor", _descriptor4$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "iconScale", _descriptor5$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "updateInterval", _descriptor6$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "poolInitialSize", _descriptor7$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "itemPrefab", _descriptor8$7, _assertThisInitialized(_this));
          _this._activeItems = new Map();
          _this._itemPool = [];
          _this.lastPlayerPos = {
            x: 0,
            y: 0,
            z: 0
          };
          /**
           * 注册小地图项
           */
          _this.register = wrapAll([withChecker(function (config) {
            var flag = config.node && config.node.active && config.node.isValid;
            if (!flag) {
              _this.log.Method('register').warn('无效的节点，注册失败');
            }
            return flag;
          }), withChecker(function (config) {
            var flag = !_this._activeItems.has(config.node);
            if (!flag) {
              _this.log.Method('register').warn("\u8282\u70B9\uFF1A" + config.node.name + "\uFF0C\u5DF2\u7ECF\u6CE8\u518C\u8FC7");
            }
            return flag;
          })], function (config) {
            _this.log.Method('register');
            var node = config.node,
              updateType = config.updateType,
              iconSprite = config.iconSprite;
            var minimapItem = _this.acquireItem();
            if (!minimapItem) {
              _this.log.warn('对象池已满，无法创建新的项');
              return;
            }
            minimapItem.node.name = "MinimapItem_" + node.name;
            minimapItem.init({
              targetNode: node,
              updateType: updateType,
              iconSprite: iconSprite
            });
            _this._activeItems.set(node, minimapItem);
            minimapItem.updateAll();
            _this.log.log("\u6CE8\u518C\u6210\u529F\uFF1A" + node.name);
          });
          /**
           * 批量更新动态类型的小地图项
           */
          _this.updateDynamicItems = function () {
            _this._activeItems.forEach(function (item) {
              if (item.updateType === MinimapUpdateType.DYNAMIC) {
                item.updateAll();
              }
            });
          };
          return _this;
        }
        Minimap.getInstance = function getInstance() {
          return Minimap._instance;
        };
        var _proto = Minimap.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
          Minimap._instance = this;
          this.initMap();
          this.initObjectPool();
        };
        _proto.onEnable = function onEnable() {
          this.schedule(this.updateDynamicItems, this.updateInterval, macro.REPEAT_FOREVER);
        };
        _proto.onDisable = function onDisable() {
          this.unschedule(this.updateDynamicItems);
        };
        _proto.onDestroy = function onDestroy() {
          this._activeItems.clear();
          this._itemPool.forEach(function (item) {
            var _item$node;
            return item == null || (_item$node = item.node) == null || _item$node.destroy == null ? void 0 : _item$node.destroy();
          });
          this._itemPool.length = 0;
          Minimap._instance = null;
        };
        _proto.initMap = function initMap() {
          this.calculateScale();
        }

        /**
         * 计算世界坐标到小地图坐标的缩放比例
         */;
        _proto.calculateScale = function calculateScale() {
          var mapVisibleSpace = this.content.getComponent(UITransform).contentSize;
          var scaleX = mapVisibleSpace.x / this.worldVisibleSpace.x;
          var scaleY = mapVisibleSpace.y / this.worldVisibleSpace.y;
          this.scaleFactor = Math.min(scaleX, scaleY);
        }

        /**
         * 初始化对象池
         */;
        _proto.initObjectPool = function initObjectPool() {
          for (var i = 0; i < this.poolInitialSize; i++) {
            var item = this.createPooledItem();
            if (item) {
              this._itemPool.push(item);
            }
          }
        }

        /**
         * 创建对象池项
         */;
        _proto.createPooledItem = function createPooledItem() {
          var itemNode = instantiate(this.itemPrefab);
          itemNode.name = 'MinimapItem_Pooled';
          itemNode.active = false;
          this.content.addChild(itemNode);
          return itemNode.getComponent(MinimapItem);
        }

        /**
         * 从对象池获取项
         */;
        _proto.acquireItem = function acquireItem() {
          if (this._itemPool.length > 0) {
            var _item = this._itemPool.pop();
            _item.node.active = true;
            return _item;
          }
          var item = this.createPooledItem();
          if (item) {
            item.node.active = true;
          }
          return item;
        }

        /**
         * 将项归还到对象池
         */;
        _proto.releaseItem = function releaseItem(item) {
          item.node.active = false;
          item.node.setPosition(0, 0, 0);
          if (this._itemPool.length < 100) {
            this._itemPool.push(item);
          } else {
            item.node.destroy();
          }
        };
        /**
         * 将世界坐标映射到以玩家为中心的小地图坐标系
         */
        _proto.worldToMinimap = function worldToMinimap(worldPos) {
          var _player;
          var playerWorldPos;
          if (!((_player = gmVar().player) != null && _player.isValid)) {
            playerWorldPos = this.lastPlayerPos;
          } else {
            var pos = gmVar().player.worldPosition;
            playerWorldPos = {
              x: pos.x,
              y: pos.y,
              z: pos.z
            };
            this.lastPlayerPos = playerWorldPos;
          }
          var relativePos = {
            x: 0,
            y: 0,
            z: 0
          };
          Vec3.subtract(relativePos, worldPos, playerWorldPos);
          return new Vec3(relativePos.x * this.scaleFactor, relativePos.y * this.scaleFactor, relativePos.z);
        };
        /**
         * 注销小地图项
         */
        _proto.unregister = function unregister(node) {
          var minimapItem = this._activeItems.get(node);
          if (minimapItem) {
            this.releaseItem(minimapItem);
            this._activeItems.delete(node);
            this.log.log("\u6CE8\u9500\u6210\u529F\uFF1A" + node.name);
          }
        }

        /**
         * 更新指定小地图项（用于静态类型）
         */;
        _proto.updatePosition = function updatePosition(node) {
          var item = this._activeItems.get(node);
          if (item) {
            item.updateAll();
          }
        };
        /**
         * 获取指定节点的小地图项
         */
        _proto.getItem = function getItem(node) {
          return this._activeItems.get(node);
        }

        /**
         * 获取所有已注册的小地图项
         */;
        _proto.getAllItems = function getAllItems() {
          return Array.from(this._activeItems.values());
        }

        /**
         * 获取对象池大小
         */;
        _proto.getPoolSize = function getPoolSize() {
          return this._itemPool.length;
        }

        /**
         * 获取活跃项数量
         */;
        _proto.getActiveCount = function getActiveCount() {
          return this._activeItems.size;
        };
        return Minimap;
      }(Component), _class3$1._instance = null, _class3$1), (_descriptor$d = _applyDecoratedDescriptor(_class2$d.prototype, "mainCamera", [_dec3$n], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$c = _applyDecoratedDescriptor(_class2$d.prototype, "content", [_dec4$i], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor3$a = _applyDecoratedDescriptor(_class2$d.prototype, "worldVisibleSpace", [_dec5$e], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec2(400, 400);
        }
      }), _descriptor4$8 = _applyDecoratedDescriptor(_class2$d.prototype, "scaleFactor", [_dec6$b], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor5$7 = _applyDecoratedDescriptor(_class2$d.prototype, "iconScale", [_dec7$7], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1.0;
        }
      }), _descriptor6$7 = _applyDecoratedDescriptor(_class2$d.prototype, "updateInterval", [_dec8$7], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      }), _descriptor7$7 = _applyDecoratedDescriptor(_class2$d.prototype, "poolInitialSize", [_dec9$7], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 20;
        }
      }), _descriptor8$7 = _applyDecoratedDescriptor(_class2$d.prototype, "itemPrefab", [_dec10$7], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$d)) || _class$o) || _class$o);

      /**
       * 便捷访问函数
       */
      var minimap = Minimap.getInstance;
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "15aebkPupRKKrVN67FEGbqG", "richTextBuilder", undefined);

      // ==================== 散装函数（基础API）====================

      /**
       * 纯文本
       * @param content 文本内容
       * @returns 纯文本字符串
       *
       * @example text('获得金币')
       */
      function _text(content) {
        return content;
      }
      function _color(content, color) {
        if (color === void 0) {
          color = Color.RED.toHEX();
        }
        return "<color=" + color + ">" + content + "</color>";
      }
      function _img(src, options) {
        var imgTag = "<img src='" + src + "'";
        if ((options == null ? void 0 : options.width) !== undefined && (options == null ? void 0 : options.height) !== undefined) {
          imgTag += " width=" + options.width + " height=" + options.height;
        }
        if (options != null && options.align) {
          imgTag += " align=" + options.align;
        }
        imgTag += ' />';
        return imgTag;
      }
      function _bold(content) {
        return "<b>" + content + "</b>";
      }
      function _italic(content) {
        return "<i>" + content + "</i>";
      }
      function _underline(content) {
        return "<u>" + content + "</u>";
      }
      function _size(content, size) {
        if (size === void 0) {
          size = 30;
        }
        return "<size=" + size + ">" + content + "</size>";
      }
      function _outline(content, color, width) {
        if (color === void 0) {
          color = Color.BLACK.toHEX();
        }
        if (width === void 0) {
          width = 2;
        }
        return "<outline color=" + color + " width=" + width + ">" + content + "</outline>";
      }
      function _br(n) {
        if (n === void 0) {
          n = 1;
        }
        return '<br/>'.repeat(n);
      }
      function _space(count) {
        if (count === void 0) {
          count = 1;
        }
        return ' '.repeat(count);
      }
      function _imgSize(src, width, height, align) {
        return _img(src, {
          width: width,
          height: height,
          align: align
        });
      }

      // ==================== 构建器（可选，基于函数式）====================

      /**
       * 文本构建器（基于散装函数的链式API）
       * 如果不喜欢链式调用，可以直接使用上面的散装函数
       */
      var richTextBuilder = /*#__PURE__*/function () {
        function richTextBuilder(str) {
          if (str === void 0) {
            str = '';
          }
          this.parts = [];
          // 默认添加一个空字符串，用于处理链式调用
          this.parts.push(str);
        }

        /**
         * 添加纯文本
         * @param content 文本内容
         */
        var _proto = richTextBuilder.prototype;
        _proto.text = function text(content) {
          // 处理并放回
          this.parts.push(_text(content));
          return this;
        }

        /**
         * 添加颜色文本
         * @param color 颜色值
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.color = function color(colorV, content) {
          var _ref;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref = content != null ? content : this.parts.pop()) != null ? _ref : '';
          colorV = typeof colorV === 'string' ? colorV : colorV.toHEX();
          // 处理并放回
          this.parts.push(_color(targetText, colorV));
          return this;
        }

        /**
         * 添加图片
         * @param src 图片在图集中的名称
         * @param options 可选配置：width, height, align
         */;
        _proto.img = function img(src, options) {
          this.parts.push(_img(src, options));
          return this;
        }

        /**
         * 添加带大小的图片
         * @param src 图片名称
         * @param width 宽度
         * @param height 高度
         * @param align 对齐方式（可选）
         */;
        _proto.imgSize = function imgSize(src, width, height, align) {
          this.parts.push(_imgSize(src, width, height, align));
          return this;
        }

        /**
         * 添加加粗文本
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.bold = function bold(content) {
          var _ref2;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref2 = content != null ? content : this.parts.pop()) != null ? _ref2 : '';
          // 处理并放回
          this.parts.push(_bold(targetText));
          return this;
        }

        /**
         * 添加斜体文本
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.italic = function italic(content) {
          var _ref3;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref3 = content != null ? content : this.parts.pop()) != null ? _ref3 : '';
          // 处理并放回
          this.parts.push(_italic(targetText));
          return this;
        }

        /**
         * 添加下划线文本
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.underline = function underline(content) {
          var _ref4;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref4 = content != null ? content : this.parts.pop()) != null ? _ref4 : '';
          // 处理并放回
          this.parts.push(_underline(targetText));
          return this;
        }

        /**
         * 添加字体大小文本
         * @param size 字体大小
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.size = function size(sizeV, content) {
          var _ref5;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref5 = content != null ? content : this.parts.pop()) != null ? _ref5 : '';
          // 处理并放回
          this.parts.push(_size(targetText, sizeV));
          return this;
        }

        /**
         * 添加描边文本
         * @param color 描边颜色
         * @param width 描边宽度
         * @param content 文本内容，可选。不提供时则操作最后一个文本部分
         */;
        _proto.outline = function outline(color, width, content) {
          var _ref6;
          // 有文本参数就使用它，没有就取出最后一个文本部分
          var targetText = (_ref6 = content != null ? content : this.parts.pop()) != null ? _ref6 : '';
          color = typeof color === 'string' ? color : color.toHEX();
          // 处理并放回
          this.parts.push(_outline(targetText, color, width));
          return this;
        }

        /**
         * 添加换行
         */;
        _proto.br = function br(n) {
          if (n === void 0) {
            n = 1;
          }
          this.parts.push(_br(n));
          return this;
        }

        /**
         * 添加空格
         */;
        _proto.space = function space(count) {
          if (count === void 0) {
            count = 1;
          }
          this.parts.push(_space(count));
          return this;
        }

        /**
         * 追加文本（text的别名）
         * @param content 文本内容
         */;
        _proto.append = function append(content) {
          return this.text(content);
        }

        /**
         * 合并所有文本部分为一段
         */;
        _proto.merge = function merge() {
          if (this.parts.length > 0) {
            var merged = this.parts.join('');
            this.parts = [merged];
          }
          return this;
        }

        /**
         * 清空当前构建的内容
         */;
        _proto.clear = function clear() {
          this.parts = [];
          return this;
        }

        /**
         * 构建最终字符串
         */;
        _proto.build = function build(separator) {
          if (separator === void 0) {
            separator = '';
          }
          return this.parts.join(separator);
        }

        /**
         * 转换为字符串
         */;
        _proto.toString = function toString() {
          return this.build();
        };
        return richTextBuilder;
      }();

      /**
       * 快捷创建构建器（如果需要链式调用）
       */
      function richText(str) {
        return new richTextBuilder(str);
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "6af8e6Wzt1BVLr1n9mJGCrQ", "TweenHack", undefined);

      /**
       * HackTween - tween 批量管理工具
       *
       * 核心功能：
       * 1. 使用 hackTween 创建 tween 时自动记录
       * 2. 提供批量暂停所有 hacktween 的函数
       * 3. 提供批量恢复所有 hacktween 的函数
       */
      var HackTween = /*#__PURE__*/function () {
        function HackTween() {
          // 记录所有通过 HackTween 创建的 tween
          this.tweenRecords = new Set();
        }

        /**
         * 获取单例
         */
        HackTween.getInstance = function getInstance() {
          if (!HackTween.instance) {
            HackTween.instance = new HackTween();
          }
          return HackTween.instance;
        }

        /**
         * 创建一个被管理的 tween
         * @param target 缓动目标
         * @param option 缓动选项
         * @returns tween 对象
         */;
        HackTween.tween = function tween(target) {
          var instance = HackTween.getInstance();
          return instance.createTween(target);
        }

        /**
         * 创建 tween 并记录
         */;
        var _proto = HackTween.prototype;
        _proto.createTween = function createTween(target) {
          var _this = this;
          // 创建原始 tween
          var tween = new Tween(target);

          // 记录 tween
          this.tweenRecords.add(tween);

          // 劫持 stop 方法，清理记录
          var originalStop = tween.stop.bind(tween);
          tween.stop = function () {
            _this.tweenRecords.delete(tween);
            return originalStop();
          };

          // 标记为 hack tween
          tween.__hackTween = true;
          return tween;
        }

        /**
         * 暂停所有 hacktween
         */;
        HackTween.pauseAll = function pauseAll() {
          var instance = HackTween.getInstance();
          instance.pauseAllTweens();
        }

        /**
         * 暂停所有 tween（内部方法）
         */;
        _proto.pauseAllTweens = function pauseAllTweens() {
          this.tweenRecords.forEach(function (tween) {
            tween.pause();
          });
        }

        /**
         * 恢复所有 hacktween
         */;
        HackTween.resumeAll = function resumeAll() {
          var instance = HackTween.getInstance();
          instance.resumeAllTweens();
        }

        /**
         * 恢复所有 tween（内部方法）
         */;
        _proto.resumeAllTweens = function resumeAllTweens() {
          this.tweenRecords.forEach(function (tween) {
            tween.resume();
          });
        }

        /**
         * 清理所有已完成的 tween 记录
         */;
        HackTween.cleanup = function cleanup() {
          var instance = HackTween.getInstance();
          // 已完成的 tween 在 stop 时会被清理，这里只需清空整个集合
          instance.tweenRecords.clear();
        }

        /**
         * 获取所有记录的 tween 数量
         */;
        HackTween.getActiveCount = function getActiveCount() {
          return HackTween.getInstance().tweenRecords.size;
        }

        /**
         * 销毁单例（用于测试或重置）
         */;
        HackTween.destroy = function destroy() {
          var instance = HackTween.instance;
          if (instance) {
            instance.tweenRecords.clear();
            HackTween.instance = null;
          }
        };
        return HackTween;
      }();

      /**
       * 便捷函数：创建被管理的 tween
       * @param target 缓动目标
       * @param option 缓动选项
       * @returns tween 对象
       */
      HackTween.instance = null;
      function hackTween(target) {
        return HackTween.tween(target);
      }

      /**
       * 便捷函数：暂停所有 hacktween
       */
      function pauseAllHackTweens() {
        HackTween.pauseAll();
      }

      /**
       * 便捷函数：恢复所有 hacktween
       */
      function resumeAllHackTweens() {
        HackTween.resumeAll();
      }
      cclegacy._RF.pop();
      var _dec$p, _dec2$o, _dec3$o, _dec4$j, _dec5$f, _dec6$c, _dec7$8, _dec8$8, _dec9$8, _dec10$8, _dec11$7, _dec12$6, _dec13$5, _dec14$5, _dec15$4, _class$p, _class2$e, _descriptor$e, _descriptor2$d, _descriptor3$b, _descriptor4$9, _descriptor5$8, _descriptor6$8, _descriptor7$8, _descriptor8$8, _descriptor9$5, _descriptor10$5, _descriptor11$4;
      cclegacy._RF.push({}, "a9426N5AwdD0o5Gy71Wvnr7", "AnchorCountdown", undefined);
      var ccclass$p = _decorator.ccclass,
        menu$n = _decorator.menu,
        disallowMultiple$k = _decorator.disallowMultiple,
        property$f = _decorator.property,
        executeInEditMode$1 = _decorator.executeInEditMode;

      /**
       * 锚点倒计时组件
       * 可附加到锚点节点上，提供倒计时功能
       */
      var AnchorCountdown = (_dec$p = ccclass$p('AnchorCountdown'), _dec2$o = menu$n('Utils/AnchorCountdown'), _dec3$o = disallowMultiple$k(true), _dec4$j = executeInEditMode$1(true), _dec5$f = property$f({
        displayName: 'Duration',
        tooltip: '倒计时时长(秒)',
        min: 0.1,
        step: 0.1,
        visible: true
      }), _dec6$c = property$f({
        displayName: 'Auto Start',
        tooltip: '是否自动开始倒计时',
        visible: true
      }), _dec7$8 = property$f({
        displayName: 'Auto Destroy',
        tooltip: '倒计时结束后是否自动摧毁节点',
        visible: true
      }), _dec8$8 = property$f({
        displayName: 'Start Color',
        tooltip: '倒计时开始时的颜色',
        visible: true
      }), _dec9$8 = property$f({
        displayName: 'End Color',
        tooltip: '倒计时结束时的颜色',
        visible: true
      }), _dec10$8 = property$f({
        displayName: 'Inner Radius',
        tooltip: '进度条内半径',
        range: [0, 1, 0.01],
        slide: true,
        visible: true
      }), _dec11$7 = property$f({
        displayName: 'Outer Radius',
        tooltip: '进度条外半径',
        range: [0, 1, 0.01],
        slide: true,
        visible: true
      }), _dec12$6 = property$f({
        displayName: 'Start Angle',
        tooltip: '进度条起始角度',
        range: [0, 360, 1],
        slide: true,
        visible: true
      }), _dec13$5 = property$f({
        displayName: 'Smoothness',
        tooltip: '进度条平滑度',
        range: [0, 0.4, 0.001],
        slide: true,
        visible: true
      }), _dec14$5 = property$f({
        displayName: 'Reverse',
        tooltip: '进度条是否反向',
        visible: true
      }), _dec15$4 = property$f({
        displayName: 'Progress Bar Offset',
        tooltip: '进度条位置偏移',
        visible: true
      }), _dec$p(_class$p = _dec2$o(_class$p = _dec3$o(_class$p = _dec4$j(_class$p = (_class2$e = /*#__PURE__*/function (_Component) {
        _inheritsLoose(AnchorCountdown, _Component);
        function AnchorCountdown() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          // === 私有变量 ===
          _initializerDefineProperty(_this, "_duration", _descriptor$e, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_autoStart", _descriptor2$d, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_autoDestroy", _descriptor3$b, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_startColor", _descriptor4$9, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_endColor", _descriptor5$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_innerRadius", _descriptor6$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_outerRadius", _descriptor7$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_startAngle", _descriptor8$8, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_smoothness", _descriptor9$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_reverse", _descriptor10$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "_progressBarOffset", _descriptor11$4, _assertThisInitialized(_this));
          // 私有变量
          _this._progressBar = null;
          _this._isRunning = false;
          _this._currentTween = null;
          _this._completeCallbacks = [];
          return _this;
        }
        var _proto = AnchorCountdown.prototype;
        _proto.onLoad = function onLoad() {
          // 从子节点查找进度条组件
          this.findProgressBarFromChildren();
          if (this._autoStart) {
            this.startCountdown();
          }
        };
        _proto.onEnable = function onEnable() {
          if (!this._progressBar) {
            this.findProgressBarFromChildren();
          }
        };
        _proto.onDisable = function onDisable() {
          this.stopCountdown();
        };
        _proto.onDestroy = function onDestroy() {
          this.stopCountdown();
        }

        /**
         * 从子节点查找进度条组件
         */;
        _proto.findProgressBarFromChildren = function findProgressBarFromChildren() {
          this._progressBar = this.node.getComponentInChildren(CircularProgressBar);
          if (this._progressBar) {
            // 设置进度条位置偏移
            var progressBarNode = this._progressBar.node;
            progressBarNode.setPosition(this._progressBarOffset);
          }
        }

        /**
         * 开始倒计时
         */;
        _proto.startCountdown = function startCountdown() {
          var _this2 = this;
          if (this._isRunning) {
            this.stopCountdown();
          }

          // 初始化进度条状态
          if (this._progressBar) {
            this._progressBar.progress = 1;
            this._progressBar.ringColor = this._startColor;
            this._progressBar.innerRadius = this._innerRadius;
            this._progressBar.outerRadius = this._outerRadius;
            this._progressBar.startAngle = this._startAngle;
            this._progressBar.smoothness = this._smoothness;
            this._progressBar.reverse = this._reverse;

            // 创建倒计时动画
            this._currentTween = hackTween(this._progressBar).to(this._duration, {
              progress: 0,
              ringColor: this._endColor
            }).call(function () {
              _this2.onCountdownComplete();
            }).start();
            this._isRunning = true;
          }
        }

        /**
         * 停止倒计时
         */;
        _proto.stopCountdown = function stopCountdown() {
          if (this._currentTween) {
            this._currentTween.stop();
            this._currentTween = null;
          }
          this._isRunning = false;
        }

        /**
         * 重置倒计时
         */;
        _proto.resetCountdown = function resetCountdown() {
          this.stopCountdown();
          if (this._progressBar) {
            this._progressBar.progress = 1;
            this._progressBar.ringColor = this._startColor;
          }
        }

        /**
         * 暂停倒计时
         */;
        _proto.pauseCountdown = function pauseCountdown() {
          if (this._currentTween && this._isRunning) {
            this._currentTween.pause();
          }
        }

        /**
         * 恢复倒计时
         */;
        _proto.resumeCountdown = function resumeCountdown() {
          if (this._currentTween && this._isRunning) {
            this._currentTween.resume();
          }
        }

        /**
         * 获取剩余时间（秒）
         */;
        _proto.getRemainingTime = function getRemainingTime() {
          if (!this._progressBar || !this._isRunning) {
            return 0;
          }
          return this._progressBar.progress * this._duration;
        }

        /**
         * 获取倒计时进度 (0-1)
         */;
        _proto.getProgress = function getProgress() {
          return this._progressBar ? this._progressBar.progress : 0;
        }

        /**
         * 注册倒计时完成回调
         */;
        _proto.onComplete = function onComplete(callback) {
          if (callback && typeof callback === 'function') {
            this._completeCallbacks.push(callback);
          }
        }

        /**
         * 移除倒计时完成回调
         */;
        _proto.removeCompleteCallback = function removeCompleteCallback(callback) {
          var index = this._completeCallbacks.indexOf(callback);
          if (index !== -1) {
            this._completeCallbacks.splice(index, 1);
          }
        }

        /**
         * 倒计时完成回调
         */;
        _proto.onCountdownComplete = function onCountdownComplete() {
          var _this3 = this;
          this._isRunning = false;

          // 执行所有注册的回调
          for (var _iterator = _createForOfIteratorHelperLoose(this._completeCallbacks), _step; !(_step = _iterator()).done;) {
            var callback = _step.value;
            try {
              callback(this.node);
            } catch (e) {
              console.error('执行倒计时完成回调时出错:', e);
            }
          }

          // 如果设置了自动销毁，则销毁节点
          if (this._autoDestroy) {
            this.scheduleOnce(function () {
              var _gmVar;
              (_gmVar = gmVar()) == null || (_gmVar = _gmVar.gameEvent) == null || _gmVar.emit('gm.anchor.destroy', _this3.node);
            }, 0.1);
          }
        }

        // === Getters and Setters ===
        ;

        _createClass(AnchorCountdown, [{
          key: "duration",
          get: function get() {
            return this._duration;
          },
          set: function set(value) {
            this._duration = value;
          }
        }, {
          key: "autoStart",
          get: function get() {
            return this._autoStart;
          },
          set: function set(value) {
            this._autoStart = value;
          }
        }, {
          key: "autoDestroy",
          get: function get() {
            return this._autoDestroy;
          },
          set: function set(value) {
            this._autoDestroy = value;
          }
        }, {
          key: "startColor",
          get: function get() {
            return this._startColor;
          },
          set: function set(value) {
            this._startColor = value;
          }
        }, {
          key: "endColor",
          get: function get() {
            return this._endColor;
          },
          set: function set(value) {
            this._endColor = value;
          }
        }, {
          key: "innerRadius",
          get: function get() {
            return this._innerRadius;
          },
          set: function set(value) {
            this._innerRadius = value;
            if (this._progressBar) {
              this._progressBar.innerRadius = value;
            }
          }
        }, {
          key: "outerRadius",
          get: function get() {
            return this._outerRadius;
          },
          set: function set(value) {
            this._outerRadius = value;
            if (this._progressBar) {
              this._progressBar.outerRadius = value;
            }
          }
        }, {
          key: "startAngle",
          get: function get() {
            return this._startAngle;
          },
          set: function set(value) {
            this._startAngle = value;
            if (this._progressBar) {
              this._progressBar.startAngle = value;
            }
          }
        }, {
          key: "smoothness",
          get: function get() {
            return this._smoothness;
          },
          set: function set(value) {
            this._smoothness = value;
            if (this._progressBar) {
              this._progressBar.smoothness = value;
            }
          }
        }, {
          key: "reverse",
          get: function get() {
            return this._reverse;
          },
          set: function set(value) {
            this._reverse = value;
            if (this._progressBar) {
              this._progressBar.reverse = value;
            }
          }
        }, {
          key: "progressBarOffset",
          get: function get() {
            return this._progressBarOffset;
          },
          set: function set(value) {
            this._progressBarOffset = value;
            if (this._progressBar) {
              this._progressBar.node.setPosition(value);
            }
          }
        }]);
        return AnchorCountdown;
      }(Component), (_descriptor$e = _applyDecoratedDescriptor(_class2$e.prototype, "_duration", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 5;
        }
      }), _descriptor2$d = _applyDecoratedDescriptor(_class2$e.prototype, "_autoStart", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      }), _descriptor3$b = _applyDecoratedDescriptor(_class2$e.prototype, "_autoDestroy", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      }), _descriptor4$9 = _applyDecoratedDescriptor(_class2$e.prototype, "_startColor", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Color(0, 255, 0, 255);
        }
      }), _descriptor5$8 = _applyDecoratedDescriptor(_class2$e.prototype, "_endColor", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Color(255, 0, 0, 255);
        }
      }), _descriptor6$8 = _applyDecoratedDescriptor(_class2$e.prototype, "_innerRadius", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.3;
        }
      }), _descriptor7$8 = _applyDecoratedDescriptor(_class2$e.prototype, "_outerRadius", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.45;
        }
      }), _descriptor8$8 = _applyDecoratedDescriptor(_class2$e.prototype, "_startAngle", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return -90;
        }
      }), _descriptor9$5 = _applyDecoratedDescriptor(_class2$e.prototype, "_smoothness", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.02;
        }
      }), _descriptor10$5 = _applyDecoratedDescriptor(_class2$e.prototype, "_reverse", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor11$4 = _applyDecoratedDescriptor(_class2$e.prototype, "_progressBarOffset", [property$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec3(0, 0, 0);
        }
      }), _applyDecoratedDescriptor(_class2$e.prototype, "duration", [_dec5$f], Object.getOwnPropertyDescriptor(_class2$e.prototype, "duration"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "autoStart", [_dec6$c], Object.getOwnPropertyDescriptor(_class2$e.prototype, "autoStart"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "autoDestroy", [_dec7$8], Object.getOwnPropertyDescriptor(_class2$e.prototype, "autoDestroy"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "startColor", [_dec8$8], Object.getOwnPropertyDescriptor(_class2$e.prototype, "startColor"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "endColor", [_dec9$8], Object.getOwnPropertyDescriptor(_class2$e.prototype, "endColor"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "innerRadius", [_dec10$8], Object.getOwnPropertyDescriptor(_class2$e.prototype, "innerRadius"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "outerRadius", [_dec11$7], Object.getOwnPropertyDescriptor(_class2$e.prototype, "outerRadius"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "startAngle", [_dec12$6], Object.getOwnPropertyDescriptor(_class2$e.prototype, "startAngle"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "smoothness", [_dec13$5], Object.getOwnPropertyDescriptor(_class2$e.prototype, "smoothness"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "reverse", [_dec14$5], Object.getOwnPropertyDescriptor(_class2$e.prototype, "reverse"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "progressBarOffset", [_dec15$4], Object.getOwnPropertyDescriptor(_class2$e.prototype, "progressBarOffset"), _class2$e.prototype)), _class2$e)) || _class$p) || _class$p) || _class$p) || _class$p);
      cclegacy._RF.pop();
      var _dec$q, _dec2$p, _dec3$p, _dec4$k, _dec5$g, _dec6$d, _class$q, _class2$f, _descriptor$f, _descriptor2$e, _descriptor3$c;
      cclegacy._RF.push({}, "294fdDBSKREa4VbkB5Gqrm0", "CameraFollow", undefined);
      var ccclass$q = _decorator.ccclass,
        property$g = _decorator.property,
        menu$o = _decorator.menu,
        disallowMultiple$l = _decorator.disallowMultiple;
      var CameraFollow = (_dec$q = ccclass$q('CameraFollow'), _dec2$p = menu$o('Utils/CameraFollow'), _dec3$p = disallowMultiple$l(true), _dec4$k = property$g({
        type: Node,
        tooltip: '要跟随的目标'
      }), _dec5$g = property$g({
        tooltip: '跟随偏移量'
      }), _dec6$d = property$g({
        tooltip: '跟随平滑时间（秒），越小跟随越快'
      }), _dec$q(_class$q = _dec2$p(_class$q = _dec3$p(_class$q = (_class2$f = /*#__PURE__*/function (_Component) {
        _inheritsLoose(CameraFollow, _Component);
        function CameraFollow() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "target", _descriptor$f, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "offset", _descriptor2$e, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "smoothTime", _descriptor3$c, _assertThisInitialized(_this));
          // 旋转时跟随目标为旋转中心
          _this.handleRotate = function () {
            var _playerState$nowAncho;
            // 无锚点时不跟随
            if (!((_playerState$nowAncho = gmVar().playerState.nowAnchor) != null && _playerState$nowAncho.isValid)) {
              return;
            }
            _this.target = gmVar().playerState.rotateCenter;
            gmVar().playerEvent.once('rotate.stop', function () {
              _this.target = gmVar().player;
            });
          };
          return _this;
        }
        var _proto = CameraFollow.prototype;
        _proto.onEnable = function onEnable() {
          gmVar().playerEvent.on('rotate.left', this.handleRotate);
          gmVar().playerEvent.on('rotate.right', this.handleRotate);
        };
        _proto.onDisable = function onDisable() {
          gmVar().playerEvent.off('rotate.left', this.handleRotate);
          gmVar().playerEvent.off('rotate.right', this.handleRotate);
        };
        _proto.update = function update(deltaTime) {
          var _this$target;
          if (!((_this$target = this.target) != null && _this$target.isValid)) {
            return;
          }

          // 目标位置
          var targetPos = new Vec3(this.target.worldPosition.x + this.offset.x, this.target.worldPosition.y + this.offset.y, this.node.worldPosition.z + this.offset.z);

          // 插值跟随，使用指数平滑
          var t = 1 - Math.exp(-deltaTime / Math.max(this.smoothTime, 0.001));
          var currentPos = this.node.worldPosition.clone();
          var newPos = new Vec3();
          Vec3.lerp(newPos, currentPos, targetPos, t);
          this.node.setWorldPosition(newPos);
        };
        return CameraFollow;
      }(Component), (_descriptor$f = _applyDecoratedDescriptor(_class2$f.prototype, "target", [_dec4$k], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$e = _applyDecoratedDescriptor(_class2$f.prototype, "offset", [_dec5$g], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec3(0, 0, 0);
        }
      }), _descriptor3$c = _applyDecoratedDescriptor(_class2$f.prototype, "smoothTime", [_dec6$d], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      })), _class2$f)) || _class$q) || _class$q) || _class$q);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "af4fbwi8s5IVLwpWni8MZq7", "EnemySpawner", undefined);

      /**
       * 怪物生成配置选项
       */

      /**
       * 批量生成怪物
       * @param component 用于调度的组件实例
       * @param totalSpawnCount 需要生成的怪物总数
       * @param options 可选配置
       * @returns Promise，所有怪物生成完成后解决
       */
      function spawnEnemies(_x, _x2) {
        return _spawnEnemies.apply(this, arguments);
      }
      function _spawnEnemies() {
        _spawnEnemies = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(totalSpawnCount, options) {
          var _options, _options$spawnInterva, spawnInterval, _options$getSpawnPosi, getSpawnPosition, remainingSpawnCount;
          return _regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                if (options === void 0) {
                  options = {};
                }
                _options = options, _options$spawnInterva = _options.spawnInterval, spawnInterval = _options$spawnInterva === void 0 ? 0.5 : _options$spawnInterva, _options$getSpawnPosi = _options.getSpawnPosition, getSpawnPosition = _options$getSpawnPosi === void 0 ? function () {
                  return new Vec2(0, 0);
                } : _options$getSpawnPosi;
                remainingSpawnCount = totalSpawnCount;
                _context.next = 5;
                return _pollUntil(function () {
                  // 尝试生成怪物
                  var currentEnemyCount = sumBy(gmVar().enemyContainer.children, function (child) {
                    return child.children.length;
                  });
                  var maxSpawn = Math.max(gmVar().enemyMaxOnWaveCount - currentEnemyCount, 0);
                  var toSpawn = Math.min(remainingSpawnCount, maxSpawn);
                  gmVar().enemySpawner.spawnPrefab(getSpawnPosition(), toSpawn, toSpawn);
                  remainingSpawnCount -= toSpawn;

                  // 返回是否全部生成完毕
                  return remainingSpawnCount <= 0;
                }, gmVar(), {
                  interval: spawnInterval,
                  maxRetries: Infinity
                });
              case 5:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        return _spawnEnemies.apply(this, arguments);
      }
      cclegacy._RF.pop();
      var _dec$r, _dec2$q, _dec3$q, _dec4$l, _dec5$h, _class$r;
      cclegacy._RF.push({}, "164814X3Y1DaoCcuCfjraEL", "GameControl", undefined);
      var ccclass$r = _decorator.ccclass,
        menu$p = _decorator.menu,
        requireComponent$4 = _decorator.requireComponent,
        disallowMultiple$m = _decorator.disallowMultiple,
        executionOrder$7 = _decorator.executionOrder;

      // import { logger,LogLevels } from 'libs/Logger.ts';
      // import { EPhysics2DDrawFlags, Layers, PhysicsSystem2D } from 'cc';

      var upVec2 = new Vec2(0, 1);
      var downVec2 = new Vec2(0, -1);
      var leftVec2 = new Vec2(-1, 0);
      var rightVec2 = new Vec2(1, 0);
      var GameControl = (_dec$r = ccclass$r('GameControl'), _dec2$q = menu$p('Game/GameControl'), _dec3$q = requireComponent$4([KeyInputManager, GameEventCmp]), _dec4$l = disallowMultiple$m(true), _dec5$h = executionOrder$7(-1), _dec$r(_class$r = _dec2$q(_class$r = _dec3$q(_class$r = _dec4$l(_class$r = _dec5$h(_class$r = /*#__PURE__*/function (_Component) {
        _inheritsLoose(GameControl, _Component);
        function GameControl() {
          var _this;
          for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
            _args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(_args)) || this;
          _this.log = new LogBuilder();
          // ========== GM 事件处理 ==========
          _this._tmp_Vec3 = new Vec3();
          _this._tmp_Vec3_1 = new Vec3();
          // ==================== 游戏管理事件绑定 ====================
          /**
           * 道具生成事件绑定
           */
          _this.spawnItemEventBinding = {
            event: 'gm.spawnItem',
            callback: function callback(position) {
              var _gmVar;
              if ((_gmVar = gmVar()) != null && _gmVar.itemSpawner) {
                var _position;
                // 默认生成位置为中心位置
                position = (_position = position) != null ? _position : _this.getScreenCenter();
                var nodes = gmVar().itemSpawner.spawnPrefab(position);
                nodes == null || nodes.forEach(function (node) {
                  return _this.scheduleOnce(function () {
                    var _minimap;
                    return (_minimap = minimap()) == null ? void 0 : _minimap.register({
                      node: node
                    });
                  });
                });
              }
            },
            tag: 'spawn'
          };
          /**
           * 敌人生成事件绑定
           */
          _this.spawnEnemyEventBinding = {
            event: 'gm.spawnEnemy',
            callback: function callback(position) {
              var _gmVar2;
              if ((_gmVar2 = gmVar()) != null && _gmVar2.enemySpawner) {
                var _position2;
                // 默认生成位置为中心位置
                position = (_position2 = position) != null ? _position2 : _this.getScreenCenter();
                gmVar().enemySpawner.spawnPrefab(position);
                // 更新当前剩余怪物数量
                gmVar().enemyRemainCount++;
              }
            },
            tag: 'spawn'
          };
          /**
           * 怪物死亡事件绑定
           */
          _this.enemyDeathEventBinding = {
            event: 'gm.monster.destroy',
            callback: function callback(enemyNode) {
              // 减少当前波次怪物计数
              gmVar().enemyWaveRemainCount--;
              // 增加总击杀
              gmVar().enemyTotalKillCount++;
              // 死亡点随机创建道具
              _this.scheduleOnce(function () {
                var _gmVar3;
                (_gmVar3 = gmVar()) == null || (_gmVar3 = _gmVar3.gameEvent) == null || _gmVar3.emit('gm.spawnItem', enemyNode.worldPosition.toVec2());
                enemyNode.destroy();
              }, 0.1);
            },
            tag: 'wave'
          };
          /**
           * 锚点生成事件绑定
           */
          _this.spawnAnchorEventBinding = {
            event: 'gm.anchor.spawn',
            callback: function callback(position) {
              // 使用scheduleOnce将逻辑放在下一帧执行
              _this.scheduleOnce(function () {
                var spawnPosition = position.toVec3();

                // 实例化预制体
                var anchorNode = instantiate(gmVar().anchorPrefab);
                // 设置预制体位置
                anchorNode.setPosition(spawnPosition);
                // 获取锚点倒计时组件并注册回调
                var anchorCountdown = anchorNode.getComponent(AnchorCountdown);
                if (anchorCountdown) {
                  // 设置倒计时时长
                  anchorCountdown.duration = gmVar().anchorLifeTime;
                }

                // 将预制体添加到场景中
                anchorNode.setParent(gmVar().anchorContainer, true);
              });
            },
            tag: 'anchor'
          };
          /**
           * 锚点摧毁事件绑定
           */
          _this.destroyAnchorEventBinding = {
            event: 'gm.anchor.destroy',
            callback: function callback(anchorNode) {
              var _playerState$nowAncho;
              // 检查玩家是否在使用锚点
              if (((_playerState$nowAncho = gmVar().playerState.nowAnchor) == null ? void 0 : _playerState$nowAncho.uuid) === anchorNode.uuid) {
                var _playerEvent;
                (_playerEvent = gmVar().playerEvent) == null || _playerEvent.emit('control.rotate.disconnectAnchor');
                _this.scheduleOnce(function () {
                  return anchorNode.destroy();
                });
              } else {
                anchorNode.destroy();
              }
            },
            tag: 'anchor'
          };
          /**
           * 侧边通知栏事件绑定
           */
          _this.sideNotifPanelEventBinding = {
            event: 'gm.notification.side.add',
            callback: function callback(messageData) {
              gmVar().sideNotifPanel.addNotification(messageData);
            },
            tag: 'ui'
          };
          /**
           * 主边通知栏事件绑定
           */
          _this.mainNotifPanelEventBinding = {
            event: 'gm.notification.main.add',
            callback: function callback(messageData) {
              gmVar().mainNotifPanel.addNotification(messageData);
            },
            tag: 'ui'
          };
          /**
           * ui显示
           */
          _this.showUIBinding = {
            event: 'gm.show.ui',
            callback: function callback() {
              var uiCanvas = gmVar().uiCimmond;
              uiCanvas.active = !uiCanvas.active;
            },
            tag: 'ui'
          };
          // ==================== 开发者事件绑定 ====================
          _this.playerHealthBinding = {
            event: 'dev.playerHealth',
            callback: function callback() {
              var headlth = gmVar().player.getComponent(PlayerHealth);
              headlth.enabled = !headlth.enabled;
            },
            tag: 'dev'
          };
          _this.createPlayerBinding = {
            event: 'dev.createPlayer',
            callback: function callback() {
              _this.createNewPlayer();
            },
            tag: 'dev'
          };
          // ==================== 暂停事件绑定 ====================
          // 排除pause按键的正则
          _this.excludePauseKeyRegex = /^(?!pause$).*$/;
          _this.pauseTargets = [];
          /**
           * 暂停事件绑定
           */
          _this.pauseEventBinding = {
            event: 'gm.pause.pause',
            callback: function callback() {
              return _this.scheduleOnce(function () {
                _this.log.Method('pauseEventBinding').info('暂停游戏');
                if (gmVar().isPaused) {
                  return;
                }
                gmVar().isPaused = true;
                // 暂停游戏
                PhysicsSystem2D.instance.enable = false;
                pauseAllHackTweens();
                _this.pauseTargets = director.getScheduler().pauseAllTargets();
                // 取消所有按键监听
                autoUnregisterKeyListeners(_assertThisInitialized(_this), _this.excludePauseKeyRegex);
                // 取消鼠标监听
                autoUnregisterMouseListeners(_assertThisInitialized(_this));
                // 打开暂停UI
                gmVar().pausePanel.active = true;
              });
            },
            tag: 'pause'
          };
          /**
           * 恢复事件绑定
           */
          _this.resumeEventBinding = {
            event: 'gm.pause.resume',
            callback: function callback() {
              _this.log.Method('resumeEventBinding').info('恢复游戏');
              if (!gmVar().isPaused) {
                return;
              }
              gmVar().isPaused = false;
              // 关闭暂停UI
              gmVar().pausePanel.active = false;
              // 恢复所有按键监听
              autoRegisterKeyListeners(_assertThisInitialized(_this), _this.excludePauseKeyRegex);
              // 恢复鼠标监听
              autoRegisterMouseListeners(_assertThisInitialized(_this));
              // 恢复游戏
              PhysicsSystem2D.instance.enable = true;
              resumeAllHackTweens();
              director.getScheduler().resumeTargets(_this.pauseTargets);
            },
            tag: 'resume'
          };
          // ==================== 玩家状态事件绑定 ====================
          /**
           * 玩家生命值变化UI更新
           */
          _this.updateHealthUI = function () {
            var progressBar = gmVar().UIplagerHealthProgressBar;
            if (progressBar) {
              progressBar.progress = gmVar().playerState.healthBar.progress;
            }
            var label = gmVar().UIplagerHealthRatioLabel;
            if (label) {
              label.string = gmVar().playerState.healthRatioLabel.label.string;
            }
          };
          /**
           * 生命值变化事件绑定
           */
          _this.healthChangeBinding = {
            event: 'playerState.change.health.health',
            callback: _this.updateHealthUI,
            tag: 'ui'
          };
          /**
           * 最大生命值变化事件绑定
           */
          _this.maxHealthChangeBinding = {
            event: 'playerState.change.health.maxHealth',
            callback: _this.updateHealthUI,
            tag: 'ui'
          };
          /**
           * 经验值变化事件绑定
           */
          _this.expChangeBinding = {
            event: 'playerState.change.exp.exp',
            callback: function callback(exp) {
              var progress = exp / gmVar().playerState.levelExpArray[gmVar().playerState.level] * gmVar().UIplagerExpMaxValue;
              var progressBar = gmVar().UIplagerExpProgressBar;
              if (progressBar) {
                progressBar.progress = progress;
              }
            },
            tag: 'ui'
          };
          /**
           * 等级变化事件绑定
           */
          _this.levelChangeBinding = {
            event: 'playerState.change.level.level',
            callback: function callback(level) {
              var label = gmVar().UIplagerLevelLabel;
              if (label) {
                label.string = "" + level;
              }
            },
            tag: 'ui'
          };
          /**
           * 总伤害变化事件绑定
           */
          _this.totalDamageChangeBinding = {
            event: 'playerState.change.line.totalDamage',
            callback: function callback(totalDamage) {
              var label = gmVar().attackDamageLabel;
              if (label) {
                label.string = "" + totalDamage;
              }
            },
            tag: 'ui'
          };
          /**
           * 移动速度变化事件绑定
           */
          _this.moveSpeedChangeBinding = {
            event: 'playerState.change.move.moveSpeed',
            callback: function callback(moveSpeed) {
              var label = gmVar().moveSpeedLabel;
              if (label) {
                label.string = "" + moveSpeed;
              }
            },
            tag: 'ui'
          };
          /**
           * 旋转速度变化事件绑定
           */
          _this.rotateSpeedChangeBinding = {
            event: 'playerState.change.rotate.rotateSpeed',
            callback: function callback(rotateSpeed) {
              var label = gmVar().rotateSpeedLabel;
              if (label) {
                label.string = "" + rotateSpeed;
              }
            },
            tag: 'ui'
          };
          /**
           * 恢复系数变化事件绑定
           */
          _this.healMultiChangeBinding = {
            event: 'playerState.change.healMulti.change',
            callback: function callback(args) {
              var label = gmVar().healMultiplyLabel;
              if (label) {
                label.string = args.add.toFixed(0) + "|" + (args.multi * 100).toFixed(0) + "%";
              }
            },
            tag: 'ui'
          };
          /**
           * 减伤系数变化事件绑定
           */
          _this.healReduceChangeBinding = {
            event: 'playerState.change.damageReduce.change',
            callback: function callback(args) {
              var label = gmVar().healReduceMultiplyLabel;
              if (label) {
                label.string = args.add.toFixed(0) + "|" + (args.multi * 100).toFixed(0) + "%";
              }
            },
            tag: 'ui'
          };
          // ==================== 玩家事件绑定 ====================
          /**
           * 玩家死亡事件绑定
           */
          _this.playerDeathBinding = {
            event: 'death.die',
            callback: function callback() {
              return _this.removeMoveListeners();
            },
            tag: 'control'
          };
          // ==================== 键盘事件绑定 ====================
          /**
           * 通用移动
           */
          _this.moveEvent = function (dir, keyCode) {
            return sthrottle(function () {
              // 定时执行
              var moveFunc = function moveFunc() {
                return gmVar().playerEvent.emit('control.move', dir);
              };
              _this.schedule(moveFunc, 0.3, 10, 0);
              // 一次性事件，抬起时移除持续移动
              var unschedule = function unschedule() {
                _this.unschedule(moveFunc);
              };
              var warpper = function warpper() {
                keyIO().offKeyUp(keyCode, warpper);
                unschedule();
              };
              keyIO().onKeyUp(keyCode, warpper);
              // 立即执行一次
              moveFunc();
            }, 50);
          };
          // 上
          _this.moveUpBinding = {
            keyCode: KeyCode.KEY_W,
            callback: _this.moveEvent(upVec2, KeyCode.KEY_W),
            tag: 'move'
          };
          // 下
          _this.moveDownBinding = {
            keyCode: KeyCode.KEY_S,
            callback: _this.moveEvent(downVec2, KeyCode.KEY_S),
            tag: 'move'
          };
          // 左
          _this.moveLeftBinding = {
            keyCode: KeyCode.KEY_A,
            callback: _this.moveEvent(leftVec2, KeyCode.KEY_A),
            tag: 'move'
          };
          // 右
          _this.moveRightBinding = {
            keyCode: KeyCode.KEY_D,
            callback: _this.moveEvent(rightVec2, KeyCode.KEY_D),
            tag: 'move'
          };
          /**
           * 通用旋转
           */
          _this.rotateEvent = function (dir) {
            return sthrottle(function () {
              return gmVar().playerEvent.emit("control.rotate." + dir);
            }, 50);
          };
          // 左旋转
          _this.rotateLeftBinding = {
            keyCode: KeyCode.KEY_Q,
            callback: _this.rotateEvent('left'),
            tag: 'move'
          };
          // 右旋转
          _this.rotateRightBinding = {
            keyCode: KeyCode.KEY_E,
            callback: _this.rotateEvent('right'),
            tag: 'move'
          };
          /**
           * 切换旋转中心事件绑定
           */
          _this.switchCenterBinding = {
            keyCode: KeyCode.SPACE,
            callback: sthrottle(function () {
              return gmVar().playerEvent.emit('control.rotate.switchCenter');
            }, 50),
            tag: 'move'
          };
          /**
           * 冲刺事件绑定（F键）
           */
          _this.dashKeyBinding = {
            keyCode: KeyCode.KEY_F,
            callback: sthrottle(function () {
              return gmVar().playerEvent.emit('control.dash');
            }, 50),
            tag: 'move'
          };
          // 开发者模式事件绑定
          /**
           * 生成敌人事件绑定
           */
          _this.spawnEnemyBinding = {
            keyCode: KeyCode.KEY_T,
            callback: function callback() {
              var _gmVar4;
              return (_gmVar4 = gmVar()) == null ? void 0 : _gmVar4.gameEvent.emit('gm.spawnEnemy');
            },
            tag: 'dev'
          };
          /**
           * 生成道具事件绑定
           */
          _this.spawnItemBinding = {
            keyCode: KeyCode.KEY_Y,
            callback: function callback() {
              var _gmVar5;
              return (_gmVar5 = gmVar()) == null ? void 0 : _gmVar5.gameEvent.emit('gm.spawnItem');
            },
            tag: 'dev'
          };
          /**
           * 新建玩家事件绑定
           */
          _this.newPlayerBinding = {
            keyCode: KeyCode.KEY_N,
            callback: function callback() {
              var _gmVar6;
              return (_gmVar6 = gmVar()) == null ? void 0 : _gmVar6.gameEvent.emit('dev.createPlayer');
            },
            tag: 'dev'
          };
          /**
           * 切换生命值系统事件绑定
           */
          _this.toggleHealthBinding = {
            keyCode: KeyCode.KEY_M,
            callback: function callback() {
              return gmVar().gameEvent.emit('dev.playerHealth');
            },
            tag: 'dev'
          };
          /**
           * 切换UI节点显示/隐藏事件绑定
           */
          _this.toggleUIBinding = {
            keyCode: KeyCode.KEY_J,
            callback: function callback() {
              return gmVar().gameEvent.emit('gm.show.ui');
            },
            tag: 'dev'
          };
          /**
           * 主动断开锚点
           */
          _this.disconnectAnchorBinding = {
            keyCode: KeyCode.KEY_K,
            callback: function callback() {
              return gmVar().playerEvent.emit('control.rotate.disconnectAnchor');
            },
            tag: 'dev'
          };
          _this.pauseGamefunc = function () {
            var pause = function pause() {
              return gmVar().gameEvent.emit('gm.pause.pause');
            };
            var resume = function resume() {
              return gmVar().gameEvent.emit('gm.pause.resume');
            };
            if (gmVar().isPaused) {
              resume();
            } else {
              pause();
            }
          };
          /**
           * 暂停游戏
           */
          _this.pauseGameBinding = {
            keyCode: KeyCode.ESCAPE,
            callback: function callback() {
              return _this.pauseGamefunc();
            },
            tag: 'pause'
          };
          // ==================== 鼠标事件绑定 ====================
          /**
           * 放置锚点事件绑定
           */
          _this.dropAnchorBinding = {
            mouseEvent: MouseEvent.leftMouseDown,
            callback: sthrottle(function (event) {
              var pos = mouseIO().screenToWorld(event);
              gmVar().playerEvent.emit('control.dropAnchor', pos.toVec2());
            }, 50),
            tag: 'move'
          };
          /**
           * 切换锚点事件绑定（右键）
           */
          _this.switchAnchorBinding = {
            mouseEvent: MouseEvent.rightMouseDown,
            callback: sthrottle(function (event) {
              var pos = mouseIO().screenToWorld(event);
              gmVar().playerEvent.emit('control.switchAnchor', pos.toVec2());
            }, 50),
            tag: 'move'
          };
          // ==================== 怪物波次系统 ====================
          /**
           * 启动怪物波次系统
           */
          _this.startEnemyWaveStartBinding = {
            event: 'gm.wave.start',
            callback: withAsyncSingleRunner( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(wave) {
              var enemyCount;
              return _regeneratorRuntime().wrap(function _callee$(_context) {
                while (1) switch (_context.prev = _context.next) {
                  case 0:
                    // 设置当前波次
                    gmVar().enemyWave = wave;
                    // 计算当前波次怪物数量：初始数量 * 波次数量的乘数^(波次-1)
                    enemyCount = Math.floor(gmVar().enemyInitCount * Math.pow(gmVar().enemyWaveCountMultiply, wave - 1)); // 发送通知
                    gmVar().mainNotifPanel.addNotification({
                      content: richText("\u5F00\u59CB\u7B2C " + wave + " \u6CE2\uFF0C\u9700\u8981\u51FB\u6740\u602A\u7269 " + enemyCount + " \u4E2A").color(Color.GREEN).size(30).build(),
                      displayTime: 3,
                      maxWaitTime: 0
                    });

                    // 重置当前波次怪物计数
                    gmVar().enemyWaveRemainCount = enemyCount;
                    // 重置当前剩余怪物数量
                    gmVar().enemyRemainCount = 0;

                    // 等待怪物生成完毕
                    _context.next = 7;
                    return spawnEnemies(enemyCount, {
                      spawnInterval: 1,
                      getSpawnPosition: function getSpawnPosition() {
                        return _this.getScreenCenter();
                      }
                    });
                  case 7:
                    _context.next = 9;
                    return _pollUntil(function () {
                      return gmVar().enemyWaveRemainCount <= 0;
                    }, _assertThisInitialized(_this), {
                      interval: 1,
                      maxRetries: Infinity
                    });
                  case 9:
                    // 通知当前波次结束
                    gmVar().gameEvent.emit('gm.wave.stop');
                  case 10:
                  case "end":
                    return _context.stop();
                }
              }, _callee);
            }))),
            tag: 'wave'
          };
          /**
           * 停止怪物波次系统
           */
          _this.stopEnemyWaveSystemBinding = {
            event: 'gm.wave.stop',
            callback: function callback() {
              // 发送通知
              _this.stopEnemyWaveSystemMsg();
              // 开启下一波次
              _this.scheduleOnce(function () {
                return gmVar().gameEvent.emit('gm.wave.start', ++gmVar().enemyWave);
              }, gmVar().enemyWaveInterval);
            },
            tag: 'wave'
          };
          _this.stopEnemyWaveSystemMsg = function () {
            var maxTime = gmVar().enemyWaveInterval;
            var nextWaveMsg = function nextWaveMsg(time) {
              return richText(time + "\u79D2\u540E\u5F00\u59CB\u4E0B\u4E00\u6CE2\u6B21").color(Color.GREEN).size(30).build();
            };
            gmVar().mainNotifPanel.addNotification({
              content: richText('当前波次已结束').color(Color.BLUE).size(30).br(2).text(nextWaveMsg(maxTime)).build(),
              displayTime: 1,
              maxWaitTime: 0
            });
            for (var time = maxTime - 1; time > 0; time--) {
              gmVar().mainNotifPanel.addNotification({
                content: nextWaveMsg(time),
                displayTime: 1,
                maxWaitTime: 0
              });
            }
          };
          return _this;
        }
        var _proto = GameControl.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
          var player = gmVar().canvas.getChildByName('Player');
          this.bindPlayerToGame(player);

          // 初始化说明面板
          initExplainList(gmVar().explainPanelList, this);
        };
        _proto.onEnable = function onEnable() {
          // 注册所有事件监听
          this.registerAllEventListeners();

          // 启动第一波怪物
          this.scheduleOnce(function () {
            gmVar().gameEvent.emit('gm.wave.start', 1);
          });

          // 注册墙体显示
          gmVar().wallContainer.children.forEach(function (wall) {
            var _minimap2;
            (_minimap2 = minimap()) == null || _minimap2.register({
              node: wall,
              updateType: MinimapUpdateType.DYNAMIC
            });
          });

          // 先进入暂停界面
          this.scheduleOnce(function () {
            gmVar().gameEvent.emit('gm.pause.pause');
          });

          // DEBUG_TEST: 调试模式
          // PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.All;
          // // 设置绘制层级，保证跟随
          // this.scheduleOnce(() => {
          //     const draw = find('Canvas/PHYSICS_2D_DEBUG_DRAW')!;
          //     draw.layer = Layers.Enum.DEFAULT;
          // }, 0.1);

          // // DEBUG_TEST: 提高日志等级，减少杂音
          // logger.minLevel = LogLevels.info;
        };

        _proto.onDisable = function onDisable() {
          // 移除所有事件监听
          this.unregisterAllEventListeners();
        }

        // ==================== 事件监听管理 ====================

        // ------------------- 通用事件监听 -------------------
        /**
         * 注册所有游戏和玩家事件监听器（spawn、wave、anchor、ui、control等）
         */;
        _proto.registerCommonEventListeners = function registerCommonEventListeners() {
          // 游戏事件
          autoRegisterGameListeners(this, 'spawn');
          autoRegisterGameListeners(this, 'wave');
          autoRegisterGameListeners(this, 'anchor');
          autoRegisterGameListeners(this, 'ui');
          autoRegisterGameListeners(this, 'control');

          // 玩家事件
          autoRegisterPlayerListeners(this, 'control');

          // dev
          autoRegisterGameListeners(this, 'dev');
          autoRegisterKeyListeners(this, 'dev');

          // 暂停
          autoRegisterGameListeners(this, 'pause');
          autoRegisterKeyListeners(this, 'pause');
          autoRegisterGameListeners(this, 'resume');
        }

        /**
         * 注销所有游戏和玩家事件监听器
         */;
        _proto.unregisterCommonEventListeners = function unregisterCommonEventListeners() {
          // 游戏事件
          autoUnregisterGameListeners(this, 'spawn');
          autoUnregisterGameListeners(this, 'wave');
          autoUnregisterGameListeners(this, 'anchor');
          autoUnregisterGameListeners(this, 'ui');
          autoUnregisterGameListeners(this, 'control');

          // 玩家事件
          autoUnregisterPlayerListeners(this, 'control');

          // dev
          autoUnregisterGameListeners(this, 'dev');
          autoUnregisterKeyListeners(this, 'dev');

          // 暂停
          autoUnregisterGameListeners(this, 'pause');
          autoUnregisterKeyListeners(this, 'pause');
          autoRegisterGameListeners(this, 'resume');
        }

        // ------------------- 移动控制监听 -------------------
        /**
         * 注册移动控制监听器（键盘+鼠标）
         */;
        _proto.addMoveListeners = function addMoveListeners() {
          autoRegisterKeyListeners(this, 'move');
          autoRegisterMouseListeners(this, 'move');
        }

        /**
         * 注销移动控制监听器
         */;
        _proto.removeMoveListeners = function removeMoveListeners() {
          autoUnregisterKeyListeners(this, 'move');
          autoUnregisterMouseListeners(this, 'move');
        }

        // ------------------- 统一注册/注销接口 -------------------
        /**
         * 注册所有事件监听
         */;
        _proto.registerAllEventListeners = function registerAllEventListeners() {
          this.registerCommonEventListeners();
          this.addMoveListeners();
        }

        /**
         * 移除所有事件监听
         */;
        _proto.unregisterAllEventListeners = function unregisterAllEventListeners() {
          this.removeMoveListeners();
          this.unregisterCommonEventListeners();
        };
        _proto.getScreenCenter = function getScreenCenter() {
          // 设计分辨率
          var _view$getDesignResolu = view.getDesignResolutionSize(),
            width = _view$getDesignResolu.width,
            height = _view$getDesignResolu.height;
          this._tmp_Vec3_1.set(width / 2, height / 2);
          return mainCameraCmp().screenToWorld(this._tmp_Vec3_1, this._tmp_Vec3).toVec2();
        }

        /**
         * 绑定玩家到游戏中相关的各种组件和系统
         */;
        _proto.bindPlayerToGame = function bindPlayerToGame(player) {
          var _playerState$event;
          // 线
          var lineEvent = gmVar().canvas.getComponentInChildren(LineEventCmp);
          var lineState = gmVar().canvas.getComponentInChildren(LineState);
          lineState.startNode = player;
          lineState.canDraw = false;
          // 调整玩家自身状态
          var playerState = player.getComponent(PlayerState);
          playerState.lineEvent = lineEvent;
          // gm
          gmVar().player = player;
          gmVar().playerState = playerState;
          gmVar().playerEvent = player.getComponent(PlayerEventCmp);
          gmVar().playerLineEvent = lineEvent;
          gmVar().playerCollider = player.getComponent(ColliderAble);
          // 玩家控制
          this.addMoveListeners();
          // 相机跟踪
          find$1('Canvas/Camera').getComponent(CameraFollow).target = player;
          // 调整其他物体绑定
          (_playerState$event = playerState.event) == null || _playerState$event.emit('control.rotate.switchCenter', true);
          // 怪兽
          var monsterStates = gmVar().canvas.getComponentsInChildren(MonsterState);
          for (var _iterator = _createForOfIteratorHelperLoose(monsterStates), _step; !(_step = _iterator()).done;) {
            var monsterState = _step.value;
            monsterState.target = player;
          }
        }

        /**
         * 创建新玩家并绑定到游戏中
         */;
        _proto.createNewPlayer = function createNewPlayer(position) {
          var _player, _position3;
          // 摧毁当前玩家
          (_player = gmVar().player) == null || _player.destroy();
          position = (_position3 = position) != null ? _position3 : this.getScreenCenter();

          // 创建玩家
          var player = instantiate(gmVar().playerPrefab);
          /**绑定顺序不要乱换，小心BUG */
          // 绑定玩家到游戏中相关的各种组件和系统
          this.bindPlayerToGame(player);
          // FIXME:不知道为什么创建玩家后居然没有旋转中心，但后续只要创建锚点之后就正常了，待测试到底是单纯的看不见，还是其他问题

          player.setWorldPosition(position.toVec3());
          player.setParent(gmVar().canvas, true);
        };
        return GameControl;
      }(Component)) || _class$r) || _class$r) || _class$r) || _class$r) || _class$r);

      // ==================== 说明列表工具函数 ====================

      /**
       * 说明列表数据类型
       */
      /**
       * 创建说明列表
       * @param scrollView 虚拟滚动列表组件
       * @param explainItems 说明数据数组
       */
      function createExplainList(scrollView, explainItems) {
        // 渲染每个列表项
        scrollView.renderItemFn = function (node, index) {
          var data = explainItems[index];
          if (data) {
            var _node$getChildByName, _node$getChildByName2;
            var descriptionLabel = (_node$getChildByName = node.getChildByName('按键说明')) == null ? void 0 : _node$getChildByName.getComponent(Label);
            if (descriptionLabel) {
              descriptionLabel.string = data == null ? void 0 : data.description;
            }
            var keyLabel = (_node$getChildByName2 = node.getChildByName('按键映射')) == null ? void 0 : _node$getChildByName2.getComponent(Label);
            if (keyLabel) {
              keyLabel.string = data == null ? void 0 : data.key;
            }
          }
        };

        // 设置列表项数量
        scrollView.setTotalCount(explainItems.length);
      }

      /**
       * 获取默认说明列表数据
       * @param gameControl GameControl 实例（用于获取键位绑定）
       */
      function getDefaultExplainItems(gameControl) {
        return [
        // 移动控制
        {
          description: '4向移动',
          key: 'W、A、S、D'
        },
        // 旋转控制
        {
          description: '顺时针旋转（向左）',
          key: KeyCode[gameControl.rotateLeftBinding.keyCode]
        }, {
          description: '逆时针旋转（向右）',
          key: KeyCode[gameControl.rotateRightBinding.keyCode]
        }, {
          description: '切换旋转中心（旋转后自动切换一次）',
          key: KeyCode[gameControl.switchCenterBinding.keyCode]
        }, {
          description: '朝当前锚点冲刺（无锚点时自动连接最近锚点）',
          key: KeyCode[gameControl.dashKeyBinding.keyCode]
        },
        // 鼠标操作
        {
          description: '放置锚点',
          key: '鼠标左键'
        }, {
          description: '切换锚点（二次点击向锚点冲刺）',
          key: '鼠标右键'
        },
        // 开发者功能
        {
          description: '生成敌人（开发者功能）',
          key: KeyCode[gameControl.spawnEnemyBinding.keyCode]
        }, {
          description: '生成道具（开发者功能）',
          key: KeyCode[gameControl.spawnItemBinding.keyCode]
        }, {
          description: '新建玩家（开发者功能）',
          key: KeyCode[gameControl.newPlayerBinding.keyCode]
        }, {
          description: '开关生命值系统（开发者功能）',
          key: KeyCode[gameControl.toggleHealthBinding.keyCode]
        }, {
          description: '切换UI显示（开发者功能）',
          key: KeyCode[gameControl.toggleUIBinding.keyCode]
        }, {
          description: '断开锚点（开发者功能）',
          key: KeyCode[gameControl.disconnectAnchorBinding.keyCode]
        },
        // 游戏控制
        {
          description: '暂停/继续',
          key: KeyCode[gameControl.pauseGameBinding.keyCode]
        }];
      }

      /**
       * 初始化说明列表（使用默认数据）
       * @param scrollView 虚拟滚动列表组件
       * @param gameControl GameControl 实例
       */
      function initExplainList(scrollView, gameControl) {
        var defaultItems = getDefaultExplainItems(gameControl);
        createExplainList(scrollView, defaultItems);
      }
      cclegacy._RF.pop();
      var _dec$s, _dec2$r, _dec3$r, _class$s;
      cclegacy._RF.push({}, "fe1b66Sn09IDpMP04o3EXT2", "LineCollision", undefined);
      var ccclass$s = _decorator.ccclass,
        menu$q = _decorator.menu,
        disallowMultiple$n = _decorator.disallowMultiple;
      var LineCollision = (_dec$s = ccclass$s('LineCollision'), _dec2$r = menu$q('Line/LineCollision'), _dec3$r = disallowMultiple$n(true), _dec$s(_class$s = _dec2$r(_class$s = _dec3$r(_class$s = /*#__PURE__*/function (_ref) {
        _inheritsLoose(LineCollision, _ref);
        function LineCollision() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ref.call.apply(_ref, [this].concat(args)) || this;
          _this.State = null;
          _this.previousColliders = [];
          // 默认点
          _this.deafultPoint = new Vec2(Infinity, Infinity);
          return _this;
        }
        var _proto = LineCollision.prototype;
        _proto.onLoad = function onLoad() {
          _ref.prototype.onLoad.call(this);
          this.State = this.getComponent(LineState);
        };
        _proto.update = function update(_dt) {
          if (!this.State.canDraw) return;
          var results = this.testCollision();
          this.transferCollision(results);
        };
        /**
         * 计算线段与其他物体的碰撞
         */
        _proto.testCollision = function testCollision(State) {
          var _State$startNode$worl, _State$startNode$worl2, _State$endNode$worldP, _State$endNode$worldP2;
          if (State === void 0) {
            State = this.State;
          }
          // 射线检测
          var physicsSystem = PhysicsSystem2D.instance;
          var startPoint = (_State$startNode$worl = (_State$startNode$worl2 = State.startNode.worldPosition) == null ? void 0 : _State$startNode$worl2.toVec2()) != null ? _State$startNode$worl : this.deafultPoint;
          var endPoint = (_State$endNode$worldP = (_State$endNode$worldP2 = State.endNode.worldPosition) == null ? void 0 : _State$endNode$worldP2.toVec2()) != null ? _State$endNode$worldP : this.deafultPoint;
          var raycastResult2D = physicsSystem.raycast(startPoint, endPoint, ERaycast2DType.All, State.colliderGroup);
          var distance = Vec2.distance(startPoint, endPoint);
          // 筛选距离并提取，可以考虑只保留提取，因为好像确实的线段检测。
          var results = raycastResult2D.filter(function (result) {
            return Vec2.distance(result.point, startPoint) < distance;
          }).map(function (result) {
            return result.collider;
          });
          return results;
        }

        /**
         * 转发碰撞信号
         */;
        _proto.transferCollision = function transferCollision(results) {
          var _this2 = this;
          // 使用lodash的differenceBy函数比较碰撞体数组，通过uuid属性进行比较
          var addedColliders = differenceBy(results, this.previousColliders, function (collider) {
            return collider.uuid;
          });
          var removedColliders = differenceBy(this.previousColliders, results, function (collider) {
            return collider.uuid;
          });

          // 发送开始接触事件
          addedColliders.forEach(function (collider) {
            _this2.emit("collider." + ColliderTag[collider.tag] + ".start", collider);
          });

          // 发送结束接触事件
          removedColliders.forEach(function (collider) {
            _this2.emit("collider." + ColliderTag[collider.tag] + ".end", collider);
          });

          // 更新历史记录
          this.previousColliders = [].concat(results);
        };
        return LineCollision;
      }(BaseEventCmp)) || _class$s) || _class$s) || _class$s);
      cclegacy._RF.pop();
      var _dec$t, _dec2$s, _dec3$s, _class$t;
      cclegacy._RF.push({}, "a5323h5c81AuZ+127YZQgTv", "LineControl", undefined);
      var ccclass$t = _decorator.ccclass,
        menu$r = _decorator.menu,
        disallowMultiple$o = _decorator.disallowMultiple;
      var LineControl = (_dec$t = ccclass$t('LineControl'), _dec2$s = menu$r('Line/LineControl'), _dec3$s = disallowMultiple$o(true), _dec$t(_class$t = _dec2$s(_class$t = _dec3$s(_class$t = /*#__PURE__*/function (_Component) {
        _inheritsLoose(LineControl, _Component);
        function LineControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.Event = null;
          /**
           * 处理切换线端点事件
           */
          _this.handleSwitchEnd = function (node) {
            return _this.State.endNode = node;
          };
          _this.handleSwitchStart = function (node) {
            return _this.State.startNode = node;
          };
          /**
           * 处理绘制事件
           */
          _this.handleStartDrawing = function () {
            return _this.State.canDraw = true;
          };
          _this.handleStopDrawing = function () {
            return _this.State.canDraw = false;
          };
          return _this;
        }
        var _proto = LineControl.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(LineState);
          this.Event = this.getComponent(LineEventCmp);
        };
        _proto.onEnable = function onEnable() {
          var _this$Event, _this$Event2, _this$Event3, _this$Event4;
          // 注册事件监听
          (_this$Event = this.Event) == null || _this$Event.on('switch.end', this.handleSwitchEnd);
          (_this$Event2 = this.Event) == null || _this$Event2.on('switch.start', this.handleSwitchStart);
          (_this$Event3 = this.Event) == null || _this$Event3.on('draw.start', this.handleStartDrawing);
          (_this$Event4 = this.Event) == null || _this$Event4.on('draw.stop', this.handleStopDrawing);
        };
        _proto.onDisable = function onDisable() {
          var _this$Event5, _this$Event6, _this$Event7, _this$Event8;
          // 移除事件监听
          (_this$Event5 = this.Event) == null || _this$Event5.off('switch.end', this.handleSwitchEnd);
          (_this$Event6 = this.Event) == null || _this$Event6.off('switch.start', this.handleSwitchStart);
          (_this$Event7 = this.Event) == null || _this$Event7.off('draw.start', this.handleStartDrawing);
          (_this$Event8 = this.Event) == null || _this$Event8.off('draw.stop', this.handleStopDrawing);
        };
        return LineControl;
      }(Component)) || _class$t) || _class$t) || _class$t);
      cclegacy._RF.pop();
      var _dec$u, _dec2$t, _dec3$t, _dec4$m, _dec5$i, _dec6$e, _dec7$9, _dec8$9, _class$u, _class2$g, _descriptor$g, _descriptor2$f, _descriptor3$d, _descriptor4$a;
      cclegacy._RF.push({}, "3aa15LrjI1My6B0CvUohdrg", "MeleeState", undefined);
      var ccclass$u = _decorator.ccclass,
        menu$s = _decorator.menu,
        property$h = _decorator.property,
        disallowMultiple$p = _decorator.disallowMultiple,
        executionOrder$8 = _decorator.executionOrder;
      var MeleeState = (_dec$u = ccclass$u('MeleeState'), _dec2$t = menu$s('Monster/Melee/MeleeState'), _dec3$t = disallowMultiple$p(true), _dec4$m = executionOrder$8(-1), _dec5$i = property$h(pOpt2('攻击时间（秒）', '攻击', '控制')), _dec6$e = property$h(pOpt2('攻击放大倍数', '攻击', '控制')), _dec7$9 = property$h(pOpt2('是否攻击中', '攻击', '状态')), _dec8$9 = property$h(pOpt2('攻击伤害', '攻击', '控制')), _dec$u(_class$u = _dec2$t(_class$u = _dec3$t(_class$u = _dec4$m(_class$u = (_class2$g = /*#__PURE__*/function (_MonsterState) {
        _inheritsLoose(MeleeState, _MonsterState);
        function MeleeState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _MonsterState.call.apply(_MonsterState, [this].concat(args)) || this;
          _this.colliderAble = null;
          _this.event = null;
          /* -------------------- 近战攻击 -------------------- */
          _initializerDefineProperty(_this, "attackTime", _descriptor$g, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "zoomScale", _descriptor2$f, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "isAttacking", _descriptor3$d, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "damage", _descriptor4$a, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = MeleeState.prototype;
        _proto.onLoad = function onLoad() {
          _MonsterState.prototype.onLoad.call(this);
          this.colliderAble = this.getComponent(ColliderAble);
          this.event = this.getComponent(MonsterEventCmp);
        };
        return MeleeState;
      }(MonsterState), (_descriptor$g = _applyDecoratedDescriptor(_class2$g.prototype, "attackTime", [_dec5$i], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor2$f = _applyDecoratedDescriptor(_class2$g.prototype, "zoomScale", [_dec6$e], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor3$d = _applyDecoratedDescriptor(_class2$g.prototype, "isAttacking", [_dec7$9], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor4$a = _applyDecoratedDescriptor(_class2$g.prototype, "damage", [_dec8$9], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 10;
        }
      })), _class2$g)) || _class$u) || _class$u) || _class$u) || _class$u);
      cclegacy._RF.pop();
      var _dec$v, _dec2$u, _dec3$u, _class$v;
      cclegacy._RF.push({}, "afb2faZj79NFptvIBKko32o", "MeleeAttack", undefined);
      var ccclass$v = _decorator.ccclass,
        menu$t = _decorator.menu,
        disallowMultiple$q = _decorator.disallowMultiple;
      var MeleeAttack = (_dec$v = ccclass$v('MeleeAttack'), _dec2$u = menu$t('Monster/Melee/MeleeAttack'), _dec3$u = disallowMultiple$q(true), _dec$v(_class$v = _dec2$u(_class$v = _dec3$u(_class$v = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MeleeAttack, _Component);
        function MeleeAttack() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.handleAttack = function () {
            var _this$State$target;
            if (_this.State.isAttacking || !((_this$State$target = _this.State.target) != null && _this$State$target.isValid)) {
              return;
            }
            _this.State.isAttacking = true;
            _this.State.moveState = Enum_MonsterMoveStates.MOVE;
            // 攻击动画
            _this.handleAttackTween();
          };
          _this._temp_targetVec = new Vec3();
          _this.handleAttackTween = function () {
            // 目标向量
            var targetVec = Vec3.subtract(_this._temp_targetVec, _this.State.target.worldPosition, _this.node.worldPosition).toVec2();
            // 转向
            _this.node.worldRotation = quatFromVec(targetVec);
            // 放大缓动
            var originScale = _this.node.scale.clone(); // 原来的大小
            var zoomTween = hackTween(_this.node).to(_this.State.attackTime / 2, {
              scale: _this.node.scale.multiplyScalar(_this.State.zoomScale)
            }).to(_this.State.attackTime / 2, {
              scale: originScale
            });
            // 旋转缓动
            var rotateTween = hackTween(_this.node).by(_this.State.attackTime / 2, {
              angle: 360
            }).by(_this.State.attackTime / 2, {
              angle: -360
            });
            // 组合动画
            zoomTween.parallel(rotateTween).call(function () {
              _this.State.moveState = Enum_MonsterMoveStates.STOP;
              _this.State.isAttacking = false;
            }).bindNodeState(true).start();
          };
          return _this;
        }
        var _proto = MeleeAttack.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(MeleeState);
        };
        _proto.onEnable = function onEnable() {
          this.State.event.on('attack', this.handleAttack);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event;
          (_this$State$event = this.State.event) == null || _this$State$event.off('attack', this.handleAttack);
        };
        return MeleeAttack;
      }(Component)) || _class$v) || _class$v) || _class$v);
      cclegacy._RF.pop();
      var _dec$w, _dec2$v, _dec3$v, _class$w;
      cclegacy._RF.push({}, "756adf7xo1M+anuSUtWZaa7", "MeleeControl", undefined);
      var ccclass$w = _decorator.ccclass,
        menu$u = _decorator.menu,
        disallowMultiple$r = _decorator.disallowMultiple;
      var MeleeControl = (_dec$w = ccclass$w('MeleeControl'), _dec2$v = menu$u('Monster/Melee/MeleeControl'), _dec3$v = disallowMultiple$r(true), _dec$w(_class$w = _dec2$v(_class$w = _dec3$v(_class$w = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MeleeControl, _Component);
        function MeleeControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          // 监听取消函数数组
          _this.unsubscribeFunctions = [];
          _this.handleFollow = function () {
            var _this$State$target;
            if (!((_this$State$target = _this.State.target) != null && _this$State$target.isValid)) {
              return;
            }
            _this.State.event.emit('follow.follow');
          };
          _this.handleAttack = function () {
            return _this.State.event.emit('attack');
          };
          _this.handleStop = function () {
            _this.State.colliderAble.RigidBody.linearVelocity = Vec2.ZERO.clone();
            _this.State.moveState = Enum_MonsterMoveStates.STAND;
            _this.scheduleOnce(function () {
              return _this.State.moveState = Enum_MonsterMoveStates.STOP;
            }, _this.State.stopTime);
          };
          _this.handlePlayerDamage = sthrottle(function () {
            gmVar().playerEvent.emit('control.damage.damage', _this.State.damage);
          }, 1000);
          _this.stateListener_healthChange = function (newValue, old_value) {
            _this.State.event.emit('hp.change', {
              now_value: newValue,
              old_value: old_value,
              max_value: _this.State.maxHealth
            });
          };
          _this.stateListener_healthZero = function (newValue) {
            if (newValue <= 0) {
              _this.State.event.emit('death');
            }
          };
          // 节流刷新血条
          _this.handleHealthChange = sthrottle(function (_ref) {
            var new_value = _ref.now_value,
              max_value = _ref.max_value;
            _this.State.healthBar.progress = clamp$1(new_value / max_value, 0, 1);
            _this.State.healthRatioLabel.handleRefreshRatio(new_value, max_value);
          }, 100);
          return _this;
        }
        var _proto = MeleeControl.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(MeleeState);
        };
        _proto.onEnable = function onEnable() {
          var _minimap;
          // 小地图显示
          (_minimap = minimap()) == null || _minimap.register({
            node: this.node
          });

          // 持续跟随
          this.schedule(this.handleFollow, this.State.moveInterval, macro.REPEAT_FOREVER);
          // 到达范围则攻击
          this.State.event.on('follow.reached', this.handleAttack);
          // 到达范围停止移动
          this.State.event.on('follow.reached', this.handleStop);
          // 碰到玩家
          this.State.event.on('collider.Player.start', this.handlePlayerDamage);

          // 生命值变化
          var healthUnsubscribe = this.State._health.listen(this.stateListener_healthChange);
          this.unsubscribeFunctions.push(healthUnsubscribe);

          // 生命值归零
          var healthZeroUnsubscribe = this.State._health.listen(this.stateListener_healthZero);
          this.unsubscribeFunctions.push(healthZeroUnsubscribe);
          this.State.event.on('hp.change', this.handleHealthChange);
        };
        _proto.onDisable = function onDisable() {
          var _minimap2, _this$State$event, _this$State$event2, _this$State$event3, _this$State$event4;
          (_minimap2 = minimap()) == null || _minimap2.unregister(this.node);
          this.unschedule(this.handleFollow);
          (_this$State$event = this.State.event) == null || _this$State$event.off('follow.reached', this.handleAttack);
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('follow.reached', this.handleStop);
          (_this$State$event3 = this.State.event) == null || _this$State$event3.off('collider.Player.start', this.handlePlayerDamage);
          (_this$State$event4 = this.State.event) == null || _this$State$event4.off('hp.change', this.handleHealthChange);

          // 取消所有nanostores订阅
          this.unsubscribeFunctions.forEach(function (unsubscribe) {
            return unsubscribe();
          });
          this.unsubscribeFunctions = [];
        };
        return MeleeControl;
      }(Component)) || _class$w) || _class$w) || _class$w);
      cclegacy._RF.pop();
      var _dec$x, _dec2$w, _dec3$w, _class$x;
      cclegacy._RF.push({}, "d1dbasxFdZNwausQA/jm/ru", "MonsterDeath", undefined);
      var ccclass$x = _decorator.ccclass,
        menu$v = _decorator.menu,
        disallowMultiple$s = _decorator.disallowMultiple;
      var MonsterDeath = (_dec$x = ccclass$x('MonsterDeath'), _dec2$w = menu$v('Monster/MonsterDeath'), _dec3$w = disallowMultiple$s(true), _dec$x(_class$x = _dec2$w(_class$x = _dec3$w(_class$x = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MonsterDeath, _Component);
        function MonsterDeath() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.handleDeath = function () {
            var _gmVar;
            (_gmVar = gmVar()) == null || (_gmVar = _gmVar.gameEvent) == null || _gmVar.emit('gm.monster.destroy', _this.node);
          };
          return _this;
        }
        var _proto = MonsterDeath.prototype;
        _proto.onEnable = function onEnable() {
          var _this$State$event;
          (_this$State$event = this.State.event) == null || _this$State$event.on('death', this.handleDeath);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event2;
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('death', this.handleDeath);
        };
        return MonsterDeath;
      }(Component)) || _class$x) || _class$x) || _class$x);
      cclegacy._RF.pop();
      var _dec$y, _dec2$x, _class$y;
      cclegacy._RF.push({}, "ea702Fd7EVBPY9Cu5GEg0yj", "MeleeDeath", undefined);
      var ccclass$y = _decorator.ccclass,
        menu$w = _decorator.menu;
      var MeleeDeath = (_dec$y = ccclass$y('MeleeDeath'), _dec2$x = menu$w('Monster/Melee/MeleeDeath'), _dec$y(_class$y = _dec2$x(_class$y = /*#__PURE__*/function (_MonsterDeath) {
        _inheritsLoose(MeleeDeath, _MonsterDeath);
        function MeleeDeath() {
          return _MonsterDeath.apply(this, arguments) || this;
        }
        var _proto = MeleeDeath.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterDeath$prototy;
          this.State = this.getComponent(MeleeState);
          (_MonsterDeath$prototy = _MonsterDeath.prototype.onLoad) == null || _MonsterDeath$prototy.call(this);
        };
        return MeleeDeath;
      }(MonsterDeath)) || _class$y) || _class$y);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "5f9a5GwOsxDs4mOTlLncf1L", "MonsterPathfinder", undefined);

      /**
       * 寻路结果
       */

      /**
       * 怪物寻路模块
       * 提供简单的避障追踪功能
       *
       * 寻路算法：
       * 1. 获取当前位置 a，朝目标位置 b 发送射线检测
       * 2. 如果无遮挡，直接前进（但受 moveDistance 限制）
       * 3. 如果有遮挡，在最近障碍物的 AABB 上找到最近点 c
       * 4. 从 a 到 c 延伸到点 d，使得 ad 的长度大于该障碍物 AABB 在 ac 方向上的投影
       */
      /**
       * 寻找路径
       * @param node 当前节点
       * @param targetPos 目标位置
       * @param targetNode 目标节点（用于判断遮挡是否为目标本身）
       * @returns 寻路结果
       *
       * TEMP // 需要更好的避障或者寻路算法 ，当前避障效果极差，所以干脆注释，按直接寻路计算
       */
      function findPath(node, targetPos, targetNode) {
        // 获取当前位置
        var currentPos = node.worldPosition;

        // 朝目标位置发送射线检测
        var raycastResult = raycastToTarget(node, currentPos, targetPos);

        // 判断是否可以直达
        var isDirect = raycastResult.length === 0 || raycastResult.length === 1 && raycastResult[0].collider.node.uuid === (targetNode == null ? void 0 : targetNode.uuid);

        // 获取下一个目标点
        var nextTarget;
        if (isDirect) {
          // 直达：目标点就是目标位置
          nextTarget = {
            x: targetPos.x,
            y: targetPos.y
          };
        } else {
          // 避障：计算避障目标点
          // nextTarget = calculateAvoidanceTarget(currentPos, raycastResult);
          // 需要更好的避障或者寻路算法 ，当前避障效果极差，所以干脆注释，按直接寻路计算
          nextTarget = {
            x: targetPos.x,
            y: targetPos.y
          };
        }

        // 根据当前位置和目标点计算方向和距离
        var distance = Vec2.distance(currentPos, nextTarget);
        var direction = {
          x: 0,
          y: 0
        };
        Vec2.subtract(direction, nextTarget, currentPos);
        Vec2.normalize(direction, direction);
        return {
          isDirect: isDirect,
          direction: direction,
          nextTarget: nextTarget,
          distance: distance
        };
      }

      /**
       * 射线检测（使用节点碰撞分组自动过滤）
       */
      function raycastToTarget(node, startPos, targetPos) {
        // 获取节点上的碰撞体，从而获取碰撞分组
        var collider2D = node.getComponent(Collider2D);
        var colliderGroup = collider2D ? collider2D.group : 0;
        var colliderMask = PhysicsSystem2D.instance.collisionMatrix[colliderGroup];

        // 使用 PhysicsSystem2D 的 raycast，传入碰撞分组的位掩码来过滤碰撞体
        return PhysicsSystem2D.instance.raycast(startPos, targetPos, ERaycast2DType.All, colliderMask);
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "acc8c222QJB5K6ULKpEdNcd", "MonsterFollow", undefined);
      var MonsterFollow = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MonsterFollow, _Component);
        function MonsterFollow() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.handleSwitchTarget = function (node) {
            return _this.State.target = node;
          };
          _this.handleFollow = function () {
            // 目标
            var target = _this.State.target;
            if (!(target != null && target.isValid)) {
              return;
            }

            // 使用寻路模块获取寻路结果
            var _findPath = findPath(_this.node, target.worldPosition, target),
              isDirect = _findPath.isDirect,
              nextTarget = _findPath.nextTarget,
              distance = _findPath.distance;

            // 如果是直达且距离小于停止距离，说明已经到达
            if (isDirect && distance <= _this.State.stopDistance) {
              var _this$State$event;
              (_this$State$event = _this.State.event) == null || _this$State$event.emit('follow.reached');
            } else {
              var _this$State$event2;
              // 移动
              var newTargetPos = new Vec2(nextTarget.x, nextTarget.y);
              (_this$State$event2 = _this.State.event) == null || _this$State$event2.emit('move', newTargetPos);
            }
          };
          return _this;
        }
        var _proto = MonsterFollow.prototype;
        _proto.onEnable = function onEnable() {
          this.State.event.on('follow.switchTarget', this.handleSwitchTarget);
          this.State.event.on('follow.follow', this.handleFollow);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event3, _this$State$event4;
          (_this$State$event3 = this.State.event) == null || _this$State$event3.off('follow.switchTarget', this.handleSwitchTarget);
          (_this$State$event4 = this.State.event) == null || _this$State$event4.off('follow.follow', this.handleFollow);
        };
        return MonsterFollow;
      }(Component);
      cclegacy._RF.pop();
      var _dec$z, _dec2$y, _class$z;
      cclegacy._RF.push({}, "03a001CT2BPir2ROGcyQg0G", "MeleeFollow", undefined);
      var ccclass$z = _decorator.ccclass,
        menu$x = _decorator.menu;
      var MeleeFollow = (_dec$z = ccclass$z('MeleeFollow'), _dec2$y = menu$x('Monster/Melee/MeleeFollow'), _dec$z(_class$z = _dec2$y(_class$z = /*#__PURE__*/function (_MonsterFollow) {
        _inheritsLoose(MeleeFollow, _MonsterFollow);
        function MeleeFollow() {
          return _MonsterFollow.apply(this, arguments) || this;
        }
        var _proto = MeleeFollow.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterFollow$protot;
          this.State = this.getComponent(MeleeState);
          (_MonsterFollow$protot = _MonsterFollow.prototype.onLoad) == null || _MonsterFollow$protot.call(this);
        };
        return MeleeFollow;
      }(MonsterFollow)) || _class$z) || _class$z);
      cclegacy._RF.pop();
      var _dec$A, _dec2$z, _dec3$x, _class$A;
      cclegacy._RF.push({}, "d3fe3dWruBEpKSJ/oEZoYQh", "MonsterHealth", undefined);
      var ccclass$A = _decorator.ccclass,
        menu$y = _decorator.menu,
        disallowMultiple$t = _decorator.disallowMultiple;
      var MonsterHealth = (_dec$A = ccclass$A('MonsterHealth'), _dec2$z = menu$y('Monster/MonsterHealth'), _dec3$x = disallowMultiple$t(true), _dec$A(_class$A = _dec2$z(_class$A = _dec3$x(_class$A = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MonsterHealth, _Component);
        function MonsterHealth() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          return _this;
        }
        var _proto = MonsterHealth.prototype;
        _proto.onEnable = function onEnable() {
          this.State.event.on('damage', this.handleDamage, this);
        };
        _proto.onDisable = function onDisable() {
          this.State.event.off('damage', this.handleDamage, this);
        }

        // 响应伤害
        ;

        _proto.handleDamage = function handleDamage(damage) {
          var nowDamage = this.State.damageAdd + damage * this.State.damageMultiply;
          this.State.health = this.State.health - nowDamage;
        };
        return MonsterHealth;
      }(Component)) || _class$A) || _class$A) || _class$A);
      cclegacy._RF.pop();
      var _dec$B, _dec2$A, _dec3$y, _class$B;
      cclegacy._RF.push({}, "6221cz01rJEYqkO7uNi4hLO", "MeleeHealth", undefined);
      var ccclass$B = _decorator.ccclass,
        menu$z = _decorator.menu,
        disallowMultiple$u = _decorator.disallowMultiple;
      var MeleeHealth = (_dec$B = ccclass$B('MeleeHealth'), _dec2$A = menu$z('Monster/Melee/MeleeHealth'), _dec3$y = disallowMultiple$u(true), _dec$B(_class$B = _dec2$A(_class$B = _dec3$y(_class$B = /*#__PURE__*/function (_MonsterHealth) {
        _inheritsLoose(MeleeHealth, _MonsterHealth);
        function MeleeHealth() {
          return _MonsterHealth.apply(this, arguments) || this;
        }
        var _proto = MeleeHealth.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterHealth$protot;
          this.State = this.getComponent(MeleeState);
          (_MonsterHealth$protot = _MonsterHealth.prototype.onLoad) == null || _MonsterHealth$protot.call(this);
        };
        return MeleeHealth;
      }(MonsterHealth)) || _class$B) || _class$B) || _class$B);
      cclegacy._RF.pop();
      var _dec$C, _dec2$B, _class$C;
      cclegacy._RF.push({}, "3fbd7PoopNOI4oo6ykXwr9Q", "MeleeMove", undefined);
      var ccclass$C = _decorator.ccclass,
        menu$A = _decorator.menu;
      var MeleeMove = (_dec$C = ccclass$C('MeleeMove'), _dec2$B = menu$A('Monster/Melee/MeleeMove'), _dec$C(_class$C = _dec2$B(_class$C = /*#__PURE__*/function (_MonsterMove) {
        _inheritsLoose(MeleeMove, _MonsterMove);
        function MeleeMove() {
          return _MonsterMove.apply(this, arguments) || this;
        }
        var _proto = MeleeMove.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterMove$prototyp;
          this.State = this.getComponent(MeleeState);
          (_MonsterMove$prototyp = _MonsterMove.prototype.onLoad) == null || _MonsterMove$prototyp.call(this);
        };
        return MeleeMove;
      }(MonsterMove)) || _class$C) || _class$C);
      cclegacy._RF.pop();
      var _dec$D, _dec2$C, _dec3$z, _dec4$n, _dec5$j, _class$D, _class2$h, _descriptor$h, _descriptor2$g;
      cclegacy._RF.push({}, "8a4672qjPpDP4u4U4kVpVG7", "BulletControl", undefined);
      var ccclass$D = _decorator.ccclass,
        requireComponent$5 = _decorator.requireComponent,
        property$i = _decorator.property,
        menu$B = _decorator.menu;
      var BulletControl = (_dec$D = ccclass$D('BulletControl'), _dec2$C = menu$B('Monster/Ranged/Bullet/BulletControl'), _dec3$z = requireComponent$5(ColliderAble), _dec4$n = property$i({
        tooltip: '子弹伤害值'
      }), _dec5$j = property$i({
        tooltip: '子弹持续时间(秒)'
      }), _dec$D(_class$D = _dec2$C(_class$D = _dec3$z(_class$D = (_class2$h = /*#__PURE__*/function (_Component) {
        _inheritsLoose(BulletControl, _Component);
        function BulletControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.colliderAble = void 0;
          _initializerDefineProperty(_this, "bulletdamage", _descriptor$h, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletduration", _descriptor2$g, _assertThisInitialized(_this));
          /**
           * 子弹与墙体碰撞时的处理 - 反弹
           * @param selfCollider 子弹的碰撞体
           * @param otherCollider 墙体的碰撞体
           * @param contact 碰撞信息
           */
          _this.handleWallCollision = function (selfCollider, otherCollider, contact) {
            // 计算反射向量实现反弹效果
            var rigidBody = _this.colliderAble.RigidBody;
            var velocity = rigidBody.linearVelocity.clone();
            var normal = contact.getWorldManifold().normal.clone();

            // 根据入射角计算反射角: r = v - 2 * (v · n) * n
            var dot = Vec2.dot(velocity, normal);
            var reflect = new Vec2();
            Vec2.scaleAndAdd(reflect, velocity, normal, -2 * dot);

            // 应用反射后的速度
            _this.scheduleOnce(function () {
              rigidBody.linearVelocity = reflect;
              // 调整方向
              _this.node.worldRotation = quatFromVec(reflect);
            });
            // 忽略后续碰撞事件
            contact.disabled = true;
          };
          /**
           * 子弹与玩家碰撞时的处理 - 销毁并向玩家发送伤害事件
           * @param selfCollider 子弹的碰撞体
           * @param otherCollider 玩家的碰撞体
           * @param contact 碰撞信息
           */
          _this.handlePlayerCollision = function (selfCollider, otherCollider, contact) {
            // 向玩家发送伤害事件
            var PlayerEvent = otherCollider.getComponent(PlayerEventCmp);
            PlayerEvent == null || PlayerEvent.emit('control.damage.damage', _this.bulletdamage);

            // 销毁子弹节点
            _this.scheduleOnce(function () {
              _this.node.destroy();
            });

            // 忽略后续碰撞事件
            contact.disabled = true;
          };
          /**
           * 忽略后续碰撞事件
           */
          _this.ignoreContact = function (_selfCollider, _otherCollider, contact) {
            contact.disabled = true;
          };
          return _this;
        }
        var _proto = BulletControl.prototype;
        _proto.onLoad = function onLoad() {
          this.colliderAble = this.getComponent(ColliderAble);
        };
        _proto.onEnable = function onEnable() {
          var _this2 = this;
          // 监听碰撞事件
          this.colliderAble.on('collider.Wall.start', this.handleWallCollision);
          this.colliderAble.on('collider.Player.start', this.handlePlayerCollision);
          this.colliderAble.on('collider.Monster.start', this.ignoreContact);
          // 定时消失
          this.scheduleOnce(function () {
            return _this2.node.destroy();
          }, this.bulletduration);
        };
        _proto.onDisable = function onDisable() {
          // 取消监听碰撞事件
          this.colliderAble.off('collider.Wall.start', this.handleWallCollision);
          this.colliderAble.off('collider.Player.start', this.handlePlayerCollision);
          this.colliderAble.off('collider.Monster.start', this.ignoreContact);
        };
        return BulletControl;
      }(Component), (_descriptor$h = _applyDecoratedDescriptor(_class2$h.prototype, "bulletdamage", [_dec4$n], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1;
        }
      }), _descriptor2$g = _applyDecoratedDescriptor(_class2$h.prototype, "bulletduration", [_dec5$j], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 3;
        }
      })), _class2$h)) || _class$D) || _class$D) || _class$D);
      cclegacy._RF.pop();
      var _dec$E, _dec2$D, _dec3$A, _dec4$o, _dec5$k, _dec6$f, _dec7$a, _dec8$a, _dec9$9, _class$E, _class2$i, _descriptor$i, _descriptor2$h, _descriptor3$e, _descriptor4$b, _descriptor5$9, _descriptor6$9;
      cclegacy._RF.push({}, "e781dGkJQJD7IssXaXtSMUH", "RangedState", undefined);
      var ccclass$E = _decorator.ccclass,
        menu$C = _decorator.menu,
        property$j = _decorator.property,
        executionOrder$9 = _decorator.executionOrder;
      var RangedState = (_dec$E = ccclass$E('RangedState'), _dec2$D = menu$C('Monster/Ranged/RangedState'), _dec3$A = executionOrder$9(-1), _dec4$o = property$j(pOpt2('是否攻击中', '攻击', '状态')), _dec5$k = property$j(pOpt2('子弹速度（像素/秒）', '攻击', '控制')), _dec6$f = property$j(pOpt1(Node, '子弹容器', '攻击', '绑定')), _dec7$a = property$j(pOpt1(Node, '子弹发射位置', '攻击', '绑定')), _dec8$a = property$j(pOpt1(Prefab, '子弹预制体', '攻击', '绑定')), _dec9$9 = property$j(pOpt2('攻击间隔（秒）', '攻击', '控制')), _dec$E(_class$E = _dec2$D(_class$E = _dec3$A(_class$E = (_class2$i = /*#__PURE__*/function (_MonsterState) {
        _inheritsLoose(RangedState, _MonsterState);
        function RangedState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _MonsterState.call.apply(_MonsterState, [this].concat(args)) || this;
          _this.colliderAble = null;
          _this.event = null;
          /* -------------------- 远程攻击 -------------------- */
          _initializerDefineProperty(_this, "isAttacking", _descriptor$i, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletSpeed", _descriptor2$h, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletContainer", _descriptor3$e, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletCreatePos", _descriptor4$b, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "bulletPrefab", _descriptor5$9, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "attackInterval", _descriptor6$9, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = RangedState.prototype;
        _proto.onLoad = function onLoad() {
          _MonsterState.prototype.onLoad.call(this);
          this.colliderAble = this.getComponent(ColliderAble);
          this.event = this.getComponent(MonsterEventCmp);

          // 尝试绑定
          this.bulletContainer = gmVar().bulletContainer;
        };
        return RangedState;
      }(MonsterState), (_descriptor$i = _applyDecoratedDescriptor(_class2$i.prototype, "isAttacking", [_dec4$o], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return false;
        }
      }), _descriptor2$h = _applyDecoratedDescriptor(_class2$i.prototype, "bulletSpeed", [_dec5$k], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 20;
        }
      }), _descriptor3$e = _applyDecoratedDescriptor(_class2$i.prototype, "bulletContainer", [_dec6$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor4$b = _applyDecoratedDescriptor(_class2$i.prototype, "bulletCreatePos", [_dec7$a], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor5$9 = _applyDecoratedDescriptor(_class2$i.prototype, "bulletPrefab", [_dec8$a], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor6$9 = _applyDecoratedDescriptor(_class2$i.prototype, "attackInterval", [_dec9$9], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      })), _class2$i)) || _class$E) || _class$E) || _class$E);
      cclegacy._RF.pop();
      var _dec$F, _dec2$E, _dec3$B, _class$F;
      cclegacy._RF.push({}, "4cd71aep/hANYgTAXJkJV8j", "RangedAttack", undefined);
      var ccclass$F = _decorator.ccclass,
        menu$D = _decorator.menu,
        disallowMultiple$v = _decorator.disallowMultiple;
      var RangedAttack = (_dec$F = ccclass$F('RangedAttack'), _dec2$E = menu$D('Monster/Ranged/RangedAttack'), _dec3$B = disallowMultiple$v(true), _dec$F(_class$F = _dec2$E(_class$F = _dec3$B(_class$F = /*#__PURE__*/function (_Component) {
        _inheritsLoose(RangedAttack, _Component);
        function RangedAttack() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.handleAttack = function () {
            var _this$State$target;
            if (_this.State.isAttacking || !((_this$State$target = _this.State.target) != null && _this$State$target.isValid)) {
              return;
            }
            _this.State.isAttacking = true;
            _this.scheduleOnce(function () {
              return _this.State.isAttacking = false;
            }, _this.State.attackInterval);
            // 开火
            _this.handleAttackAction();
          };
          _this._temp_targetVec = new Vec3();
          _this.handleAttackAction = function () {
            var _this$State$target2;
            // 目标向量
            var targetVec = Vec3.subtract(_this._temp_targetVec, ((_this$State$target2 = _this.State.target) != null ? _this$State$target2 : _this.node).worldPosition, _this.node.worldPosition).toVec2();
            // 转向
            _this.node.worldRotation = quatFromVec(targetVec);
            // 开火
            _this.createBullet(targetVec);
          };
          return _this;
        }
        var _proto = RangedAttack.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(RangedState);
        };
        _proto.onEnable = function onEnable() {
          this.State.event.on('attack', this.handleAttack);
        };
        _proto.onDisable = function onDisable() {
          this.State.event.off('attack', this.handleAttack);
        };
        _proto.createBullet = function createBullet(targetVec) {
          var bullet = instantiate(this.State.bulletPrefab);
          bullet.setWorldPosition(this.State.bulletCreatePos.worldPosition);
          bullet.setParent(this.State.bulletContainer, true);
          var rigid = bullet.getComponent(RigidBody2D);
          if (rigid) {
            var vecSpeed = targetVec.normalize().multiplyScalar(this.State.bulletSpeed);
            rigid.linearVelocity = vecSpeed;

            // 调整角度
            bullet.worldRotation = quatFromVec(vecSpeed);
          }
        };
        return RangedAttack;
      }(Component)) || _class$F) || _class$F) || _class$F);
      cclegacy._RF.pop();
      var _dec$G, _dec2$F, _dec3$C, _class$G;
      cclegacy._RF.push({}, "1e0f9NlsdZFt73R0+WLo+wr", "RangedControl", undefined);
      var ccclass$G = _decorator.ccclass,
        menu$E = _decorator.menu,
        disallowMultiple$w = _decorator.disallowMultiple;
      var RangedControl = (_dec$G = ccclass$G('RangedControl'), _dec2$F = menu$E('Monster/Ranged/RangedControl'), _dec3$C = disallowMultiple$w(true), _dec$G(_class$G = _dec2$F(_class$G = _dec3$C(_class$G = /*#__PURE__*/function (_Component) {
        _inheritsLoose(RangedControl, _Component);
        function RangedControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = void 0;
          // 监听取消函数数组
          _this.unsubscribeFunctions = [];
          _this.handleFollow = function () {
            var _this$State$target;
            if (!((_this$State$target = _this.State.target) != null && _this$State$target.isValid)) {
              return;
            }
            _this.State.event.emit('follow.follow');
          };
          _this.handleAttack = function () {
            return _this.State.event.emit('attack');
          };
          _this.handleStop = function () {
            _this.State.colliderAble.RigidBody.linearVelocity = Vec2.ZERO.clone();
            _this.State.moveState = Enum_MonsterMoveStates.STAND;
            _this.scheduleOnce(function () {
              return _this.State.moveState = Enum_MonsterMoveStates.STOP;
            }, _this.State.stopTime);
          };
          _this.stateListener_healthChange = function (newValue, old_value) {
            _this.State.event.emit('hp.change', {
              now_value: newValue,
              old_value: old_value,
              max_value: _this.State.maxHealth
            });
          };
          _this.stateListener_healthZero = function (newValue) {
            if (newValue <= 0) {
              _this.State.event.emit('death');
            }
          };
          // 节流刷新血条
          _this.handleHealthChange = sthrottle(function (_ref) {
            var new_value = _ref.now_value,
              max_value = _ref.max_value;
            _this.State.healthBar.progress = clamp$1(new_value / max_value, 0, 1);
            _this.State.healthRatioLabel.handleRefreshRatio(new_value, max_value);
          }, 100);
          return _this;
        }
        var _proto = RangedControl.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(RangedState);
        };
        _proto.onEnable = function onEnable() {
          var _minimap;
          // 小地图显示
          (_minimap = minimap()) == null || _minimap.register({
            node: this.node
          });

          // 持续跟随
          this.schedule(this.handleFollow, this.State.moveInterval, macro.REPEAT_FOREVER);
          // 到达范围则攻击
          this.State.event.on('follow.reached', this.handleAttack);
          // 到达范围停止移动
          this.State.event.on('follow.reached', this.handleStop);

          // 生命值变化
          var healthUnsubscribe = this.State._health.listen(this.stateListener_healthChange);
          this.unsubscribeFunctions.push(healthUnsubscribe);
          // 生命值归零
          var healthZeroUnsubscribe = this.State._health.listen(this.stateListener_healthZero);
          this.unsubscribeFunctions.push(healthZeroUnsubscribe);
          this.State.event.on('hp.change', this.handleHealthChange);
        };
        _proto.onDisable = function onDisable() {
          var _minimap2, _this$State$event, _this$State$event2, _this$State$event3;
          (_minimap2 = minimap()) == null || _minimap2.unregister(this.node);
          this.unschedule(this.handleFollow);
          (_this$State$event = this.State.event) == null || _this$State$event.off('follow.reached', this.handleAttack);
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('follow.reached', this.handleStop);
          (_this$State$event3 = this.State.event) == null || _this$State$event3.off('hp.change', this.handleHealthChange);

          // 取消所有nanostores订阅
          this.unsubscribeFunctions.forEach(function (unsubscribe) {
            return unsubscribe();
          });
          this.unsubscribeFunctions = [];
        };
        return RangedControl;
      }(Component)) || _class$G) || _class$G) || _class$G);
      cclegacy._RF.pop();
      var _dec$H, _dec2$G, _dec3$D, _class$H;
      cclegacy._RF.push({}, "c0123Ym4NxFiJd0IWkZTLIX", "RangedDeath", undefined);
      var ccclass$H = _decorator.ccclass,
        menu$F = _decorator.menu,
        disallowMultiple$x = _decorator.disallowMultiple;
      var RangedDeath = (_dec$H = ccclass$H('RangedDeath'), _dec2$G = menu$F('Monster/Ranged/RangedDeath'), _dec3$D = disallowMultiple$x(true), _dec$H(_class$H = _dec2$G(_class$H = _dec3$D(_class$H = /*#__PURE__*/function (_MonsterDeath) {
        _inheritsLoose(RangedDeath, _MonsterDeath);
        function RangedDeath() {
          return _MonsterDeath.apply(this, arguments) || this;
        }
        var _proto = RangedDeath.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterDeath$prototy;
          this.State = this.getComponent(RangedState);
          (_MonsterDeath$prototy = _MonsterDeath.prototype.onLoad) == null || _MonsterDeath$prototy.call(this);
        };
        return RangedDeath;
      }(MonsterDeath)) || _class$H) || _class$H) || _class$H);
      cclegacy._RF.pop();
      var _dec$I, _dec2$H, _dec3$E, _class$I;
      cclegacy._RF.push({}, "fb435q2RzpJ3YVhRupSgUR4", "RangedFollow", undefined);
      var ccclass$I = _decorator.ccclass,
        menu$G = _decorator.menu,
        disallowMultiple$y = _decorator.disallowMultiple;
      var RangedFollow = (_dec$I = ccclass$I('RangedFollow'), _dec2$H = menu$G('Monster/Ranged/RangedFollow'), _dec3$E = disallowMultiple$y(true), _dec$I(_class$I = _dec2$H(_class$I = _dec3$E(_class$I = /*#__PURE__*/function (_MonsterFollow) {
        _inheritsLoose(RangedFollow, _MonsterFollow);
        function RangedFollow() {
          return _MonsterFollow.apply(this, arguments) || this;
        }
        var _proto = RangedFollow.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterFollow$protot;
          this.State = this.getComponent(RangedState);
          (_MonsterFollow$protot = _MonsterFollow.prototype.onLoad) == null || _MonsterFollow$protot.call(this);
        };
        return RangedFollow;
      }(MonsterFollow)) || _class$I) || _class$I) || _class$I);
      cclegacy._RF.pop();
      var _dec$J, _dec2$I, _dec3$F, _class$J;
      cclegacy._RF.push({}, "8440dBiXw1Dd7CplWIQc1y1", "RangedHealth", undefined);
      var ccclass$J = _decorator.ccclass,
        menu$H = _decorator.menu,
        disallowMultiple$z = _decorator.disallowMultiple;
      var RangedHealth = (_dec$J = ccclass$J('RangedHealth'), _dec2$I = menu$H('Monster/Ranged/RangedHealth'), _dec3$F = disallowMultiple$z(true), _dec$J(_class$J = _dec2$I(_class$J = _dec3$F(_class$J = /*#__PURE__*/function (_MonsterHealth) {
        _inheritsLoose(RangedHealth, _MonsterHealth);
        function RangedHealth() {
          return _MonsterHealth.apply(this, arguments) || this;
        }
        var _proto = RangedHealth.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterHealth$protot;
          this.State = this.getComponent(RangedState);
          (_MonsterHealth$protot = _MonsterHealth.prototype.onLoad) == null || _MonsterHealth$protot.call(this);
        };
        return RangedHealth;
      }(MonsterHealth)) || _class$J) || _class$J) || _class$J);
      cclegacy._RF.pop();
      var _dec$K, _dec2$J, _dec3$G, _class$K;
      cclegacy._RF.push({}, "ee4bbx4OUlM6rg075afdF2Y", "RangedMove", undefined);
      var ccclass$K = _decorator.ccclass,
        menu$I = _decorator.menu,
        disallowMultiple$A = _decorator.disallowMultiple;
      var RangedMove = (_dec$K = ccclass$K('RangedMove'), _dec2$J = menu$I('Monster/Ranged/RangedMove'), _dec3$G = disallowMultiple$A(true), _dec$K(_class$K = _dec2$J(_class$K = _dec3$G(_class$K = /*#__PURE__*/function (_MonsterMove) {
        _inheritsLoose(RangedMove, _MonsterMove);
        function RangedMove() {
          return _MonsterMove.apply(this, arguments) || this;
        }
        var _proto = RangedMove.prototype;
        _proto.onLoad = function onLoad() {
          var _MonsterMove$prototyp;
          this.State = this.getComponent(RangedState);
          (_MonsterMove$prototyp = _MonsterMove.prototype.onLoad) == null || _MonsterMove$prototyp.call(this);
        };
        return RangedMove;
      }(MonsterMove)) || _class$K) || _class$K) || _class$K);
      cclegacy._RF.pop();
      var _dec$L, _dec2$K, _dec3$H, _class$L;
      cclegacy._RF.push({}, "522beyPHmdCZYlHCs009E4M", "PlayerControl", undefined);
      var ccclass$L = _decorator.ccclass,
        menu$J = _decorator.menu,
        disallowMultiple$B = _decorator.disallowMultiple;
      var PlayerControl = (_dec$L = ccclass$L('PlayerControl'), _dec2$K = menu$J('Player/PlayerControl'), _dec3$H = disallowMultiple$B(true), _dec$L(_class$L = _dec2$K(_class$L = _dec3$H(_class$L = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerControl, _Component);
        function PlayerControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.Event = null;
          _this.LineEvent = null;
          // ===== 玩家动作处理函数 =====
          /**
           * 处理玩家移动
           * @param vec2 移动方向向量
           */
          _this.moveBinding = {
            event: 'control.move',
            callback: function callback(vec2) {
              // 如果玩家非空闲则不处理移动事件
              if (_this.State.moveState !== PlayerMoveStates.IDLE) {
                return;
              }
              _this.Event.emit('move', vec2);
            },
            tag: 'control'
          };
          /**
           * 处理放置锚点
           * @param vec2 锚点放置位置
           */
          _this.dropAnchorBinding = {
            event: 'control.dropAnchor',
            callback: function callback(vec2) {
              return gmVar().gameEvent.emit('gm.anchor.spawn', vec2);
            },
            tag: 'control'
          };
          /**
           * 处理玩家冲刺动作（向当前锚点冲刺），没锚点时尝试连接锚点并冲刺。
           */
          _this.dashBinding = {
            event: 'control.dash',
            callback: wrapAll([
            // 是否是空闲状态
            withChecker(function () {
              return _this.State.moveState === PlayerMoveStates.IDLE;
            }),
            // 尝试获取锚点
            withChecker(function () {
              var _this$State$nowAnchor;
              // 检查当前锚点是否非空
              if (!((_this$State$nowAnchor = _this.State.nowAnchor) != null && _this$State$nowAnchor.isValid)) {
                // 获取最近锚点
                var anchor = _this.findNearestAvailableAnchor(_this.node.worldPosition);
                // 有锚点切，没锚点不执行
                if (!anchor) {
                  return false;
                } else {
                  _this.Event.emit('control.rotate.switchAnchor', anchor);
                }
              }
              return true;
            }),
            // 再次检查锚点可用性
            withChecker(function () {
              var _this$State$nowAnchor2;
              return Boolean((_this$State$nowAnchor2 = _this.State.nowAnchor) == null ? void 0 : _this$State$nowAnchor2.isValid);
            })], function () {
              // 检查距离是否在最大冲刺距离内
              var playerPos = _this.node.worldPosition.toVec2();
              var anchorPos = _this.State.nowAnchor.worldPosition.toVec2();
              var distance = Vec2.distance(playerPos, anchorPos);
              if (distance <= _this.State.anchorBreakDistance) {
                // 向当前锚点冲刺
                _this.Event.emit('dash', anchorPos);
              }
            }),
            tag: 'control'
          };
          /**
           * 清空旋转中心的相对位置，保持旋转中心跟随实际节点
           */
          _this.handleclearRotateCenterRelativePos = function () {
            _this.State.rotateCenter.setPosition(0, 0);
          };
          /**
           * 处理只切换锚点（右键）
           * @param vec2 鼠标点击位置
           */
          _this.switchAnchorPosBinding = {
            event: 'control.switchAnchor',
            callback: function callback(vec2) {
              // 获取最近的可用锚点
              var nearestAnchor = _this.getNearestAvailableAnchor(vec2);
              if (!nearestAnchor) return;
              // 只切换连线锚点
              _this.Event.emit('control.rotate.switchAnchor', nearestAnchor);
            },
            tag: 'control'
          };
          /**
           * 检查锚点距离是否超出最大距离，并在超出时断开连接
           */
          _this.checkAnchorDistance = function () {
            var _this$State$nowAnchor3;
            if (!((_this$State$nowAnchor3 = _this.State.nowAnchor) != null && _this$State$nowAnchor3.isValid)) {
              return;
            }
            var distance = Vec2.distance(_this.node.worldPosition, _this.State.nowAnchor.worldPosition);
            if (distance > _this.State.anchorBreakDistance) {
              _this.Event.emit('control.rotate.disconnectAnchor');
            }
          };
          /**
           * 断开锚点
           */
          _this.disconnectAnchorBinding = {
            event: 'control.rotate.disconnectAnchor',
            callback: function callback() {
              // 停止连线
              _this.LineEvent.emit('draw.stop');
              // 断开锚点，传入回调在切换完成后执行
              _this.Event.emit('rotate.disconnectAnchor');
              // 修改状态
              _this.State.moveState = PlayerMoveStates.IDLE;
            },
            tag: 'control'
          };
          /**
           * 处理切换锚点
           * @param anchor 要切换到的锚点节点
           */
          _this.switchAnchorBinding = {
            event: 'control.rotate.switchAnchor',
            callback: function callback(anchor) {
              var _this$State$nowAnchor4, _this$State$lineEvent, _this$State$lineEvent2;
              // 切换的锚点是否和之前相同
              if (((_this$State$nowAnchor4 = _this.State.nowAnchor) == null ? void 0 : _this$State$nowAnchor4.uuid) === anchor.uuid) {
                // 相同触发冲刺
                _this.Event.emit('control.dash');
                return;
              }

              // 切换锚点
              _this.Event.emit('rotate.switchAnchor', anchor);
              // 切换连线终点
              (_this$State$lineEvent = _this.State.lineEvent) == null || _this$State$lineEvent.emit('switch.end', anchor);
              (_this$State$lineEvent2 = _this.State.lineEvent) == null || _this$State$lineEvent2.emit('draw.start');
            },
            tag: 'control'
          };
          // ===== 旋转动作处理函数 =====
          /**
           * 通用旋转处理函数
           * @param rotateState 旋转方向：'left' 或 'right'
           * @returns 处理旋转的函数
           */
          _this.handleRotate = function (rotateState) {
            return function () {
              if (_this.State.moveState === PlayerMoveStates.DASHING) {
                return;
              }
              // 再次同向旋转停止(公共的停止不能提取，应为stop会改变状态，改变后判断就相当于停了之后再执行)
              if (_this.State.rotateState === rotateState) {
                _this.Event.emit('rotate.stop');
              } else {
                _this.Event.emit('rotate.stop');
                _this.Event.emit("rotate." + rotateState);
              }
            };
          };
          /**
           * 处理向左旋转
           */
          _this.rotateLeftBinding = {
            event: 'control.rotate.left',
            callback: _this.handleRotate('left'),
            tag: 'control'
          };
          /**
           * 处理向右旋转
           */
          _this.rotateRightBinding = {
            event: 'control.rotate.right',
            callback: _this.handleRotate('right'),
            tag: 'control'
          };
          /**
           * 处理停止旋转
           */
          _this.rotateStopBinding = {
            event: 'control.rotate.stop',
            callback: function callback() {
              return _this.Event.emit('rotate.stop');
            },
            tag: 'control'
          };
          /**
           * 处理切换旋转中心
           * @param switchSelf 是否切换为自己作为中心
           */
          _this.rotateSwitchCenterBinding = {
            event: 'control.rotate.switchCenter',
            callback: function callback(switchSelf) {
              _this.Event.emit('rotate.switchCenter', switchSelf);
            },
            tag: 'control'
          };
          // ===== 状态监听处理函数 =====
          /**
           * 生命值变化绑定
           */
          _this.healthChangeBinding = {
            event: 'control.hp.change',
            callback: sthrottle(function (_ref) {
              var new_value = _ref.new_value,
                max_value = _ref.max_value;
              _this.State.healthBar.progress = clamp$1(new_value / max_value, 0, 1);
              _this.State.healthRatioLabel.handleRefreshRatio(new_value, max_value);
            }, 100),
            tag: 'control'
          };
          /**
           * 转发生命值变化
           */
          _this.healthForwardBinding = {
            atom: function atom() {
              return _this.State._health;
            },
            callback: function callback(health) {
              gmVar().gameEvent.emit('playerState.change.health.health', health);
              _this.Event.emit('control.hp.change', {
                new_value: health,
                old_value: health,
                max_value: _this.State.maxHealth
              });
            },
            tag: 'forward'
          };
          /**
           * 处理生命值归零的状态监听
           */
          _this.healthZeroBinding = {
            event: 'control.hp.zero',
            callback: function callback() {
              return _this.Event.emit('death.willDie');
            },
            tag: 'control'
          };
          /**
           * 生命值归零状态监听绑定
           */
          _this.healthZeroAtomBinding = {
            atom: function atom() {
              return _this.State._health;
            },
            callback: function callback(health) {
              if (health === 0) {
                _this.Event.emit('control.hp.zero');
              }
            },
            tag: 'atom'
          };
          /**
           * 处理受到伤害事件
           */
          _this.damageBinding = {
            event: 'control.damage.damage',
            callback: function callback(damage) {
              return _this.Event.emit('damage.damage', damage);
            },
            tag: 'control'
          };
          // ===== 战斗相关处理函数 =====
          /**
           * 处理线段碰撞造成的伤害
           * @param otherCollider 碰撞的怪物碰撞器
           */
          _this.handleLineDamage = function (otherCollider) {
            var _otherCollider$getCom;
            (_otherCollider$getCom = otherCollider.getComponent(MonsterEventCmp)) == null || _otherCollider$getCom.emit('damage', _this.State.lineTotalDamage);
          };
          // ===== 经验值和等级处理函数 =====
          /**
           * 增加经验值事件绑定
           */
          _this.addExpBinding = {
            event: 'control.exp.add',
            callback: function callback(exp) {
              return _this.Event.emit('exp.add', exp);
            },
            tag: 'control'
          };
          /**
           * 经验值变化状态监听绑定
           */
          _this.expChangeBinding = {
            atom: function atom() {
              return _this.State._exp;
            },
            callback: function callback(exp) {
              _this.Event.emit('control.exp.change', exp);
              gmVar().gameEvent.emit('playerState.change.exp.exp', exp);
              _this.Event.emit('exp.add', exp);
            },
            tag: 'atom'
          };
          /**
           * 处理升级事件
           */
          _this.levelUpBinding = {
            event: 'control.level.up',
            callback: function callback(lv) {
              _this.Event.emit('level.up', lv);
              // 最大生命值增加
              _this.State.maxHealth += _this.State.maxHealthAdd;
              _this.State.health += _this.State.maxHealthAdd;
            },
            tag: 'control'
          };
          /**
           * 等级变化状态监听绑定
           */
          _this.levelChangeBinding = {
            atom: function atom() {
              return _this.State._level;
            },
            callback: function callback(level) {
              return gmVar().gameEvent.emit('playerState.change.level.level', level);
            },
            tag: 'atom'
          };
          // ===== 其他状态监听处理函数 =====
          /**
           * 线段总伤害值变化状态监听绑定
           */
          _this.lineTotalDamageBinding = {
            atom: function atom() {
              return _this.State._lineTotalDamage;
            },
            callback: function callback(lineTotalDamage) {
              gmVar().gameEvent.emit('playerState.change.line.totalDamage', lineTotalDamage);
            },
            tag: 'atom'
          };
          /**
           * 移动速度变化状态监听绑定
           */
          _this.moveSpeedBinding = {
            atom: function atom() {
              return _this.State._moveSpeed;
            },
            callback: function callback(moveSpeed) {
              gmVar().gameEvent.emit('playerState.change.move.moveSpeed', moveSpeed);
            },
            tag: 'atom'
          };
          /**
           * 旋转速度变化状态监听绑定
           */
          _this.rotateSpeedBinding = {
            atom: function atom() {
              return _this.State._rotateSpeed;
            },
            callback: function callback(rotateSpeed) {
              gmVar().gameEvent.emit('playerState.change.rotate.rotateSpeed', rotateSpeed);
            },
            tag: 'atom'
          };
          /**
           * 处理恢复系数变化的状态监听
           */
          _this.healReduceChange = function () {
            gmVar().gameEvent.emit('playerState.change.healMulti.change', {
              add: _this.State.recoveryAdd,
              multi: _this.State.recoveryMultiply
            });
          };
          /**
           * 恢复系数add变化状态监听绑定
           */
          _this.healReduceAddBinding = {
            atom: function atom() {
              return _this.State._recoveryAdd;
            },
            callback: function callback() {
              return _this.healReduceChange();
            },
            tag: 'atom'
          };
          /**
           * 恢复系数multi变化状态监听绑定
           */
          _this.healReduceMultiBinding = {
            atom: function atom() {
              return _this.State._recoveryMultiply;
            },
            callback: function callback() {
              return _this.healReduceChange();
            },
            tag: 'atom'
          };
          /**
           * 处理减伤系数变化的状态监听
           */
          _this.damageReduceChange = function () {
            gmVar().gameEvent.emit('playerState.change.damageReduce.change', {
              add: _this.State.defenseAdd,
              multi: _this.State.defenseMultiply
            });
          };
          /**
           * 减伤系数add变化状态监听绑定
           */
          _this.damageReduceAddBinding = {
            atom: function atom() {
              return _this.State._defenseAdd;
            },
            callback: function callback() {
              return _this.damageReduceChange();
            },
            tag: 'atom'
          };
          /**
           * 减伤系数multi变化状态监听绑定
           */
          _this.damageReduceMultiBinding = {
            atom: function atom() {
              return _this.State._defenseMultiply;
            },
            callback: function callback() {
              return _this.damageReduceChange();
            },
            tag: 'atom'
          };
          // ===== 旋转准备扇形区域 =====
          /**
           * 结束旋转，创建扇形区域并自动切换旋转中心
           */
          _this.rotateEndBinding = {
            event: 'rotate.endRotate',
            callback: function callback(context) {
              var startAngle = context.startAngle,
                sweepAngle = context.sweepAngle;
              // 太小的旋转角度不处理
              if (Math.abs(sweepAngle) < 3) {
                return;
              }

              // 中心点
              var center = _this.State.rotateCenter.worldPosition;
              // 半径
              var radius = Vec2.distance(center, _this.State.rotateEdge.worldPosition);
              // 创建扇形区域
              gmVar().gameEvent.emit('sector.create', {
                center: center,
                radius: radius,
                startAngle: startAngle,
                rotateAngle: sweepAngle,
                tag: _this.State.fanType,
                group: RigidBodyGroup.MONSTER_PROP,
                duration: _this.State.fanDuration
              });

              // TEMP 自动切换旋转中心,临时放这边，后期再想办法
              _this.Event.emit('rotate.switchCenter');
            },
            tag: 'control'
          };
          /**
           * 死亡事件绑定
           */
          _this.deathWillDieBinding = {
            event: 'control.death.willDie',
            callback: function callback() {
              return _this.Event.emit('death.willDie');
            },
            tag: 'control'
          };
          return _this;
        }
        var _proto = PlayerControl.prototype;
        // ===== 生命周期方法 =====
        /**
         * 组件初始化，获取必要的事件组件和状态组件
         */
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(PlayerState);
          this.Event = this.State.event;
          this.LineEvent = this.State.lineEvent;
        }

        /**
         * 组件启用时注册所有玩家控制事件监听
         */;
        _proto.onEnable = function onEnable() {
          var _this2 = this;
          // 自动注册所有 Player 事件监听
          autoRegisterPlayerListeners(this);

          // 自动注册所有 Atom 监听
          autoRegisterAtomListeners(this);

          // 线碰怪造成伤害（LineEvent 需要手动注册）
          this.LineEvent.on('collider.Monster.start', this.handleLineDamage);

          // 超出范围断开锚点
          this.schedule(this.checkAnchorDistance, this.State.anchorBreakCheckInterval, macro.REPEAT_FOREVER);

          // TEMP 保持旋转中心居中
          this.scheduleOnce(function () {
            return _this2.schedule(_this2.handleclearRotateCenterRelativePos, 0, macro.REPEAT_FOREVER);
          }, 0.5);
        }

        /**
         * 组件禁用时注销所有事件监听
         */;
        _proto.onDisable = function onDisable() {
          // 自动注销所有 Player 事件监听
          autoUnregisterPlayerListeners(this);

          // 自动注销所有 Atom 监听
          autoUnregisterAtomListeners(this);

          // 线碰怪造成伤害（LineEvent 需要手动注销）
          this.LineEvent.off('collider.Monster.start', this.handleLineDamage);

          // 超出范围断开锚点
          this.unschedule(this.checkAnchorDistance);

          // TEMP 保持旋转中心居中
          this.unschedule(this.handleclearRotateCenterRelativePos);
        };
        /**
         * 获取最近的可用锚点，可连接
         */
        _proto.findNearestAvailableAnchor = function findNearestAvailableAnchor(point) {
          // 找到最近的锚点
          return getNearestPoint(gmVar().anchorContainer.children.filter(function (node) {
            return node.isValid && node.active;
          }), {
            x: point.x,
            y: point.y
          }, function (a, b) {
            return Vec2.distance({
              x: a.worldPositionX,
              y: a.worldPositionY
            }, b);
          });
        };
        // ===== 辅助函数 =====
        /**
         * 获取最近的可用锚点
         * @param point 参考点位置
         * @returns 在冲刺距离内的最近锚点，否则返回undefined
         */
        _proto.getNearestAvailableAnchor = function getNearestAvailableAnchor(point) {
          // 找到最近的锚点
          var nearestAnchor = this.findNearestAvailableAnchor(point);
          // 如果没有找到锚点，则返回 undefined
          if (nearestAnchor) {
            // 计算与指定坐标距离
            var distance = Vec2.distance(point, nearestAnchor.worldPosition.toVec2());
            // 计算自身距离
            var selfDistance = Vec2.distance(this.node.worldPosition, nearestAnchor.worldPosition);
            // 检查是否在锚点最大链接范围内，并且在自身距离范围内
            if (distance <= this.State.maxAnchorDistance && selfDistance <= this.State.anchorBreakDistance) {
              return nearestAnchor;
            }
          }
        };
        return PlayerControl;
      }(Component)) || _class$L) || _class$L) || _class$L);
      cclegacy._RF.pop();
      var _dec$M, _dec2$L, _dec3$I, _class$M;
      cclegacy._RF.push({}, "52bccOOb1NIJaJWMSRiZ8Ik", "PlayerDash", undefined);
      var ccclass$M = _decorator.ccclass,
        menu$K = _decorator.menu,
        disallowMultiple$C = _decorator.disallowMultiple;
      var PlayerDash = (_dec$M = ccclass$M('PlayerDash'), _dec2$L = menu$K('Player/PlayerDash'), _dec3$I = disallowMultiple$C(true), _dec$M(_class$M = _dec2$L(_class$M = _dec3$I(_class$M = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerDash, _Component);
        function PlayerDash() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          /**
           * 处理冲刺事件
           */
          _this.handleDash = function (point) {
            if (!point) {
              return;
            }

            // 计算距离
            var distance = Vec2.distance(_this.node.worldPosition.toVec2(), point);
            // 设置玩家状态为冲刺状态
            _this.State.moveState = PlayerMoveStates.DASHING;
            hackTween(_this.node).to(distance / _this.State.dashSpeedMultiplier, {
              worldPosition: point.toVec3()
            }).call(function () {
              return (/* 冲刺结束，返回 idle 状态*/
                _this.State.moveState = PlayerMoveStates.IDLE
              );
            }).start();
          };
          return _this;
        }
        var _proto = PlayerDash.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(PlayerState);
        };
        _proto.onEnable = function onEnable() {
          var _this$State$event;
          // 监听来自控制层的冲刺事件
          (_this$State$event = this.State.event) == null || _this$State$event.on('dash', this.handleDash, this);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event2;
          // 取消监听冲刺事件
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('dash', this.handleDash, this);
        };
        return PlayerDash;
      }(Component)) || _class$M) || _class$M) || _class$M);
      cclegacy._RF.pop();
      var _dec$N, _dec2$M, _dec3$J, _class$N;
      cclegacy._RF.push({}, "80734fs/7FEtoetRB4B7wZY", "PlayerDeath", undefined);
      var ccclass$N = _decorator.ccclass,
        menu$L = _decorator.menu,
        disallowMultiple$D = _decorator.disallowMultiple;

      /**
       * 死亡钩子函数接口
       */

      var PlayerDeath = (_dec$N = ccclass$N('PlayerDeath'), _dec2$M = menu$L('Player/PlayerDeath'), _dec3$J = disallowMultiple$D(true), _dec$N(_class$N = _dec2$M(_class$N = _dec3$J(_class$N = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerDeath, _Component);
        function PlayerDeath() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.log = new LogBuilder();
          /**
           * 存储死亡前钩子函数的数组
           */
          _this.deathHooks = [];
          /**
           * 标记是否正在处理死亡事件，防止重复触发
           */
          _this.isDying = false;
          /**
           * 处理即将死亡事件
           */
          _this.handleWillDie = function () {
            _this.log.Method('handleWillDie');

            // 如果已经在死亡流程中，则忽略
            if (!_this.isDying) {
              _this.isDying = true;

              // 按优先级顺序执行所有钩子函数
              for (var _iterator = _createForOfIteratorHelperLoose(_this.deathHooks), _step; !(_step = _iterator()).done;) {
                var hook = _step.value;
                var result = hook.execute();
                // 如果任何一个钩子函数返回false，则中断死亡流程
                if (!result) {
                  _this.interruptDeath();
                  return;
                }
              }
              // 所有钩子都允许继续，触发实际死亡事件
              _this.State.event.emit('death.die');
            }
          };
          /**
           * 处理实际死亡事件
           */
          _this.handleDie = function () {
            if (!_this.isDying) {
              // 如果不是通过willDie流程触发的die事件，直接处理
              _this.isDying = true;
            }
            _this.scheduleOnce(_this.node.destroy.bind(_this.node), 0.5);

            // 重置死亡状态
            _this.isDying = false;
          };
          return _this;
        }
        var _proto = PlayerDeath.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
          this.State = this.getComponent(PlayerState);
        };
        _proto.onEnable = function onEnable() {
          // 监听死亡事件
          this.State.event.on('death.willDie', this.handleWillDie);
          this.State.event.on('death.die', this.handleDie);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event, _this$State$event2;
          (_this$State$event = this.State.event) == null || _this$State$event.off('death.willDie', this.handleWillDie);
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('death.die', this.handleDie);
        }

        /**
         * 注册死亡前钩子函数
         * @param hook 钩子函数
         */;
        _proto.registerDeathHook = function registerDeathHook(hook) {
          var _this2 = this;
          // 包装原始函数
          var execute = function execute() {
            return fromThrowable(hook.originalFunction, function (error) {
              return _this2.log.error("death hook execution error: " + error);
            })().unwrapOr(true);
          };
          var newHook = _extends({}, hook, {
            execute: execute
          });
          this.deathHooks.push(newHook);
          // 按优先级从高到低排序
          this.deathHooks.sort(function (a, b) {
            return b.priority - a.priority;
          });
        }

        /**
         * 注销死亡前钩子函数
         * @param hook 钩子函数
         */;
        _proto.unregisterDeathHook = function unregisterDeathHook(hook) {
          // 找到并移除该钩子
          var index = this.deathHooks.findIndex(function (h) {
            return h.originalFunction === hook;
          });
          if (index >= 0) {
            this.deathHooks.splice(index, 1);
          }
        }

        /**
         * 阻断当前死亡事件
         */;
        _proto.interruptDeath = function interruptDeath() {
          this.isDying = false;
          // 可以在这里添加其他需要重置的状态
        };

        return PlayerDeath;
      }(Component)) || _class$N) || _class$N) || _class$N);
      cclegacy._RF.pop();
      var _dec$O, _dec2$N, _dec3$K, _class$O;
      cclegacy._RF.push({}, "faee1mZWB1FvKXGXu8XC7Cn", "PlayerLevel", undefined);
      var ccclass$O = _decorator.ccclass,
        menu$M = _decorator.menu,
        disallowMultiple$E = _decorator.disallowMultiple;
      var PlayerLevel = (_dec$O = ccclass$O('PlayerLevel'), _dec2$N = menu$M('Player/PlayerLevel'), _dec3$K = disallowMultiple$E(true), _dec$O(_class$O = _dec2$N(_class$O = _dec3$K(_class$O = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerLevel, _Component);
        function PlayerLevel() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _this.handleChangeExp = function () {
            // 遍历检查能满足几个等级
            for (var _iterator = _createForOfIteratorHelperLoose(_this.State.levelExpArray.slice(_this.State.level)), _step; !(_step = _iterator()).done;) {
              var needExp = _step.value;
              if (_this.State.exp >= needExp) {
                _this.State.level++;
                _this.State.exp -= needExp;
                _this.State.event.emit('control.level.up', _this.State.level);
              } else {
                break;
              }
            }
          };
          return _this;
        }
        var _proto = PlayerLevel.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(PlayerState);

          // DEBUG_TEST: 测试经验增加
          // this.scheduleOnce(
          //     () => {
          //         this.State.exp += 5000;
          //     },
          //     0.2,
          // );
        };

        _proto.onEnable = function onEnable() {
          // 监听经验获取事件
          this.State.event.on('exp.add', this.handleChangeExp);
        };
        _proto.onDisable = function onDisable() {
          this.State.event.off('exp.add', this.handleChangeExp);
        };
        return PlayerLevel;
      }(Component)) || _class$O) || _class$O) || _class$O);
      cclegacy._RF.pop();
      var _dec$P, _dec2$O, _dec3$L, _dec4$p, _dec5$l, _dec6$g, _dec7$b, _class$P, _class2$j, _descriptor$j, _descriptor2$i;
      cclegacy._RF.push({}, "43089oZR1JLO50bq+OT6CA2", "PlayerMove", undefined);
      var ccclass$P = _decorator.ccclass,
        menu$N = _decorator.menu,
        disallowMultiple$F = _decorator.disallowMultiple,
        property$k = _decorator.property;
      var PlayerMove = (_dec$P = ccclass$P('PlayerMove'), _dec2$O = menu$N('Player/PlayerMove'), _dec3$L = disallowMultiple$F(true), _dec4$p = property$k({
        tooltip: '输入缓冲区大小'
      }), _dec5$l = property$k(CCInteger), _dec6$g = property$k({
        tooltip: '输入有效时间（帧）'
      }), _dec7$b = property$k(CCInteger), _dec$P(_class$P = _dec2$O(_class$P = _dec3$L(_class$P = (_class2$j = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerMove, _Component);
        function PlayerMove() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.State = null;
          _initializerDefineProperty(_this, "bufferSize", _descriptor$j, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "inputLifetime", _descriptor2$i, _assertThisInitialized(_this));
          _this.inputBuffer = new _cjsExports$4(Array, _this.bufferSize);
          /**
           * 处理移动事件
           * @param direction 移动方向向量
           */
          _this.handleMove = function (direction) {
            // 将输入添加到缓冲区
            _this.addInputToBuffer(direction);

            // 根据缓冲区中的输入计算实际移动向量
            var movement = _this.calculateMovementVector();

            // 应用移动
            var rigidBody = _this.State.colliderAble.RigidBody;
            rigidBody.linearVelocity = movement.multiplyScalar(_this.State.moveSpeed);
          };
          return _this;
        }
        var _proto = PlayerMove.prototype;
        _proto.onLoad = function onLoad() {
          this.State = this.getComponent(PlayerState);
        };
        _proto.onEnable = function onEnable() {
          var _this$State$event;
          // 监听移动事件
          (_this$State$event = this.State.event) == null || _this$State$event.on('move', this.handleMove);
        };
        _proto.onDisable = function onDisable() {
          var _this$State$event2;
          (_this$State$event2 = this.State.event) == null || _this$State$event2.off('move', this.handleMove);
        }

        /**
         * 将新的输入添加到循环缓冲区
         * @param direction 输入方向向量
         */;
        _proto.addInputToBuffer = function addInputToBuffer(direction) {
          var now = director.getTotalFrames();
          this.inputBuffer.push({
            direction: direction.clone(),
            timestamp: now
          });
        }

        /**
         * 根据缓冲区中的输入计算移动向量
         * @returns 标准化的移动向量
         */;
        _proto.calculateMovementVector = function calculateMovementVector() {
          var _this2 = this;
          var sum = Vec2.ZERO.clone();
          this.inputBuffer.toArray().filter(function (input) {
            return input.timestamp + _this2.inputLifetime > director.getTotalFrames();
          }).forEach(function (input) {
            return sum.add(input.direction);
          });
          return sum.normalize();
        };
        return PlayerMove;
      }(Component), (_descriptor$j = _applyDecoratedDescriptor(_class2$j.prototype, "bufferSize", [_dec4$p, _dec5$l], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 4;
        }
      }), _descriptor2$i = _applyDecoratedDescriptor(_class2$j.prototype, "inputLifetime", [_dec6$g, _dec7$b], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 10;
        }
      })), _class2$j)) || _class$P) || _class$P) || _class$P);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "83ab7RO+zZHR54SCW8qOaS6", "macro", undefined);
      var temp_quat_1 = new Quat();
      Quat.fromEuler(temp_quat_1, 0, 0, 0);
      var ZERO_QUAT = temp_quat_1.clone();
      cclegacy._RF.pop();
      var _dec$Q, _dec2$P, _dec3$M, _class$Q;
      cclegacy._RF.push({}, "2c5b7ruaEtMPbBksaDEIUp/", "PlayerRotate", undefined);
      var ccclass$Q = _decorator.ccclass,
        menu$O = _decorator.menu,
        disallowMultiple$G = _decorator.disallowMultiple;

      // 状态机上下文类型

      // 状态机事件类型

      // 创建状态机
      var rotateMachine = setup({
        types: {
          context: {},
          events: {},
          input: {}
        },
        actions: {
          清除速度: function 清除速度(_ref) {
            var context = _ref.context;
            // console.info('动作-清除速度');
            var state = context.state;
            clearAllSpeed(state);
          },
          向右转: function 向右转(_ref2) {
            var context = _ref2.context;
            // console.info('动作-向右转');
            handleRotate(context.state, PlayerRotateStates.RIGHT);
          },
          向左转: function 向左转(_ref3) {
            var context = _ref3.context;
            // console.info('动作-向左转');
            handleRotate(context.state, PlayerRotateStates.LEFT);
          },
          停止旋转: function 停止旋转(_ref4) {
            var context = _ref4.context;
            // console.info('动作-停止旋转');
            handleStopRotate(context.state);
          },
          交换旋转中心: function 交换旋转中心(_ref5) {
            var context = _ref5.context;
            // console.info('动作-交换旋转中心');
            handleSwitchCenter(context.state, false);
          },
          断开连接: function 断开连接(_ref6) {
            var context = _ref6.context;
            // console.info('动作-断开连接');
            var state = context.state;
            handleSwitchAnchor(state, null);
          },
          切换锚点: function 切换锚点(_ref7) {
            var context = _ref7.context,
              event = _ref7.event;
            // console.info('动作-切换锚点');
            var state = context.state;
            handleSwitchAnchor(state, event.anchorNode);
          },
          计算当前旋转角度: function 计算当前旋转角度(_ref8) {
            var context = _ref8.context,
              event = _ref8.event;
            // console.info('动作-计算当前旋转角度');
            var state = context.state;
            context.dir = event.type === '向右转' ? PlayerRotateStates.RIGHT : PlayerRotateStates.LEFT;
            context.startAngle = getRotateAngle(state);
          },
          计算本次旋转角度: function 计算本次旋转角度(_ref9) {
            var _state$nowAnchor, _state$event;
            var context = _ref9.context;
            // console.info('动作-计算本次旋转角度');
            var state = context.state,
              dir = context.dir;
            var startAngle = context.startAngle;
            var now_angle = getRotateAngle(state);
            var rawDiff = now_angle - startAngle;
            var sign = dir === PlayerRotateStates.LEFT ? 1 : -1;
            var rotateAngle = sign * ((sign * rawDiff % 360 + 360) % 360);

            // TEMP FIX: 临时修复: 旋转中心在锚点时，起始角度需要反向
            if (((_state$nowAnchor = state.nowAnchor) == null ? void 0 : _state$nowAnchor.uuid) === state.rotateCenter.parent.uuid) {
              startAngle = 180 + startAngle;
            }
            (_state$event = state.event) == null || _state$event.emit('rotate.endRotate', {
              dir: context.dir,
              startAngle: startAngle,
              sweepAngle: rotateAngle
            });
          }
        }
      }).createMachine({
        context: function context(_ref10) {
          var input = _ref10.input;
          return {
            state: input.state,
            event: input.event,
            dir: input.dir,
            startAngle: input.startAngle
          };
        },
        id: 'rotate',
        initial: '空闲不可旋转',
        states: {
          空闲可旋转: {
            on: {
              向右转: {
                target: '旋转.右转'
              },
              向左转: {
                target: '旋转.左转'
              },
              断开连接: {
                target: '空闲不可旋转'
              },
              切换锚点: {
                actions: {
                  type: '切换锚点'
                }
              },
              切换旋转中心: {
                actions: {
                  type: '交换旋转中心'
                }
              }
            }
          },
          空闲不可旋转: {
            entry: [{
              type: '断开连接'
            }],
            on: {
              切换锚点: {
                target: '空闲可旋转',
                actions: [{
                  type: '切换锚点'
                }]
              }
            }
          },
          旋转: {
            initial: '左转',
            on: {
              断开连接: {
                target: '空闲不可旋转'
              },
              切换旋转中心: {
                target: '空闲可旋转',
                actions: [{
                  type: '交换旋转中心'
                }]
              },
              停止: {
                target: '空闲可旋转'
              },
              切换锚点: {
                target: '空闲可旋转',
                actions: [{
                  type: '切换锚点'
                }]
              }
            },
            entry: [{
              type: '清除速度'
            }],
            exit: {
              type: '停止旋转'
            },
            states: {
              左转: {
                on: {
                  向右转: {
                    target: '右转'
                  }
                },
                entry: [{
                  type: '向左转'
                }, {
                  type: '计算当前旋转角度'
                }],
                exit: {
                  type: '计算本次旋转角度'
                }
              },
              右转: {
                on: {
                  向左转: {
                    target: '左转'
                  }
                },
                entry: [{
                  type: '向右转'
                }, {
                  type: '计算当前旋转角度'
                }],
                exit: {
                  type: '计算本次旋转角度'
                }
              }
            }
          }
        }
      });

      /**
       * 清除所有速度
       */
      function clearAllSpeed(state) {
        var clearSpeed = function clearSpeed(node) {
          if (!(node != null && node.isValid)) {
            return;
          }
          var rigidBody = node.getComponent(RigidBody2D);
          if (rigidBody) {
            rigidBody.angularVelocity = 0;
            rigidBody.linearVelocity = Vec2.ZERO.clone();
          }
        };
        clearSpeed(state.rotateCenter);
        clearSpeed(state.rotateEdge);
        clearSpeed(state.rotateCenter.parent);
        state.rotateCenter.worldRotation = ZERO_QUAT;
      }

      /**
       * 旋转
       * @param angleSpeed 旋转速度（度/秒）
       */
      function handleRotate(State, direction) {
        // 计算关节锚点位置
        State.rotateCenter.position = Vec3.ZERO.clone();
        var centerPos = State.rotateCenter.worldPosition.clone();
        var edgePos = State.rotateEdge.worldPosition;
        var diff = centerPos.subtract(edgePos);
        State.rotateCenterJoint.connectedAnchor = diff.toVec2();

        // 启用关节
        State.rotateCenterJoint.enabled = true;
        State.rotateCenterJoint.apply();

        // 开始旋转
        var angleSpeed = direction === PlayerRotateStates.LEFT ? -State.rotateSpeed : State.rotateSpeed;
        State.rotateCenterRigidBody.angularVelocity = toRadian(angleSpeed);
      }
      function handleStopRotate(State) {
        State.rotateCenterJoint.enabled = false;
        clearAllSpeed(State);
      }
      function handleSwitchCenter(State, switchSelf) {
        var _center$getComponent;
        // 确定当前状态
        var center = switchSelf ? State.nowAnchor : State.rotateCenter.parent;
        var edge = switchSelf ? State.node : State.rotateEdge;
        // 交换中心点和边缘点
        State.rotateCenter.setParent(edge);
        State.rotateCenter.position = Vec3.ZERO.clone();
        State.rotateEdge = center;
        State.rotateCenterJoint.connectedBody = (_center$getComponent = center == null ? void 0 : center.getComponent(RigidBody2D)) != null ? _center$getComponent : null;
      }
      function handleSwitchAnchor(State, node) {
        State.nowAnchor = node;
        handleSwitchCenter(State, true);
      }

      /**
       * 获取当前线的旋转夹角
       * @returns 旋转夹角，单位：角度
       */
      function getRotateAngle(State) {
        // const edge = this.State.rotateEdge!.worldPosition;
        // const center = this.State.rotateCenter.parent!.worldPosition;
        // const diff = { x: edge.x - center.x, y: edge.y - center.y };
        // return zRotFromVec(diff);
        // TEMP FIX: 临时修复: 使用固定玩家-锚点计算角度。同时要求后续使用时，假如出现锚点-玩家的时候，需要手动反向。测试结果起始角度需要反向
        var edge = State.nowAnchor.worldPosition;
        var center = State.node.worldPosition;
        var diff = {
          x: edge.x - center.x,
          y: edge.y - center.y
        };
        return zRotFromVec(diff);
      }
      var PlayerRotate = (_dec$Q = ccclass$Q('PlayerRotate'), _dec2$P = menu$O('Player/PlayerRotate'), _dec3$M = disallowMultiple$G(true), _dec$Q(_class$Q = _dec2$P(_class$Q = _dec3$M(_class$Q = /*#__PURE__*/function (_Component) {
        _inheritsLoose(PlayerRotate, _Component);
        function PlayerRotate() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.log = new LogBuilder();
          _this.State = null;
          _this.Event = null;
          _this.actor = null;
          _this.handleRotateLeft = function () {
            _this.actor.send({
              type: '向左转'
            });
          };
          _this.handleRotateRight = function () {
            _this.actor.send({
              type: '向右转'
            });
          };
          _this.handleStopRotate = function () {
            _this.actor.send({
              type: '停止'
            });
          };
          _this.handleSwitchCenter = function (switchSelf) {
            _this.actor.send({
              type: '切换旋转中心',
              switchSelf: switchSelf
            });
          };
          _this.handleSwitchAnchor = function (node) {
            _this.actor.send({
              type: '切换锚点',
              anchorNode: node
            });
          };
          _this.handleDisconnectAnchor = function () {
            _this.actor.send({
              type: '断开连接'
            });
          };
          /**
           * 同步 xstate 状态到 PlayerState.rotateState
           */
          _this.syncRotateState = function (snapshot) {
            var currentState = snapshot.value;

            // this.log.info(`xstate 状态：${currentState}`);

            // 将 xstate 状态映射到 PlayerState 的 rotateState
            if (typeof currentState === 'string') {
              // 简单状态：空闲可旋转、空闲不可旋转
              _this.State.rotateState = PlayerRotateStates.STOP;
              _this.State.moveState = PlayerMoveStates.IDLE;
            } else {
              // 嵌套状态：旋转.左转、旋转.右转
              if (currentState.旋转 === '左转') {
                _this.State.rotateState = PlayerRotateStates.LEFT;
                _this.State.moveState = PlayerMoveStates.ROTATING;
              } else if (currentState.旋转 === '右转') {
                _this.State.rotateState = PlayerRotateStates.RIGHT;
                _this.State.moveState = PlayerMoveStates.ROTATING;
              } else {
                _this.State.rotateState = PlayerRotateStates.STOP;
                _this.State.moveState = PlayerMoveStates.IDLE;
              }
            }
          };
          return _this;
        }
        var _proto = PlayerRotate.prototype;
        _proto.onLoad = function onLoad() {
          this.log.This(this);
          this.State = this.getComponent(PlayerState);
          this.Event = gmVar().playerEvent;
        };
        _proto.onEnable = function onEnable() {
          var input = {
            state: this.State,
            event: this.Event,
            dir: PlayerRotateStates.LEFT,
            startAngle: 0
          };

          // 启动状态机

          this.actor = createActor(rotateMachine, {
            input: input
          });

          // 监听旋转控制事件
          this.Event.on('rotate.left', this.handleRotateLeft);
          this.Event.on('rotate.right', this.handleRotateRight);
          this.Event.on('rotate.stop', this.handleStopRotate);
          this.Event.on('rotate.switchCenter', this.handleSwitchCenter);
          this.Event.on('rotate.switchAnchor', this.handleSwitchAnchor);
          this.Event.on('rotate.disconnectAnchor', this.handleDisconnectAnchor);

          // 订阅状态机状态变化，同步到 PlayerState
          this.actor.subscribe(this.syncRotateState);
          this.actor.start();
        };
        _proto.onDisable = function onDisable() {
          // 取消监听旋转控制事件
          this.Event.off('rotate.left', this.handleRotateLeft);
          this.Event.off('rotate.right', this.handleRotateRight);
          this.Event.off('rotate.stop', this.handleStopRotate);
          this.Event.off('rotate.switchCenter', this.handleSwitchCenter);
          this.Event.off('rotate.switchAnchor', this.handleSwitchAnchor);
          this.Event.off('rotate.disconnectAnchor', this.handleDisconnectAnchor);

          // 停止状态机
          this.actor.stop();
        };
        return PlayerRotate;
      }(Component)) || _class$Q) || _class$Q) || _class$Q);
      cclegacy._RF.pop();
      var _dec$R, _dec2$Q, _dec3$N, _dec4$q, _class$R, _class2$k, _descriptor$k;
      cclegacy._RF.push({}, "a5b3cx+hKdDf6Wp+fxKjQWI", "ExpPropControl", undefined);
      var ccclass$R = _decorator.ccclass,
        property$l = _decorator.property,
        menu$P = _decorator.menu,
        disallowMultiple$H = _decorator.disallowMultiple;
      var ExpPropControl = (_dec$R = ccclass$R('ExpPropControl'), _dec2$Q = menu$P('Prop/ExpPropControl'), _dec3$N = disallowMultiple$H(true), _dec4$q = property$l({
        tooltip: '经验值'
      }), _dec$R(_class$R = _dec2$Q(_class$R = _dec3$N(_class$R = (_class2$k = /*#__PURE__*/function (_Component) {
        _inheritsLoose(ExpPropControl, _Component);
        function ExpPropControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "expAmount", _descriptor$k, _assertThisInitialized(_this));
          _this.colliderAble = null;
          _this.onTriggerEnter = function (_selfCollider, otherCollider, _contact) {
            // 获取玩家事件组件
            var state = otherCollider.node.getComponent(PlayerState);
            // 玩家经验增加
            state.exp += _this.expAmount;
            // 销毁道具
            _this.scheduleOnce(_this.destroySelf);
          };
          // 销毁自身
          _this.destroySelf = function () {
            if (_this.isValid) {
              _this.node.destroy();
            }
          };
          return _this;
        }
        var _proto = ExpPropControl.prototype;
        _proto.onLoad = function onLoad() {
          this.colliderAble = this.getComponent(ColliderAble);
        };
        _proto.onEnable = function onEnable() {
          this.colliderAble.on('collider.Player.start', this.onTriggerEnter);
        };
        _proto.onDisable = function onDisable() {
          this.colliderAble.off('collider.Player.start', this.onTriggerEnter);
        };
        return ExpPropControl;
      }(Component), _descriptor$k = _applyDecoratedDescriptor(_class2$k.prototype, "expAmount", [_dec4$q], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 50;
        }
      }), _class2$k)) || _class$R) || _class$R) || _class$R);
      cclegacy._RF.pop();
      var _dec$S, _dec2$R, _dec3$O, _dec4$r, _class$S, _class2$l, _descriptor$l;
      cclegacy._RF.push({}, "306c6w6fS9IJ6ExsTYRXM0O", "HealPropControl", undefined);
      var ccclass$S = _decorator.ccclass,
        property$m = _decorator.property,
        menu$Q = _decorator.menu,
        disallowMultiple$I = _decorator.disallowMultiple;
      var HealPropControl = (_dec$S = ccclass$S('HealPropControl'), _dec2$R = menu$Q('Prop/HealPropControl'), _dec3$O = disallowMultiple$I(true), _dec4$r = property$m({
        tooltip: '回血量'
      }), _dec$S(_class$S = _dec2$R(_class$S = _dec3$O(_class$S = (_class2$l = /*#__PURE__*/function (_Component) {
        _inheritsLoose(HealPropControl, _Component);
        function HealPropControl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "healAmount", _descriptor$l, _assertThisInitialized(_this));
          _this.colliderAble = null;
          _this.onTriggerEnter = function (_selfCollider, otherCollider, _contact) {
            // 获取玩家事件组件
            var playerEvent = otherCollider.node.getComponent(PlayerEventCmp);
            if (playerEvent) {
              // 触发玩家回血事件
              playerEvent.emit('damage.heal', _this.healAmount);

              // 销毁道具
              _this.scheduleOnce(_this.destroySelf);
            }
          };
          // 销毁自身
          _this.destroySelf = function () {
            if (_this.isValid) {
              _this.node.destroy();
            }
          };
          return _this;
        }
        var _proto = HealPropControl.prototype;
        _proto.onLoad = function onLoad() {
          this.colliderAble = this.getComponent(ColliderAble);
        };
        _proto.onEnable = function onEnable() {
          this.colliderAble.on('collider.Player.start', this.onTriggerEnter);
        };
        _proto.onDisable = function onDisable() {
          this.colliderAble.off('collider.Player.start', this.onTriggerEnter);
        };
        return HealPropControl;
      }(Component), _descriptor$l = _applyDecoratedDescriptor(_class2$l.prototype, "healAmount", [_dec4$r], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 50;
        }
      }), _class2$l)) || _class$S) || _class$S) || _class$S);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "f154cTm1V1AHrdqZguMuLWT", "AsyncUtils.test", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "27968iDVJBBy6laALM64wHu", "ES6Feature.test", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "fa5ecavg4dJuoVihT5GyXNA", "NodeEventSystem.test", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "e5dd3EkZkBIgpglr+r7tLsu", "NotificationPanel.test", undefined);
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "ac185vU7SRMxK2jP1ioxU/v", "ProxyManager", undefined);
      /**
       * 代理管理器 - 支持对象代理、属性监听、条件触发和生命周期钩子
       *
       * @example
       * ```typescript
       * const target = { name: 'Alice', age: 25 };
       * const proxy = ProxyManager.create(target);
       *
       * // 监听属性变化
       * proxy.on('age').change((newValue, oldValue) => {
       *   console.log(`年龄从 ${oldValue} 变为 ${newValue}`);
       * });
       *
       * // 条件触发 - 当属性等于特定值时
       * proxy.on('age').when(30).before((newValue, oldValue) => {
       *   console.log('即将变为30岁！');
       * });
       *
       * // 条件触发 - 当属性改变时
       * proxy.on('age').whenChanged((newValue, oldValue) => {
       *   console.log('年龄已改变');
       * });
       *
       * // 生命周期钩子
       * proxy.on('age').before((newValue, oldValue) => {
       *   console.log(`年龄即将改变: ${oldValue} -> ${newValue}`);
       * });
       *
       * proxy.on('age').after((newValue, oldValue) => {
       *   console.log(`年龄已改变: ${oldValue} -> ${newValue}`);
       * });
       *
       * proxy.age = 30; // 触发所有符合条件的监听器
       * ```
       */
      var PropertyWatcher = /*#__PURE__*/function () {
        function PropertyWatcher(property, proxy) {
          this.listeners = [];
          this.property = void 0;
          this.proxy = void 0;
          this.conditions = [];
          this.property = property;
          this.proxy = proxy;
        }

        /**
         * 添加前置回调
         */
        var _proto = PropertyWatcher.prototype;
        _proto.before = function before(callback) {
          this.listeners.push({
            before: callback,
            condition: this.createCompositeCondition()
          });
          return this;
        }

        /**
         * 添加后置回调
         */;
        _proto.after = function after(callback) {
          this.listeners.push({
            after: callback,
            condition: this.createCompositeCondition()
          });
          return this;
        }

        /**
         * 当属性等于特定值时触发
         */;
        _proto.when = function when(expectedValue) {
          this.conditions.push(function (newValue) {
            return newValue === expectedValue;
          });
          return this;
        }

        /**
         * 当属性值改变时触发（值不相等）
         */;
        _proto.whenChanged = function whenChanged() {
          this.conditions.push(function (newValue, oldValue) {
            return newValue !== oldValue;
          });
          return this;
        }

        /**
         * 添加自定义条件
         */;
        _proto.whenCondition = function whenCondition(condition) {
          this.conditions.push(condition);
          return this;
        }

        /**
         * 添加变化监听器（等价于 after + whenChanged）
         */;
        _proto.change = function change(callback) {
          this.conditions.push(function (newValue, oldValue) {
            return newValue !== oldValue;
          });
          this.listeners.push({
            after: callback,
            condition: this.createCompositeCondition()
          });
          return this;
        }

        /**
         * 创建组合条件（所有条件都必须满足）
         */;
        _proto.createCompositeCondition = function createCompositeCondition() {
          var conditions = [].concat(this.conditions);
          return function (newValue, oldValue, property, target) {
            return conditions.every(function (condition) {
              return condition(newValue, oldValue, property, target);
            });
          };
        }

        /**
         * 注册监听器
         */;
        _proto.register = function register(listener) {
          this.listeners.push(listener);
        }

        /**
         * 获取所有监听器
         */;
        _proto.getListeners = function getListeners() {
          return this.listeners;
        }

        /**
         * 获取所有条件
         */;
        _proto.getConditions = function getConditions() {
          return this.conditions;
        };
        return PropertyWatcher;
      }();
      var ProxyManager = /*#__PURE__*/function () {
        function ProxyManager(target) {
          this.target = void 0;
          this.proxy = void 0;
          this.listeners = new Map();
          this.target = target;
          this.proxy = this.createProxy();
        }

        /**
         * 创建代理对象
         */
        ProxyManager.create = function create(target) {
          return new ProxyManager(target);
        }

        /**
         * 获取代理对象
         */;
        var _proto2 = ProxyManager.prototype;
        _proto2.getProxy = function getProxy() {
          return this.proxy;
        }

        /**
         * 获取原始对象
         */;
        _proto2.getTarget = function getTarget() {
          return this.target;
        }

        /**
         * 监听指定属性
         */;
        _proto2.on = function on(property) {
          var propKey = String(property);
          if (!this.listeners.has(propKey)) {
            this.listeners.set(propKey, []);
          }
          var watcher = new PropertyWatcher(propKey, this);
          this.listeners.get(propKey).push(watcher);
          return watcher;
        }

        /**
         * 移除所有属性的所有监听器
         */;
        _proto2.removeAllListeners = function removeAllListeners() {
          this.listeners.clear();
        }

        /**
         * 移除指定属性的所有监听器
         */;
        _proto2.removePropertyListeners = function removePropertyListeners(property) {
          this.listeners.delete(property);
        }

        /**
         * 获取属性的所有监听器
         */;
        _proto2.getPropertyListeners = function getPropertyListeners(property) {
          return this.listeners.get(property) || [];
        }

        /**
         * 创建 Proxy 对象
         */;
        _proto2.createProxy = function createProxy() {
          var self = this;
          return new Proxy(this.target, {
            get: function get(target, property, receiver) {
              var value = Reflect.get(target, property, receiver);

              // 如果是函数，绑定到原始对象
              if (typeof value === 'function') {
                return value.bind(target);
              }
              return value;
            },
            set: function set(target, property, value, receiver) {
              var oldValue = Reflect.get(target, property, receiver);

              // 触发 before 钩子
              self.triggerBefore(property, value, oldValue);

              // 执行设置操作
              var result = Reflect.set(target, property, value, receiver);

              // 触发 after 钩子
              self.triggerAfter(property, value, oldValue);
              return result;
            },
            deleteProperty: function deleteProperty(target, property) {
              var oldValue = Reflect.get(target, property);

              // 触发 before 钩子
              self.triggerBefore(property, undefined, oldValue);

              // 执行删除操作
              var result = Reflect.deleteProperty(target, property);

              // 触发 after 钩子
              self.triggerAfter(property, undefined, oldValue);
              return result;
            }
          });
        }

        /**
         * 触发 before 钩子
         */;
        _proto2.triggerBefore = function triggerBefore(property, newValue, oldValue) {
          var _this = this;
          var watchers = this.listeners.get(property);
          if (!watchers) return;
          watchers.forEach(function (watcher) {
            watcher.getListeners().forEach(function (listener) {
              if (_this.shouldTrigger(listener, newValue, oldValue, property)) {
                listener.before == null || listener.before(newValue, oldValue, property, _this.target);
              }
            });
          });
        }

        /**
         * 触发 after 钩子
         */;
        _proto2.triggerAfter = function triggerAfter(property, newValue, oldValue) {
          var _this2 = this;
          var watchers = this.listeners.get(property);
          if (!watchers) return;
          watchers.forEach(function (watcher) {
            watcher.getListeners().forEach(function (listener) {
              if (_this2.shouldTrigger(listener, newValue, oldValue, property)) {
                listener.after == null || listener.after(newValue, oldValue, property, _this2.target);
              }
            });
          });
        }

        /**
         * 判断是否应该触发监听器
         */;
        _proto2.shouldTrigger = function shouldTrigger(listener, newValue, oldValue, property) {
          if (!listener.condition) {
            return true;
          }
          return listener.condition(newValue, oldValue, property, this.target);
        };
        return ProxyManager;
      }();

      /**
       * 便捷函数：快速创建代理对象
       */
      function createProxy(target) {
        return ProxyManager.create(target);
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "11a66O+DblME7ULHLbvn56E", "ProxyManager.test", undefined);

      /**
       * 测试 1: 基础属性监听
       */
      function test1_BasicPropertyWatch() {
        console.info('📝 测试 1: 基础属性监听');
        var obj = {
          name: 'Test',
          value: 0
        };
        var proxy = createProxy(obj);
        proxy.on('value').change(function (newValue, oldValue) {
          console.info("  \u2713 value \u53D8\u5316: " + oldValue + " -> " + newValue);
        });
        proxy.getProxy().value = 1;
        proxy.getProxy().value = 2;
        proxy.getProxy().value = 2; // 不应触发

        console.info('');
      }

      /**
       * 测试 2: before/after 钩子
       */
      function test2_BeforeAfterHooks() {
        console.info('📝 测试 2: before/after 钩子');
        var obj = {
          counter: 0
        };
        var proxy = createProxy(obj);
        proxy.on('counter').before(function (newValue, oldValue) {
          console.info("  [before] " + oldValue + " -> " + newValue);
        });
        proxy.on('counter').after(function (newValue, oldValue) {
          console.info("  [after] " + oldValue + " -> " + newValue);
        });
        proxy.getProxy().counter = 5;
        console.info('');
      }

      /**
       * 测试 3: when 条件触发
       */
      function test3_WhenCondition() {
        console.info('📝 测试 3: when 条件触发');
        var obj = {
          state: 'idle',
          attempts: 0
        };
        var proxy = createProxy(obj);

        // 当 state 变为 'active' 时触发
        proxy.on('state').when('active').after(function (newValue) {
          console.info("  \u2713 state \u53D8\u4E3A 'active'");
        });
        proxy.on('state').when('inactive').after(function () {
          console.info("  \u2713 state \u53D8\u4E3A 'inactive'");
        });
        proxy.getProxy().state = 'active'; // 触发
        proxy.getProxy().state = 'paused'; // 不触发
        proxy.getProxy().state = 'inactive'; // 触发

        console.info('');
      }

      /**
       * 测试 4: whenChanged 触发
       */
      function test4_WhenChanged() {
        console.info('📝 测试 4: whenChanged 触发');
        var obj = {
          score: 0
        };
        var proxy = createProxy(obj);
        proxy.on('score').whenChanged().after(function (newValue, oldValue) {
          console.info("  \u2713 score \u6539\u53D8: " + oldValue + " -> " + newValue + " (+" + (newValue - oldValue) + ")");
        });
        proxy.getProxy().score = 10; // 触发
        proxy.getProxy().score = 10; // 不触发
        proxy.getProxy().score = 20; // 触发

        console.info('');
      }

      /**
       * 测试 5: 自定义条件
       */
      function test5_CustomCondition() {
        console.info('📝 测试 5: 自定义条件');
        var obj = {
          health: 100,
          maxHealth: 100
        };
        var proxy = createProxy(obj);

        // 当 health <= 30 时触发警告
        proxy.on('health').whenCondition(function (newValue) {
          return newValue <= 30;
        }).after(function (newValue) {
          console.info("  \u26A0\uFE0F  \u8B66\u544A\uFF1A\u751F\u547D\u503C\u8FC7\u4F4E (" + newValue + "/" + obj.maxHealth + ")");
        });

        // 当 health 归零时触发
        proxy.on('health').when(0).after(function () {
          console.info("  \uD83D\uDC80 \u89D2\u8272\u5DF2\u6B7B\u4EA1\uFF01");
        });
        proxy.getProxy().health = 80;
        proxy.getProxy().health = 30; // 警告
        proxy.getProxy().health = 20; // 警告
        proxy.getProxy().health = 0; // 死亡

        console.info('');
      }

      /**
       * 测试 6: 链式调用 - 组合条件
       */
      function test6_ChainedConditions() {
        console.info('📝 测试 6: 链式调用 - 组合条件');
        var obj = {
          level: 1,
          exp: 0
        };
        var proxy = createProxy(obj);

        // 当 level 改变时
        proxy.on('level').whenChanged().after(function (newValue, oldValue) {
          console.info("  \uD83C\uDF89 \u5347\u7EA7: Lv." + oldValue + " -> Lv." + newValue);
        });

        // 当 exp 等于特定值时
        proxy.on('exp').when(100).after(function () {
          console.info("  \u2713 exp \u8FBE\u5230 100");
        });
        proxy.getProxy().exp = 50;
        proxy.getProxy().exp = 100; // 触发 when(100)
        proxy.getProxy().level = 2; // 触发 whenChanged

        console.info('');
      }

      /**
       * 测试 7: 多属性同时监听
       */
      function test7_MultipleProperties() {
        console.info('📝 测试 7: 多属性同时监听');
        var player = {
          name: 'Player1',
          hp: 100,
          mp: 50,
          gold: 0
        };
        var proxy = createProxy(player);
        proxy.on('hp').change(function (newValue, oldValue) {
          console.info("  HP: " + oldValue + " -> " + newValue);
        });
        proxy.on('mp').change(function (newValue, oldValue) {
          console.info("  MP: " + oldValue + " -> " + newValue);
        });
        proxy.on('gold').change(function (newValue, oldValue) {
          console.info("  Gold: +" + (newValue - oldValue) + " (\u603B\u8BA1: " + newValue + ")");
        });
        console.info('  --- 战斗开始 ---');
        proxy.getProxy().hp = 90;
        proxy.getProxy().mp = 40;
        proxy.getProxy().gold = 10;
        proxy.getProxy().hp = 85;
        proxy.getProxy().hp = 85; // 不触发

        console.info('');
      }

      /**
       * 测试 8: 移除监听器
       */
      function test8_RemoveListeners() {
        console.info('📝 测试 8: 移除监听器');
        var obj = {
          counter: 0
        };
        var proxy = createProxy(obj);

        // 添加监听器
        proxy.on('counter').change(function () {
          console.info("  \u2713 \u76D1\u542C\u5668 1 \u89E6\u53D1");
        });
        proxy.on('counter').change(function () {
          console.info("  \u2713 \u76D1\u542C\u5668 2 \u89E6\u53D1");
        });
        console.info('  修改 counter = 1:');
        proxy.getProxy().counter = 1;

        // 移除监听器
        console.info('  移除 counter 的所有监听器...');
        proxy.removePropertyListeners('counter');
        console.info('  修改 counter = 2:');
        proxy.getProxy().counter = 2;
        console.info('  (无输出，因为监听器已被移除)');
        console.info('');
      }

      /**
       * 测试 9: 复杂游戏场景
       */
      function test9_ComplexGameScenario() {
        console.info('📝 测试 9: 复杂游戏场景');
        var gameState = {
          playerName: 'Hero',
          level: 1,
          hp: 100,
          maxHp: 100,
          exp: 0,
          isDead: false,
          isGameOver: false
        };
        var proxy = createProxy(gameState);

        // 死亡检测
        proxy.on('hp').when(0).after(function () {
          console.info("  \uD83D\uDC80 " + gameState.playerName + " \u5DF2\u6B7B\u4EA1\uFF01");
          proxy.getProxy().isDead = true;
        });

        // 游戏结束
        proxy.on('isGameOver').when(true).after(function () {
          console.info("  \uD83C\uDFAE \u6E38\u620F\u7ED3\u675F\uFF01");
        });

        // 生命值警告
        proxy.on('hp').whenChanged().after(function (newValue, oldValue) {
          var ratio = newValue / gameState.maxHp;
          if (ratio > 0 && ratio <= 0.3) {
            console.info("  \u26A0\uFE0F  \u751F\u547D\u503C\u4F4E\u4E8E 30%\uFF01");
          }
        });

        // 死亡时设置游戏结束
        proxy.on('isDead').when(true).after(function () {
          proxy.getProxy().isGameOver = true;
        });

        // 升级系统 (简化版)
        proxy.on('exp').whenCondition(function (newValue, oldValue) {
          // 每增加 100 exp 升级
          return Math.floor(newValue / 100) > Math.floor(oldValue / 100);
        }).after(function (newValue) {
          var newLevel = Math.floor(newValue / 100) + 1;
          console.info("  \uD83C\uDF89 \u5347\u7EA7\uFF01\u5F53\u524D\u7B49\u7EA7: Lv." + newLevel);
          proxy.getProxy().level = newLevel;
        });

        // 模拟游戏流程
        console.info('  --- 游戏开始 ---');
        console.info("  " + gameState.playerName + " \u5F00\u59CB\u5192\u9669 (Lv." + gameState.level + ")");
        proxy.getProxy().hp = 80;
        proxy.getProxy().exp = 50;
        console.info('  --- 遭遇战斗 ---');
        proxy.getProxy().hp = 30; // 生命值警告
        proxy.getProxy().exp = 120; // 升级！
        proxy.getProxy().hp = 20; // 生命值警告

        console.info('  --- 遭遇强敌 ---');
        proxy.getProxy().hp = 0; // 死亡，触发游戏结束

        console.info('');
      }

      /**
       * 运行所有测试
       */
      function runAllTests() {
        console.info('\n========================================');
        console.info('  ProxyManager 测试套件');
        console.info('========================================\n');
        test1_BasicPropertyWatch();
        test2_BeforeAfterHooks();
        test3_WhenCondition();
        test4_WhenChanged();
        test5_CustomCondition();
        test6_ChainedConditions();
        test7_MultipleProperties();
        test8_RemoveListeners();
        test9_ComplexGameScenario();
        console.info('========================================');
        console.info('  所有测试完成！');
        console.info('========================================\n');
      }

      // 如果直接运行此文件，执行所有测试
      if (typeof window === 'undefined') {
        // Node.js 环境
        runAllTests();
      }

      // 导出到全局（浏览器环境）
      if (typeof window !== 'undefined') {
        window.runProxyTests = runAllTests;
        window.ProxyTests = {
          test1_BasicPropertyWatch: test1_BasicPropertyWatch,
          test2_BeforeAfterHooks: test2_BeforeAfterHooks,
          test3_WhenCondition: test3_WhenCondition,
          test4_WhenChanged: test4_WhenChanged,
          test5_CustomCondition: test5_CustomCondition,
          test6_ChainedConditions: test6_ChainedConditions,
          test7_MultipleProperties: test7_MultipleProperties,
          test8_RemoveListeners: test8_RemoveListeners,
          test9_ComplexGameScenario: test9_ComplexGameScenario
        };
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "93a26ZP/llEd6MqmwmlOtAI", "SetSpread.test", undefined);
      /**
       * Set 展开语法测试文件（纯 JavaScript）
       *
       * 测试 JS 对 Set 的展开为 list 的效果，也就是使用 ... 展开 Set 的结果，
       * 对比 Array.from 的展开结果
       */

      // 测试结果统计
      var testResults = [];
      function assert(condition, testName, message) {
        testResults.push({
          name: testName,
          passed: condition,
          message: message
        });
      }

      // 测试 1: 基础展开对比
      function test1_BasicSpread() {
        console.info('\n📝 测试 1: 基础展开对比');
        var mySet = new Set([1, 2, 3, 4, 5]);
        console.info('  原始 Set:', mySet);
        var spreadArray = [].concat(mySet);
        console.info('  [...Set] 结果:', spreadArray);
        console.info('  [...Set] 类型:', Array.isArray(spreadArray) ? 'Array' : typeof spreadArray);
        var fromArray = Array.from(mySet);
        console.info('  Array.from(Set) 结果:', fromArray);
        console.info('  Array.from(Set) 类型:', Array.isArray(fromArray) ? 'Array' : typeof fromArray);
        var areEqual = spreadArray.join(',') === fromArray.join(',');
        var isCorrectLength = spreadArray.length === 5;
        var areAllNumbers = spreadArray.every(function (x) {
          return typeof x === 'number';
        });
        console.info('  两者是否相等:', areEqual);
        assert(areEqual && isCorrectLength && areAllNumbers, '基础展开对比', areEqual && isCorrectLength && areAllNumbers ? '✅ 测试通过' : '❌ 测试失败: 展开结果不正确');
      }

      // 测试 2: 包含重复元素的 Set
      function test2_SetWithDuplicates() {
        console.info('\n📝 测试 2: 包含重复元素的 Set');
        var setWithDuplicates = new Set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]);
        console.info('  原始数组: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]');
        console.info('  创建的 Set:', setWithDuplicates);
        var spreadDup = [].concat(setWithDuplicates);
        var fromDup = Array.from(setWithDuplicates);
        console.info('  [...Set]:', spreadDup);
        console.info('  Array.from(Set):', fromDup);
        console.info('  Set 自动去重后长度:', spreadDup.length);
        var isCorrectLength = spreadDup.length === 4;
        var hasUniqueElements = new Set(spreadDup).size === 4;
        var areEqual = spreadDup.join(',') === fromDup.join(',');
        assert(isCorrectLength && hasUniqueElements && areEqual, 'Set 自动去重', isCorrectLength && hasUniqueElements && areEqual ? '✅ 测试通过' : '❌ 测试失败: 去重不正确');
      }

      // 测试 3: 字符串 Set
      function test3_StringSet() {
        console.info('\n📝 测试 3: 字符串 Set');
        var stringSet = new Set(['apple', 'banana', 'cherry', 'apple']);
        console.info('  原始字符串 Set:', stringSet);
        var spreadStr = [].concat(stringSet);
        var fromStr = Array.from(stringSet);
        console.info('  [...Set]:', spreadStr);
        console.info('  Array.from(Set):', fromStr);
        var isCorrectLength = spreadStr.length === 3;
        var areAllStrings = spreadStr.every(function (x) {
          return typeof x === 'string';
        });
        var areEqual = spreadStr.join(',') === fromStr.join(',');
        assert(isCorrectLength && areAllStrings && areEqual, '字符串 Set 展开', isCorrectLength && areAllStrings && areEqual ? '✅ 测试通过' : '❌ 测试失败: 字符串展开不正确');
      }

      // 测试 4: 数组方法应用
      function test4_ArrayMethods() {
        console.info('\n📝 测试 4: 数组方法应用');
        var testSet = new Set([1, 2, 3, 4, 5]);
        console.info('  原始 Set:', testSet);

        // map 操作
        var spreadMap = [].concat(testSet).map(function (x) {
          return x * 2;
        });
        var fromMap = Array.from(testSet, function (x) {
          return x * 2;
        });
        console.info('  [...Set].map(x => x * 2):', spreadMap);
        console.info('  Array.from(Set, x => x * 2):', fromMap);
        var mapEqual = spreadMap.join(',') === fromMap.join(',');
        var mapCorrect = spreadMap.length === 5 && spreadMap[0] === 2;

        // filter 操作
        var spreadFilter = [].concat(testSet).filter(function (x) {
          return x > 2;
        });
        var fromFilter = Array.from(testSet).filter(function (x) {
          return x > 2;
        });
        console.info('  [...Set].filter(x > 2):', spreadFilter);
        console.info('  Array.from(Set).filter(x > 2):', fromFilter);
        var filterEqual = spreadFilter.join(',') === fromFilter.join(',');
        var filterCorrect = spreadFilter.length === 3 && spreadFilter.every(function (x) {
          return x > 2;
        });
        assert(mapEqual && mapCorrect && filterEqual && filterCorrect, '数组方法应用', mapEqual && mapCorrect && filterEqual && filterCorrect ? '✅ 测试通过' : '❌ 测试失败: 数组方法应用不正确');
      }

      // 测试 6: 空的 Set
      function test6_EmptySet() {
        console.info('\n📝 测试 6: 空的 Set');
        var emptySet = new Set();
        var spreadEmpty = [].concat(emptySet);
        var fromEmpty = Array.from(emptySet);
        console.info('  空的 Set:', emptySet);
        console.info('  [...Set]:', spreadEmpty);
        console.info('  Array.from(Set):', fromEmpty);
        console.info('  两者都为空数组:', spreadEmpty.length === 0 && fromEmpty.length === 0);
        var bothEmpty = spreadEmpty.length === 0 && fromEmpty.length === 0;
        assert(bothEmpty, '空 Set 展开', bothEmpty ? '✅ 测试通过' : '❌ 测试失败: 空 Set 展开不正确');
      }

      // 测试 7: 数组独立性
      function test7_ArrayIndependence() {
        console.info('\n📝 测试 7: 数组独立性');
        var originalSet = new Set([1, 2, 3]);
        var arr1 = [].concat(originalSet);
        var arr2 = Array.from(originalSet);
        arr1.push(4);
        arr2.push(5);
        console.info('  修改后的 [...Set]:', arr1);
        console.info('  修改后的 Array.from(Set):', arr2);
        console.info('  原始 Set:', originalSet);
        console.info('  原始 Set 不受影响:', originalSet.size === 3);
        var originalUnchanged = originalSet.size === 3;
        var arraysChanged = arr1.length === 4 && arr2.length === 4;
        assert(originalUnchanged && arraysChanged, '数组独立性', originalUnchanged && arraysChanged ? '✅ 测试通过' : '❌ 测试失败: 数组独立性不正确');
      }

      // 运行所有测试
      function runAllTests$1() {
        console.info('\n========================================');
        console.info('  Set 展开语法测试（js版）');
        console.info('  对比 [...Set] 和 Array.from(Set)');
        console.info('========================================');

        // 清空之前的测试结果
        testResults.length = 0;
        test1_BasicSpread();
        test2_SetWithDuplicates();
        test3_StringSet();
        test4_ArrayMethods();
        test6_EmptySet();
        test7_ArrayIndependence();

        // 统计测试结果
        var totalTests = testResults.length;
        var passedTests = testResults.filter(function (r) {
          return r.passed;
        }).length;
        var failedTests = totalTests - passedTests;
        var allPassed = failedTests === 0;
        console.info('\n========================================');
        console.info('  测试统计:');
        console.info("  \u603B\u8BA1: " + totalTests + " \u4E2A\u6D4B\u8BD5");
        console.info("  \u901A\u8FC7: " + passedTests + " \u4E2A " + (allPassed ? '✅' : ''));
        console.info("  \u5931\u8D25: " + failedTests + " \u4E2A " + (failedTests > 0 ? '❌' : ''));
        if (!allPassed) {
          console.info('\n  失败的测试:');
          testResults.filter(function (r) {
            return !r.passed;
          }).forEach(function (r) {
            console.info("  - " + r.name + ": " + r.message);
          });
        }
        console.info("\n  \u6700\u7EC8\u7ED3\u679C: " + (allPassed ? '✅ 所有测试通过！' : '❌ 部分测试失败！'));
        console.info('========================================\n');

        // 返回测试是否全部通过
        return allPassed;
      }

      // 将测试函数暴露到全局 Window 对象（浏览器环境）
      if (typeof window !== 'undefined') {
        window.SetSpreadTests = {
          test1_BasicSpread: test1_BasicSpread,
          test2_SetWithDuplicates: test2_SetWithDuplicates,
          test3_StringSet: test3_StringSet,
          test4_ArrayMethods: test4_ArrayMethods,
          test6_EmptySet: test6_EmptySet,
          test7_ArrayIndependence: test7_ArrayIndependence
        };
        window.runSetSpreadTests = runAllTests$1;
      }
      cclegacy._RF.pop();
      cclegacy._RF.push({}, "21cb0+mKqVAPbCM+q6Q4yvf", "SetSpread.test", undefined);
      cclegacy._RF.pop();
      var _dec$T, _dec2$S, _dec3$P, _class$T, _class2$m, _descriptor$m, _descriptor2$j;
      cclegacy._RF.push({}, "4f84bei5C9LNrkrVvohCezT", "FixedRotate", undefined);
      var ccclass$T = _decorator.ccclass,
        menu$R = _decorator.menu,
        disallowMultiple$J = _decorator.disallowMultiple,
        property$n = _decorator.property;
      var FixedRotate = (_dec$T = ccclass$T('FixedRotate'), _dec2$S = menu$R('UI/FixedRotate'), _dec3$P = disallowMultiple$J(true), _dec$T(_class$T = _dec2$S(_class$T = _dec3$P(_class$T = (_class2$m = /*#__PURE__*/function (_Component) {
        _inheritsLoose(FixedRotate, _Component);
        function FixedRotate() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "fixedRotate", _descriptor$m, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "fixedPosition", _descriptor2$j, _assertThisInitialized(_this));
          _this._tempVec3 = new Vec3();
          return _this;
        }
        var _proto = FixedRotate.prototype;
        _proto.onEnable = function onEnable() {
          this.node.getWorldRotation(this.fixedRotate);
          this.fixedPosition = this.node.getWorldPosition().subtract(this.node.parent.worldPosition);
        };
        _proto.lateUpdate = function lateUpdate() {
          this.node.parent.getWorldPosition(this._tempVec3);
          this.node.worldPosition = this._tempVec3.add(this.fixedPosition);
          this.node.worldRotation = this.fixedRotate;
        };
        return FixedRotate;
      }(Component), (_descriptor$m = _applyDecoratedDescriptor(_class2$m.prototype, "fixedRotate", [property$n], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Quat();
        }
      }), _descriptor2$j = _applyDecoratedDescriptor(_class2$m.prototype, "fixedPosition", [property$n], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec3();
        }
      })), _class2$m)) || _class$T) || _class$T) || _class$T);
      cclegacy._RF.pop();
      var _dec$U, _dec2$T, _class$U;
      cclegacy._RF.push({}, "620898TFv9MWr7aWbIQEuFf", "BaseState", undefined);
      var ccclass$U = _decorator.ccclass,
        disallowMultiple$K = _decorator.disallowMultiple;

      /**
       * 基础状态监听器接口
       */

      /**
       * 基础状态类，提供状态管理和监听功能
       *
       * @template T - 状态接口类型
       */
      var BaseState = (_dec$U = ccclass$U('BaseState'), _dec2$T = disallowMultiple$K(true), _dec$U(_class$U = _dec2$T(_class$U = /*#__PURE__*/function (_Component) {
        _inheritsLoose(BaseState, _Component);
        function BaseState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          // 使用字典存储所有状态
          _this.stateData = {};
          // 存储状态变更监听器，使用字典提高查找效率
          _this.stateListeners = {};
          return _this;
        }
        var _proto = BaseState.prototype;
        _proto.registerStateListener = function registerStateListener(propertyOrListener, condition, callback) {
          var result;
          // 判断是哪种调用方式
          if (typeof propertyOrListener === 'object') {
            // 第二种调用方式：传入监听器对象
            result = this._registerListenerWithObject(propertyOrListener);
          } else {
            // 第一种调用方式：传入三个参数
            result = this._registerListenerWithParameters(propertyOrListener, condition, callback);
          }
          return result;
        }

        /**
         * 使用监听器对象注册状态变更监听器
         * @param listener 监听器对象
         */;
        _proto._registerListenerWithObject = function _registerListenerWithObject(listener) {
          var property = listener.property;
          if (!this.stateListeners[property]) {
            this.stateListeners[property] = [];
          }
          this.stateListeners[property].push(listener);
          return listener;
        }

        /**
         * 使用三个参数注册状态变更监听器
         * @param property 监听的属性名
         * @param condition 判断是否应该触发回调的函数
         * @param callback 状态变更时触发的回调函数
         */;
        _proto._registerListenerWithParameters = function _registerListenerWithParameters(property, condition, callback) {
          if (!this.stateListeners[property]) {
            this.stateListeners[property] = [];
          }
          var listener = {
            condition: condition,
            callback: callback,
            property: property
          };
          this.stateListeners[property].push(listener);
          return listener;
        }

        /**
         * 移除状态变更监听器
         * @param listener 要移除的监听器
         */;
        _proto.removeStateListener = function removeStateListener(listener) {
          var listeners = this.stateListeners[listener.property];
          if (listeners) {
            var index = listeners.indexOf(listener);
            if (index >= 0) {
              listeners.splice(index, 1);
            }
          }
        }

        /**
         * 获取状态值
         * @param key 状态键名
         * @returns 对应的状态值
         */;
        _proto.get = function get(key) {
          return this.stateData[key];
        }

        /**
         * 设置状态值
         * @param key 状态键名
         * @param value 状态值
         */;
        _proto.set = function set(key, value) {
          var oldValue = this.stateData[key];
          this.stateData[key] = value;
          var listeners = this.stateListeners[key];
          if (listeners) {
            listeners.forEach(function (listener) {
              if (listener.condition(value, oldValue)) {
                listener.callback(value, oldValue);
              }
            });
          }
        };
        return BaseState;
      }(Component)) || _class$U) || _class$U);
      cclegacy._RF.pop();
      var _dec$V, _dec2$U, _dec3$Q, _dec4$s, _class$V, _class2$n, _descriptor$n, _descriptor2$k, _descriptor3$f;
      cclegacy._RF.push({}, "b282aW1kutKAqxXooJHP+wt", "MoveTrajectory", undefined);
      var ccclass$V = _decorator.ccclass,
        property$o = _decorator.property;
      var MoveTrajectory = (_dec$V = ccclass$V('MoveTrajectory'), _dec2$U = property$o({
        tooltip: '轨迹记录次数'
      }), _dec3$Q = property$o({
        tooltip: '记录间隔'
      }), _dec4$s = property$o({
        type: Node,
        tooltip: '目标节点'
      }), _dec$V(_class$V = (_class2$n = /*#__PURE__*/function (_Component) {
        _inheritsLoose(MoveTrajectory, _Component);
        function MoveTrajectory() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "trajectoryRecordTime", _descriptor$n, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "trajectoryInterval", _descriptor2$k, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "targetNode", _descriptor3$f, _assertThisInitialized(_this));
          _this._moveTrajectory = new _cjsExports$4(Array, _this.trajectoryRecordTime);
          /**
           * 记录目标位置
           */
          _this.recordTargetPosition = function () {
            var pos = _this.targetNode.worldPosition;
            // 记录目标位置
            _this._moveTrajectory.push({
              x: pos.x,
              y: pos.y,
              z: pos.z
            });
          };
          return _this;
        }
        var _proto = MoveTrajectory.prototype;
        _proto.onEnable = function onEnable() {
          var _this$targetNode;
          (_this$targetNode = this.targetNode) != null ? _this$targetNode : this.targetNode = this.node;
          this.schedule(this.recordTargetPosition, this.trajectoryInterval, macro.REPEAT_FOREVER);
        };
        _proto.onDisable = function onDisable() {
          this.unschedule(this.recordTargetPosition);
        };
        /**
         * 获取第一个轨迹
         */
        _proto.peekfisrtTrajectory = function peekfisrtTrajectory() {
          var firstTrajectory = this._moveTrajectory.peekFirst();
          return firstTrajectory ? ok(firstTrajectory) : err(this.node.uuid + "\u6CA1\u6709\u8BB0\u5F55\u8F68\u8FF9");
        };
        return MoveTrajectory;
      }(Component), (_descriptor$n = _applyDecoratedDescriptor(_class2$n.prototype, "trajectoryRecordTime", [_dec2$U], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 10;
        }
      }), _descriptor2$k = _applyDecoratedDescriptor(_class2$n.prototype, "trajectoryInterval", [_dec3$Q], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.1;
        }
      }), _descriptor3$f = _applyDecoratedDescriptor(_class2$n.prototype, "targetNode", [_dec4$s], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$n)) || _class$V);
      cclegacy._RF.pop();
      var _dec$W, _dec2$V, _dec3$R, _dec4$t, _dec5$m, _dec6$h, _dec7$c, _class$W, _class2$o, _descriptor$o, _descriptor2$l, _descriptor3$g, _descriptor4$c;
      cclegacy._RF.push({}, "63445ASuCxDS5O+Xun/NlBT", "ExhaustTrail", undefined);
      var ccclass$W = _decorator.ccclass,
        property$p = _decorator.property,
        requireComponent$6 = _decorator.requireComponent,
        menu$S = _decorator.menu;

      /**
       * 尾焰发射组件
       * 基于轨迹记录，在物体两侧朝后发射粒子
       */
      var ExhaustTrail = (_dec$W = ccclass$W('ExhaustTrail'), _dec2$V = menu$S('Utils/ExhaustTrail'), _dec3$R = requireComponent$6(MoveTrajectory), _dec4$t = property$p({
        tooltip: '移动轨迹组件引用',
        type: MoveTrajectory
      }), _dec5$m = property$p({
        tooltip: '粒子发射间隔（秒）'
      }), _dec6$h = property$p({
        tooltip: '两侧距离'
      }), _dec7$c = property$p({
        tooltip: '需要用于计算的轨迹点数量'
      }), _dec$W(_class$W = _dec2$V(_class$W = _dec3$R(_class$W = (_class2$o = /*#__PURE__*/function (_Component) {
        _inheritsLoose(ExhaustTrail, _Component);
        function ExhaustTrail() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "moveTrajectory", _descriptor$o, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "emitInterval", _descriptor2$l, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "sideDistance", _descriptor3$g, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "trajectorySampleCount", _descriptor4$c, _assertThisInitialized(_this));
          _this._leftParticleSystem = null;
          _this._rightParticleSystem = null;
          return _this;
        }
        var _proto = ExhaustTrail.prototype;
        _proto.onLoad = function onLoad() {
          this.moveTrajectory = this.getComponent(MoveTrajectory);
          this._leftParticleSystem = this.createParticleSystems('左侧粒子发射器');
          this._rightParticleSystem = this.createParticleSystems('右侧粒子发射器');
        };
        _proto.onEnable = function onEnable() {
          // 启用粒子系统
          this._leftParticleSystem.playOnLoad = true;
          this._rightParticleSystem.playOnLoad = true;

          // 更新粒子系统位置和朝向
          this.schedule(this.updateParticleSystems, this.emitInterval, macro.REPEAT_FOREVER);
        };
        _proto.onDisable = function onDisable() {
          // 禁用粒子系统
          this._leftParticleSystem.playOnLoad = false;
          this._rightParticleSystem.playOnLoad = false;
          this.unschedule(this.updateParticleSystems);
        }

        /**
         * 创建粒子系统
         */;
        _proto.createParticleSystems = function createParticleSystems(name) {
          // 创建左侧粒子发射器节点
          var Emitter = this.node.getChildByName(name) || new Node(name);
          this.node.addChild(Emitter);
          var particleSystem = Emitter.getComponent(ParticleSystem2D) || Emitter.addComponent(ParticleSystem2D);
          particleSystem.playOnLoad = false;
          particleSystem.duration = -1; // 持续发射

          return particleSystem;
        }

        /**
         * 更新粒子系统的位置和朝向
         */;
        _proto.updateParticleSystems = function updateParticleSystems() {
          var _this2 = this;
          var moveDir = this.calculateMoveDirection();
          if (!moveDir) {
            return;
          }
          var sideDir = this.calSideDir(moveDir);
          var updateParticleSystems = function updateParticleSystems(system, dir) {
            // 设置粒子系统位置
            var pos = {
              x: 0,
              y: 0,
              z: 0
            };
            Vec3.multiplyScalar(pos, sideDir, dir * _this2.sideDistance);
            system.node.setPosition(pos.x, pos.y, pos.z);
            // 粒子系统朝向（向移动方向）
            _this2.updateParticleSystemAngle(system, moveDir);
          };

          // 更新左侧粒子系统
          updateParticleSystems(this._leftParticleSystem, -1);
          // 更新右侧粒子系统
          updateParticleSystems(this._rightParticleSystem, 1);
        }

        /**
         * 更新粒子系统的角度
         * @param particleSystem 粒子系统
         * @param moveDirection 移动方向
         */;
        _proto.updateParticleSystemAngle = function updateParticleSystemAngle(particleSystem, moveDirection) {
          // 计算向后发射的角度（基于 XY 平面）
          var angleDeg = Math.atan2(-moveDirection.y, -moveDirection.x) * (180 / Math.PI);
          particleSystem.angle = angleDeg;
        }

        /**
         * 计算移动方向
         * @returns 移动方向的单位向量
         */;
        _proto.calculateMoveDirection = function calculateMoveDirection() {
          var trajectory = this.moveTrajectory._moveTrajectory;
          if (trajectory.size >= 2) {
            // 使用最近的几个点计算平均方向（从末尾获取最新点）
            var direction = {
              x: 0,
              y: 0,
              z: 0
            };
            var sampleCount = Math.min(trajectory.size, this.trajectorySampleCount);

            // 从末尾开始获取最新的点
            for (var i = 0; i < sampleCount - 1; i++) {
              var next = trajectory.get(trajectory.size - 1 - i);
              var current = trajectory.get(trajectory.size - 2 - i);
              if (current && next) {
                var tempDir = {
                  x: 0,
                  y: 0,
                  z: 0
                };
                Vec3.subtract(tempDir, next, current);
                Vec3.normalize(tempDir, tempDir);
                Vec3.add(direction, direction, tempDir);
              }
            }
            Vec3.normalize(direction, direction);
            return direction;
          }
        }

        /**
         * 计算侧向方向（垂直于移动方向，2D XY平面）
         * @param moveDirection 移动方向
         * @returns 侧向方向的单位向量
         */;
        _proto.calSideDir = function calSideDir(moveDirection) {
          // 2D XY平面中，正交方向为 (y, -x)
          var sideDirection = {
            x: moveDirection.y,
            y: -moveDirection.x,
            z: 0
          };

          // 归一化
          Vec3.normalize(sideDirection, sideDirection);
          return sideDirection;
        };
        return ExhaustTrail;
      }(Component), (_descriptor$o = _applyDecoratedDescriptor(_class2$o.prototype, "moveTrajectory", [_dec4$t], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$l = _applyDecoratedDescriptor(_class2$o.prototype, "emitInterval", [_dec5$m], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.05;
        }
      }), _descriptor3$g = _applyDecoratedDescriptor(_class2$o.prototype, "sideDistance", [_dec6$h], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.5;
        }
      }), _descriptor4$c = _applyDecoratedDescriptor(_class2$o.prototype, "trajectorySampleCount", [_dec7$c], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 3;
        }
      })), _class2$o)) || _class$W) || _class$W) || _class$W);
      cclegacy._RF.pop();
    }
  };
});

(function(r) {
  r('virtual:///prerequisite-imports/main', 'chunks:///main.js'); 
})(function(mid, cid) {
    System.register(mid, [cid], function (_export, _context) {
    return {
        setters: [function(_m) {
            var _exportObj = {};

            for (var _key in _m) {
              if (_key !== "default" && _key !== "__esModule") _exportObj[_key] = _m[_key];
            }
      
            _export(_exportObj);
        }],
        execute: function () { }
    };
    });
});
//# sourceMappingURL=index.js.map