var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// ../../node_modules/tseep/lib/types.js
var require_types = __commonJS({
  "../../node_modules/tseep/lib/types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// ../../node_modules/tseep/lib/task-collection/utils.js
var require_utils = __commonJS({
  "../../node_modules/tseep/lib/task-collection/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._fast_remove_single = void 0;
    function _fast_remove_single(arr, index) {
      if (index === -1)
        return;
      if (index === 0)
        arr.shift();
      else if (index === arr.length - 1)
        arr.length = arr.length - 1;
      else
        arr.splice(index, 1);
    }
    exports2._fast_remove_single = _fast_remove_single;
  }
});

// ../../node_modules/tseep/lib/task-collection/bake-collection.js
var require_bake_collection = __commonJS({
  "../../node_modules/tseep/lib/task-collection/bake-collection.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.bakeCollectionVariadic = exports.bakeCollectionAwait = exports.bakeCollection = exports.BAKED_EMPTY_FUNC = void 0;
    exports.BAKED_EMPTY_FUNC = function() {
    };
    var FORLOOP_FALLBACK = 1500;
    function generateArgsDefCode(numArgs) {
      var argsDefCode2 = "";
      if (numArgs === 0)
        return argsDefCode2;
      for (var i = 0; i < numArgs - 1; ++i) {
        argsDefCode2 += "arg" + String(i) + ", ";
      }
      argsDefCode2 += "arg" + String(numArgs - 1);
      return argsDefCode2;
    }
    function generateBodyPartsCode(argsDefCode2, collectionLength) {
      var funcDefCode2 = "", funcCallCode2 = "";
      for (var i = 0; i < collectionLength; ++i) {
        funcDefCode2 += "var f".concat(i, " = collection[").concat(i, "];\n");
        funcCallCode2 += "f".concat(i, "(").concat(argsDefCode2, ")\n");
      }
      return { funcDefCode: funcDefCode2, funcCallCode: funcCallCode2 };
    }
    function generateBodyPartsVariadicCode(collectionLength) {
      var funcDefCode2 = "", funcCallCode2 = "";
      for (var i = 0; i < collectionLength; ++i) {
        funcDefCode2 += "var f".concat(i, " = collection[").concat(i, "];\n");
        funcCallCode2 += "f".concat(i, ".apply(undefined, arguments)\n");
      }
      return { funcDefCode: funcDefCode2, funcCallCode: funcCallCode2 };
    }
    function bakeCollection(collection, fixedArgsNum) {
      if (collection.length === 0)
        return exports.BAKED_EMPTY_FUNC;
      else if (collection.length === 1)
        return collection[0];
      var funcFactoryCode;
      if (collection.length < FORLOOP_FALLBACK) {
        var argsDefCode = generateArgsDefCode(fixedArgsNum);
        var _a = generateBodyPartsCode(argsDefCode, collection.length), funcDefCode = _a.funcDefCode, funcCallCode = _a.funcCallCode;
        funcFactoryCode = "(function(collection) {\n            ".concat(funcDefCode, "\n            collection = undefined;\n            return (function(").concat(argsDefCode, ") {\n                ").concat(funcCallCode, "\n            });\n        })");
      } else {
        var argsDefCode = generateArgsDefCode(fixedArgsNum);
        if (collection.length % 10 === 0) {
          funcFactoryCode = "(function(collection) {\n                return (function(".concat(argsDefCode, ") {\n                    for (var i = 0; i < collection.length; i += 10) {\n                        collection[i](").concat(argsDefCode, ");\n                        collection[i+1](").concat(argsDefCode, ");\n                        collection[i+2](").concat(argsDefCode, ");\n                        collection[i+3](").concat(argsDefCode, ");\n                        collection[i+4](").concat(argsDefCode, ");\n                        collection[i+5](").concat(argsDefCode, ");\n                        collection[i+6](").concat(argsDefCode, ");\n                        collection[i+7](").concat(argsDefCode, ");\n                        collection[i+8](").concat(argsDefCode, ");\n                        collection[i+9](").concat(argsDefCode, ");\n                    }\n                });\n            })");
        } else if (collection.length % 4 === 0) {
          funcFactoryCode = "(function(collection) {\n                return (function(".concat(argsDefCode, ") {\n                    for (var i = 0; i < collection.length; i += 4) {\n                        collection[i](").concat(argsDefCode, ");\n                        collection[i+1](").concat(argsDefCode, ");\n                        collection[i+2](").concat(argsDefCode, ");\n                        collection[i+3](").concat(argsDefCode, ");\n                    }\n                });\n            })");
        } else if (collection.length % 3 === 0) {
          funcFactoryCode = "(function(collection) {\n                return (function(".concat(argsDefCode, ") {\n                    for (var i = 0; i < collection.length; i += 3) {\n                        collection[i](").concat(argsDefCode, ");\n                        collection[i+1](").concat(argsDefCode, ");\n                        collection[i+2](").concat(argsDefCode, ");\n                    }\n                });\n            })");
        } else {
          funcFactoryCode = "(function(collection) {\n                return (function(".concat(argsDefCode, ") {\n                    for (var i = 0; i < collection.length; ++i) {\n                        collection[i](").concat(argsDefCode, ");\n                    }\n                });\n            })");
        }
      }
      {
        var bakeCollection_1 = void 0;
        var fixedArgsNum_1 = void 0;
        var bakeCollectionVariadic_1 = void 0;
        var bakeCollectionAwait_1 = void 0;
        var funcFactory = eval(funcFactoryCode);
        return funcFactory(collection);
      }
    }
    exports.bakeCollection = bakeCollection;
    function bakeCollectionAwait(collection, fixedArgsNum) {
      if (collection.length === 0)
        return exports.BAKED_EMPTY_FUNC;
      else if (collection.length === 1)
        return collection[0];
      var funcFactoryCode;
      if (collection.length < FORLOOP_FALLBACK) {
        var argsDefCode = generateArgsDefCode(fixedArgsNum);
        var _a = generateBodyPartsCode(argsDefCode, collection.length), funcDefCode = _a.funcDefCode, funcCallCode = _a.funcCallCode;
        funcFactoryCode = "(function(collection) {\n            ".concat(funcDefCode, "\n            collection = undefined;\n            return (function(").concat(argsDefCode, ") {\n                return Promise.all([ ").concat(funcCallCode, " ]);\n            });\n        })");
      } else {
        var argsDefCode = generateArgsDefCode(fixedArgsNum);
        funcFactoryCode = "(function(collection) {\n            return (function(".concat(argsDefCode, ") {\n                var promises = Array(collection.length);\n                for (var i = 0; i < collection.length; ++i) {\n                    promises[i] = collection[i](").concat(argsDefCode, ");\n                }\n                return Promise.all(promises);\n            });\n        })");
      }
      {
        var bakeCollection_2 = void 0;
        var fixedArgsNum_2 = void 0;
        var bakeCollectionVariadic_2 = void 0;
        var bakeCollectionAwait_2 = void 0;
        var funcFactory = eval(funcFactoryCode);
        return funcFactory(collection);
      }
    }
    exports.bakeCollectionAwait = bakeCollectionAwait;
    function bakeCollectionVariadic(collection) {
      if (collection.length === 0)
        return exports.BAKED_EMPTY_FUNC;
      else if (collection.length === 1)
        return collection[0];
      var funcFactoryCode;
      if (collection.length < FORLOOP_FALLBACK) {
        var _a = generateBodyPartsVariadicCode(collection.length), funcDefCode = _a.funcDefCode, funcCallCode = _a.funcCallCode;
        funcFactoryCode = "(function(collection) {\n            ".concat(funcDefCode, "\n            collection = undefined;\n            return (function() {\n                ").concat(funcCallCode, "\n            });\n        })");
      } else {
        funcFactoryCode = "(function(collection) {\n            return (function() {\n                for (var i = 0; i < collection.length; ++i) {\n                    collection[i].apply(undefined, arguments);\n                }\n            });\n        })";
      }
      {
        var bakeCollection_3 = void 0;
        var fixedArgsNum = void 0;
        var bakeCollectionVariadic_3 = void 0;
        var bakeCollectionAwait_3 = void 0;
        var funcFactory = eval(funcFactoryCode);
        return funcFactory(collection);
      }
    }
    exports.bakeCollectionVariadic = bakeCollectionVariadic;
  }
});

// ../../node_modules/tseep/lib/task-collection/task-collection.js
var require_task_collection = __commonJS({
  "../../node_modules/tseep/lib/task-collection/task-collection.js"(exports2) {
    "use strict";
    var __spreadArray = exports2 && exports2.__spreadArray || function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TaskCollection = void 0;
    var utils_1 = require_utils();
    var bake_collection_1 = require_bake_collection();
    function push_norebuild(a, b) {
      var len = this.length;
      if (len > 1) {
        if (b) {
          var _a2;
          (_a2 = this._tasks).push.apply(_a2, arguments);
          this.length += arguments.length;
        } else {
          this._tasks.push(a);
          this.length++;
        }
      } else {
        if (b) {
          if (len === 1) {
            var newAr = Array(1 + arguments.length);
            newAr.push(newAr);
            newAr.push.apply(newAr, arguments);
            this._tasks = newAr;
          } else {
            var newAr = Array(arguments.length);
            newAr.push.apply(newAr, arguments);
            this._tasks = newAr;
          }
          this.length += arguments.length;
        } else {
          if (len === 1)
            this._tasks = [this._tasks, a];
          else
            this._tasks = a;
          this.length++;
        }
      }
    }
    function push_rebuild(a, b) {
      var len = this.length;
      if (len > 1) {
        if (b) {
          var _a2;
          (_a2 = this._tasks).push.apply(_a2, arguments);
          this.length += arguments.length;
        } else {
          this._tasks.push(a);
          this.length++;
        }
      } else {
        if (b) {
          if (len === 1) {
            var newAr = Array(1 + arguments.length);
            newAr.push(newAr);
            newAr.push.apply(newAr, arguments);
            this._tasks = newAr;
          } else {
            var newAr = Array(arguments.length);
            newAr.push.apply(newAr, arguments);
            this._tasks = newAr;
          }
          this.length += arguments.length;
        } else {
          if (len === 1)
            this._tasks = [this._tasks, a];
          else
            this._tasks = a;
          this.length++;
        }
      }
      if (this.firstEmitBuildStrategy)
        this.call = rebuild_on_first_call;
      else
        this.rebuild();
    }
    function removeLast_norebuild(a) {
      if (this.length === 0)
        return;
      if (this.length === 1) {
        if (this._tasks === a) {
          this.length = 0;
        }
      } else {
        (0, utils_1._fast_remove_single)(this._tasks, this._tasks.lastIndexOf(a));
        if (this._tasks.length === 1) {
          this._tasks = this._tasks[0];
          this.length = 1;
        } else
          this.length = this._tasks.length;
      }
    }
    function removeLast_rebuild(a) {
      if (this.length === 0)
        return;
      if (this.length === 1) {
        if (this._tasks === a) {
          this.length = 0;
        }
        if (this.firstEmitBuildStrategy) {
          this.call = bake_collection_1.BAKED_EMPTY_FUNC;
          return;
        } else {
          this.rebuild();
          return;
        }
      } else {
        (0, utils_1._fast_remove_single)(this._tasks, this._tasks.lastIndexOf(a));
        if (this._tasks.length === 1) {
          this._tasks = this._tasks[0];
          this.length = 1;
        } else
          this.length = this._tasks.length;
      }
      if (this.firstEmitBuildStrategy)
        this.call = rebuild_on_first_call;
      else
        this.rebuild();
    }
    function insert_norebuild(index) {
      var _b;
      var func = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        func[_i - 1] = arguments[_i];
      }
      if (this.length === 0) {
        this._tasks = func;
        this.length = 1;
      } else if (this.length === 1) {
        func.unshift(this._tasks);
        this._tasks = func;
        this.length = this._tasks.length;
      } else {
        (_b = this._tasks).splice.apply(_b, __spreadArray([index, 0], func, false));
        this.length = this._tasks.length;
      }
    }
    function insert_rebuild(index) {
      var _b;
      var func = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        func[_i - 1] = arguments[_i];
      }
      if (this.length === 0) {
        this._tasks = func;
        this.length = 1;
      } else if (this.length === 1) {
        func.unshift(this._tasks);
        this._tasks = func;
        this.length = this._tasks.length;
      } else {
        (_b = this._tasks).splice.apply(_b, __spreadArray([index, 0], func, false));
        this.length = this._tasks.length;
      }
      if (this.firstEmitBuildStrategy)
        this.call = rebuild_on_first_call;
      else
        this.rebuild();
    }
    function rebuild_noawait() {
      if (this.length === 0)
        this.call = bake_collection_1.BAKED_EMPTY_FUNC;
      else if (this.length === 1)
        this.call = this._tasks;
      else
        this.call = (0, bake_collection_1.bakeCollection)(this._tasks, this.argsNum);
    }
    function rebuild_await() {
      if (this.length === 0)
        this.call = bake_collection_1.BAKED_EMPTY_FUNC;
      else if (this.length === 1)
        this.call = this._tasks;
      else
        this.call = (0, bake_collection_1.bakeCollectionAwait)(this._tasks, this.argsNum);
    }
    function rebuild_on_first_call() {
      this.rebuild();
      this.call.apply(void 0, arguments);
    }
    var TaskCollection = (
      /** @class */
      /* @__PURE__ */ function() {
        function TaskCollection2(argsNum, autoRebuild, initialTasks, awaitTasks) {
          if (autoRebuild === void 0) {
            autoRebuild = true;
          }
          if (initialTasks === void 0) {
            initialTasks = null;
          }
          if (awaitTasks === void 0) {
            awaitTasks = false;
          }
          this.awaitTasks = awaitTasks;
          this.call = bake_collection_1.BAKED_EMPTY_FUNC;
          this.argsNum = argsNum;
          this.firstEmitBuildStrategy = true;
          if (awaitTasks)
            this.rebuild = rebuild_await.bind(this);
          else
            this.rebuild = rebuild_noawait.bind(this);
          this.setAutoRebuild(autoRebuild);
          if (initialTasks) {
            if (typeof initialTasks === "function") {
              this._tasks = initialTasks;
              this.length = 1;
            } else {
              this._tasks = initialTasks;
              this.length = initialTasks.length;
            }
          } else {
            this._tasks = null;
            this.length = 0;
          }
          if (autoRebuild)
            this.rebuild();
        }
        return TaskCollection2;
      }()
    );
    exports2.TaskCollection = TaskCollection;
    function fastClear() {
      this._tasks = null;
      this.length = 0;
      this.call = bake_collection_1.BAKED_EMPTY_FUNC;
    }
    function clear() {
      this._tasks = null;
      this.length = 0;
      this.call = bake_collection_1.BAKED_EMPTY_FUNC;
    }
    function growArgsNum(argsNum) {
      if (this.argsNum < argsNum) {
        this.argsNum = argsNum;
        if (this.firstEmitBuildStrategy)
          this.call = rebuild_on_first_call;
        else
          this.rebuild();
      }
    }
    function setAutoRebuild(newVal) {
      if (newVal) {
        this.push = push_rebuild.bind(this);
        this.insert = insert_rebuild.bind(this);
        this.removeLast = removeLast_rebuild.bind(this);
      } else {
        this.push = push_norebuild.bind(this);
        this.insert = insert_norebuild.bind(this);
        this.removeLast = removeLast_norebuild.bind(this);
      }
    }
    function tasksAsArray() {
      if (this.length === 0)
        return [];
      if (this.length === 1)
        return [this._tasks];
      return this._tasks;
    }
    function setTasks(tasks) {
      if (tasks.length === 0) {
        this.length = 0;
        this.call = bake_collection_1.BAKED_EMPTY_FUNC;
      } else if (tasks.length === 1) {
        this.length = 1;
        this.call = tasks[0];
        this._tasks = tasks[0];
      } else {
        this.length = tasks.length;
        this._tasks = tasks;
        if (this.firstEmitBuildStrategy)
          this.call = rebuild_on_first_call;
        else
          this.rebuild();
      }
    }
    TaskCollection.prototype.fastClear = fastClear;
    TaskCollection.prototype.clear = clear;
    TaskCollection.prototype.growArgsNum = growArgsNum;
    TaskCollection.prototype.setAutoRebuild = setAutoRebuild;
    TaskCollection.prototype.tasksAsArray = tasksAsArray;
    TaskCollection.prototype.setTasks = setTasks;
  }
});

// ../../node_modules/tseep/lib/task-collection/index.js
var require_task_collection2 = __commonJS({
  "../../node_modules/tseep/lib/task-collection/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar(require_task_collection(), exports2);
  }
});

// ../../node_modules/tseep/lib/utils.js
var require_utils2 = __commonJS({
  "../../node_modules/tseep/lib/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.nullObj = void 0;
    function nullObj() {
      var x = {};
      x.__proto__ = null;
      return x;
    }
    exports2.nullObj = nullObj;
  }
});

// ../../node_modules/tseep/lib/ee.js
var require_ee = __commonJS({
  "../../node_modules/tseep/lib/ee.js"(exports2) {
    "use strict";
    var __spreadArray = exports2 && exports2.__spreadArray || function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EventEmitter = void 0;
    var task_collection_1 = require_task_collection2();
    var utils_1 = require_utils();
    var utils_2 = require_utils2();
    function emit(event, a, b, c, d, e) {
      var ev = this.events[event];
      if (ev) {
        if (ev.length === 0)
          return false;
        if (ev.argsNum < 6) {
          ev.call(a, b, c, d, e);
        } else {
          var arr = new Array(ev.argsNum);
          for (var i = 0, len = arr.length; i < len; ++i) {
            arr[i] = arguments[i + 1];
          }
          ev.call.apply(void 0, arr);
        }
        return true;
      }
      return false;
    }
    function emitHasOnce(event, a, b, c, d, e) {
      var ev = this.events[event];
      var argsArr;
      if (ev !== void 0) {
        if (ev.length === 0)
          return false;
        if (ev.argsNum < 6) {
          ev.call(a, b, c, d, e);
        } else {
          argsArr = new Array(ev.argsNum);
          for (var i = 0, len = argsArr.length; i < len; ++i) {
            argsArr[i] = arguments[i + 1];
          }
          ev.call.apply(void 0, argsArr);
        }
      }
      var oev = this.onceEvents[event];
      if (oev) {
        if (typeof oev === "function") {
          this.onceEvents[event] = void 0;
          if (arguments.length < 6) {
            oev(a, b, c, d, e);
          } else {
            if (argsArr === void 0) {
              argsArr = new Array(arguments.length - 1);
              for (var i = 0, len = argsArr.length; i < len; ++i) {
                argsArr[i] = arguments[i + 1];
              }
            }
            oev.apply(void 0, argsArr);
          }
        } else {
          var fncs = oev;
          this.onceEvents[event] = void 0;
          if (arguments.length < 6) {
            for (var i = 0; i < fncs.length; ++i) {
              fncs[i](a, b, c, d, e);
            }
          } else {
            if (argsArr === void 0) {
              argsArr = new Array(arguments.length - 1);
              for (var i = 0, len = argsArr.length; i < len; ++i) {
                argsArr[i] = arguments[i + 1];
              }
            }
            for (var i = 0; i < fncs.length; ++i) {
              fncs[i].apply(void 0, argsArr);
            }
          }
        }
        return true;
      }
      return ev !== void 0;
    }
    var EventEmitter2 = (
      /** @class */
      function() {
        function EventEmitter3() {
          this.events = (0, utils_2.nullObj)();
          this.onceEvents = (0, utils_2.nullObj)();
          this._symbolKeys = /* @__PURE__ */ new Set();
          this.maxListeners = Infinity;
        }
        Object.defineProperty(EventEmitter3.prototype, "_eventsCount", {
          get: function() {
            return this.eventNames().length;
          },
          enumerable: false,
          configurable: true
        });
        return EventEmitter3;
      }()
    );
    exports2.EventEmitter = EventEmitter2;
    function once(event, listener) {
      if (this.emit === emit) {
        this.emit = emitHasOnce;
      }
      switch (typeof this.onceEvents[event]) {
        case "undefined":
          this.onceEvents[event] = listener;
          if (typeof event === "symbol")
            this._symbolKeys.add(event);
          break;
        case "function":
          this.onceEvents[event] = [this.onceEvents[event], listener];
          break;
        case "object":
          this.onceEvents[event].push(listener);
      }
      return this;
    }
    function addListener(event, listener, argsNum) {
      if (argsNum === void 0) {
        argsNum = listener.length;
      }
      if (typeof listener !== "function")
        throw new TypeError("The listener must be a function");
      var evtmap = this.events[event];
      if (!evtmap) {
        this.events[event] = new task_collection_1.TaskCollection(argsNum, true, listener, false);
        if (typeof event === "symbol")
          this._symbolKeys.add(event);
      } else {
        evtmap.push(listener);
        evtmap.growArgsNum(argsNum);
        if (this.maxListeners !== Infinity && this.maxListeners <= evtmap.length)
          console.warn('Maximum event listeners for "'.concat(String(event), '" event!'));
      }
      return this;
    }
    function removeListener(event, listener) {
      var evt = this.events[event];
      if (evt) {
        evt.removeLast(listener);
      }
      var evto = this.onceEvents[event];
      if (evto) {
        if (typeof evto === "function") {
          this.onceEvents[event] = void 0;
        } else if (typeof evto === "object") {
          if (evto.length === 1 && evto[0] === listener) {
            this.onceEvents[event] = void 0;
          } else {
            (0, utils_1._fast_remove_single)(evto, evto.lastIndexOf(listener));
          }
        }
      }
      return this;
    }
    function addListenerBound(event, listener, bindTo, argsNum) {
      if (bindTo === void 0) {
        bindTo = this;
      }
      if (argsNum === void 0) {
        argsNum = listener.length;
      }
      if (!this.boundFuncs)
        this.boundFuncs = /* @__PURE__ */ new Map();
      var bound = listener.bind(bindTo);
      this.boundFuncs.set(listener, bound);
      return this.addListener(event, bound, argsNum);
    }
    function removeListenerBound(event, listener) {
      var _a2, _b;
      var bound = (_a2 = this.boundFuncs) === null || _a2 === void 0 ? void 0 : _a2.get(listener);
      (_b = this.boundFuncs) === null || _b === void 0 ? void 0 : _b.delete(listener);
      return this.removeListener(event, bound);
    }
    function hasListeners(event) {
      return this.events[event] && !!this.events[event].length;
    }
    function prependListener(event, listener, argsNum) {
      if (argsNum === void 0) {
        argsNum = listener.length;
      }
      if (typeof listener !== "function")
        throw new TypeError("The listener must be a function");
      var evtmap = this.events[event];
      if (!evtmap || !(evtmap instanceof task_collection_1.TaskCollection)) {
        evtmap = this.events[event] = new task_collection_1.TaskCollection(argsNum, true, listener, false);
        if (typeof event === "symbol")
          this._symbolKeys.add(event);
      } else {
        evtmap.insert(0, listener);
        evtmap.growArgsNum(argsNum);
        if (this.maxListeners !== Infinity && this.maxListeners <= evtmap.length)
          console.warn('Maximum event listeners for "'.concat(String(event), '" event!'));
      }
      return this;
    }
    function prependOnceListener(event, listener) {
      if (this.emit === emit) {
        this.emit = emitHasOnce;
      }
      var evtmap = this.onceEvents[event];
      if (!evtmap) {
        this.onceEvents[event] = [listener];
        if (typeof event === "symbol")
          this._symbolKeys.add(event);
      } else if (typeof evtmap !== "object") {
        this.onceEvents[event] = [listener, evtmap];
        if (typeof event === "symbol")
          this._symbolKeys.add(event);
      } else {
        evtmap.unshift(listener);
        if (this.maxListeners !== Infinity && this.maxListeners <= evtmap.length) {
          console.warn('Maximum event listeners for "'.concat(String(event), '" once event!'));
        }
      }
      return this;
    }
    function removeAllListeners(event) {
      if (event === void 0) {
        this.events = (0, utils_2.nullObj)();
        this.onceEvents = (0, utils_2.nullObj)();
        this._symbolKeys = /* @__PURE__ */ new Set();
      } else {
        this.events[event] = void 0;
        this.onceEvents[event] = void 0;
        if (typeof event === "symbol")
          this._symbolKeys.delete(event);
      }
      return this;
    }
    function setMaxListeners(n) {
      this.maxListeners = n;
      return this;
    }
    function getMaxListeners() {
      return this.maxListeners;
    }
    function listeners(event) {
      if (this.emit === emit)
        return this.events[event] ? this.events[event].tasksAsArray().slice() : [];
      else {
        if (this.events[event] && this.onceEvents[event]) {
          return __spreadArray(__spreadArray([], this.events[event].tasksAsArray(), true), typeof this.onceEvents[event] === "function" ? [this.onceEvents[event]] : this.onceEvents[event], true);
        } else if (this.events[event])
          return this.events[event].tasksAsArray();
        else if (this.onceEvents[event])
          return typeof this.onceEvents[event] === "function" ? [this.onceEvents[event]] : this.onceEvents[event];
        else
          return [];
      }
    }
    function eventNames() {
      var _this = this;
      if (this.emit === emit) {
        var keys = Object.keys(this.events);
        return __spreadArray(__spreadArray([], keys, true), Array.from(this._symbolKeys), true).filter(function(x) {
          return x in _this.events && _this.events[x] && _this.events[x].length;
        });
      } else {
        var keys = Object.keys(this.events).filter(function(x) {
          return _this.events[x] && _this.events[x].length;
        });
        var keysO = Object.keys(this.onceEvents).filter(function(x) {
          return _this.onceEvents[x] && _this.onceEvents[x].length;
        });
        return __spreadArray(__spreadArray(__spreadArray([], keys, true), keysO, true), Array.from(this._symbolKeys).filter(function(x) {
          return x in _this.events && _this.events[x] && _this.events[x].length || x in _this.onceEvents && _this.onceEvents[x] && _this.onceEvents[x].length;
        }), true);
      }
    }
    function listenerCount(type) {
      if (this.emit === emit)
        return this.events[type] && this.events[type].length || 0;
      else
        return (this.events[type] && this.events[type].length || 0) + (this.onceEvents[type] && this.onceEvents[type].length || 0);
    }
    EventEmitter2.prototype.emit = emit;
    EventEmitter2.prototype.on = addListener;
    EventEmitter2.prototype.once = once;
    EventEmitter2.prototype.addListener = addListener;
    EventEmitter2.prototype.removeListener = removeListener;
    EventEmitter2.prototype.addListenerBound = addListenerBound;
    EventEmitter2.prototype.removeListenerBound = removeListenerBound;
    EventEmitter2.prototype.hasListeners = hasListeners;
    EventEmitter2.prototype.prependListener = prependListener;
    EventEmitter2.prototype.prependOnceListener = prependOnceListener;
    EventEmitter2.prototype.off = removeListener;
    EventEmitter2.prototype.removeAllListeners = removeAllListeners;
    EventEmitter2.prototype.setMaxListeners = setMaxListeners;
    EventEmitter2.prototype.getMaxListeners = getMaxListeners;
    EventEmitter2.prototype.listeners = listeners;
    EventEmitter2.prototype.eventNames = eventNames;
    EventEmitter2.prototype.listenerCount = listenerCount;
  }
});

// ../../node_modules/tseep/lib/index.js
var require_lib = __commonJS({
  "../../node_modules/tseep/lib/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar(require_types(), exports2);
    __exportStar(require_ee(), exports2);
  }
});

// src/hls-player.ts
import Hls from "hls.js";

// ../shared/src/assert.ts
function assert(value, message = "value is null") {
  if (value === null || value === void 0) {
    throw Error(message);
  }
}

// src/hls-player.ts
var import_tseep = __toESM(require_lib(), 1);

// src/event-manager.ts
var EventManager = class {
  constructor() {
    __publicField(this, "bindings_", /* @__PURE__ */ new Set());
    __publicField(this, "listen", (target) => (type, listener, context) => {
      const binding = createBinding(target, type, listener, context);
      this.bindings_.add(binding);
    });
    __publicField(this, "listenOnce", (target) => (type, listener, context) => {
      const binding = createBinding(target, type, listener, context, true);
      this.bindings_.add(binding);
    });
    __publicField(this, "unlisten", (target) => (type, listener) => {
      const binding = Array.from(this.bindings_).find(
        (binding2) => binding2.target === target && binding2.type === type && binding2.listener === listener
      );
      if (binding) {
        binding.remove();
        this.bindings_.delete(binding);
      }
    });
  }
  removeAll() {
    this.bindings_.forEach((binding) => {
      binding.remove();
    });
    this.bindings_.clear();
  }
};
function createBinding(target, type, listener, context, once) {
  const methodMap = {
    add: target.addEventListener?.bind(target) ?? target.on?.bind(target),
    remove: target.removeEventListener?.bind(target) ?? target.off?.bind(target)
  };
  const remove = () => {
    methodMap.remove?.(type, callback);
  };
  const callback = async (...args) => {
    try {
      await listener.apply(context, args);
      if (once) {
        remove();
      }
    } catch (error) {
      console.error(error);
    }
  };
  methodMap.add?.(type, callback);
  return {
    target,
    type,
    listener,
    context,
    once,
    remove
  };
}

// src/helpers.ts
function preciseFloat(value) {
  return Math.round((value + Number.EPSILON) * 100) / 100;
}
function getLangCode(key) {
  const value = key ? langCodes[key]?.split(",")[0] : null;
  if (!value) {
    return "Unknown";
  }
  return `${value[0].toUpperCase()}${value.slice(1)}`;
}
var langCodes = {
  sr: "\u0441\u0440\u043F\u0441\u043A\u0438 \u0458\u0435\u0437\u0438\u043A",
  ro: "Rom\xE2n\u0103",
  ii: "\uA188\uA320\uA4BF Nuosuhxop",
  ty: "Reo Tahiti",
  tl: "Wikang Tagalog",
  yi: "\u05D9\u05D9\u05B4\u05D3\u05D9\u05E9",
  ak: "Akan",
  ms: "Bahasa Melayu, \u0628\u0647\u0627\u0633 \u0645\u0644\u0627\u064A\u0648",
  ar: "\u0627\u0644\u0639\u0631\u0628\u064A\u0629",
  no: "Norsk",
  oj: "\u140A\u14C2\u1511\u14C8\u142F\u14A7\u140E\u14D0",
  ff: "Fulfulde, Pulaar, Pular",
  fa: "\u0641\u0627\u0631\u0633\u06CC",
  sq: "Shqip",
  ay: "aymar aru",
  az: "az\u0259rbaycan dili",
  zh: "\u4E2D\u6587 (Zh\u014Dngw\xE9n), \u6C49\u8BED, \u6F22\u8A9E",
  cr: "\u14C0\u1426\u1403\u152D\u140D\u140F\u1423",
  et: "eesti, eesti keel",
  gn: "Ava\xF1e'\u1EBD",
  ik: "I\xF1upiaq, I\xF1upiatun",
  iu: "\u1403\u14C4\u1483\u144E\u1450\u1466",
  kr: "Kanuri",
  kv: "\u043A\u043E\u043C\u0438 \u043A\u044B\u0432",
  kg: "Kikongo",
  ku: "Kurd\xEE, \u0623\u06C7\u0632\u0628\u06D0\u0643",
  lv: "latvie\u0161u valoda",
  mg: "fiteny malagasy",
  mn: "\u041C\u043E\u043D\u0433\u043E\u043B \u0445\u044D\u043B",
  om: "Afaan Oromoo",
  ps: "\u067E\u069A\u062A\u0648",
  qu: "Runa Simi, Kichwa",
  sc: "sardu",
  sw: "Kiswahili",
  uz: "O'zbek, \u040E\u0437\u0431\u0435\u043A, ",
  za: "Saw cue\u014B\u0185, Saw cuengh",
  bi: "Bislama",
  nb: "Norsk Bokm\xE5l",
  nn: "Norsk Nynorsk",
  id: "Bahasa Indonesia",
  tw: "Twi",
  eo: "Esperanto",
  ia: "Interlingua",
  ie: "Originally called Occidental; then Interlingue after WWII",
  io: "Ido",
  vo: "Volap\xFCk",
  bh: "\u092D\u094B\u091C\u092A\u0941\u0930\u0940",
  he: "\u05E2\u05D1\u05E8\u05D9\u05EA",
  sa: "\u0938\u0902\u0938\u094D\u0915\u0943\u0924\u092E\u094D",
  cu: "\u0469\u0437\u044B\u043A\u044A \u0441\u043B\u043E\u0432\u0463\u043D\u044C\u0441\u043A\u044A",
  pi: "\u092A\u093E\u0934\u093F",
  ae: "avesta",
  la: "latine, lingua latina",
  hy: "\u0540\u0561\u0575\u0565\u0580\u0565\u0576",
  ss: "SiSwati",
  bo: "\u0F56\u0F7C\u0F51\u0F0B\u0F61\u0F72\u0F42",
  nr: "isiNdebele",
  sl: "Slovenski Jezik, Sloven\u0161\u010Dina",
  or: "\u0B13\u0B21\u0B3C\u0B3F\u0B06",
  nd: "isiNdebele",
  na: "Dorerin Naoero",
  mi: "te reo M\u0101ori",
  mr: "\u092E\u0930\u093E\u0920\u0940",
  lu: "Kiluba",
  rn: "Ikirundi",
  km: "\u1781\u17D2\u1798\u17C2\u179A, \u1781\u17C1\u1798\u179A\u1797\u17B6\u179F\u17B6, \u1797\u17B6\u179F\u17B6\u1781\u17D2\u1798\u17C2\u179A",
  fy: "Frysk",
  bn: "\u09AC\u09BE\u0982\u09B2\u09BE",
  av: "\u0430\u0432\u0430\u0440 \u043C\u0430\u0446\u04C0, \u043C\u0430\u0433\u04C0\u0430\u0440\u0443\u043B \u043C\u0430\u0446\u04C0",
  ab: "\u0430\u04A7\u0441\u0443\u0430 \u0431\u044B\u0437\u0448\u04D9\u0430, \u0430\u04A7\u0441\u0448\u04D9\u0430",
  aa: "Afaraf",
  af: "Afrikaans",
  am: "\u12A0\u121B\u122D\u129B",
  an: "aragon\xE9s",
  as: "\u0985\u09B8\u09AE\u09C0\u09AF\u09BC\u09BE",
  bm: "bamanankan",
  ba: "\u0431\u0430\u0448\u04A1\u043E\u0440\u0442 \u0442\u0435\u043B\u0435",
  eu: "euskara, euskera",
  be: "\u0431\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F \u043C\u043E\u0432\u0430",
  bs: "bosanski jezik",
  br: "brezhoneg",
  bg: "\u0431\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438 \u0435\u0437\u0438\u043A",
  my: "\u1017\u1019\u102C\u1005\u102C",
  ca: "catal\xE0, valenci\xE0",
  ch: "Chamoru",
  ce: "\u043D\u043E\u0445\u0447\u0438\u0439\u043D \u043C\u043E\u0442\u0442",
  ny: "chiChe\u0175a, chinyanja",
  cv: "\u0447\u04D1\u0432\u0430\u0448 \u0447\u04D7\u043B\u0445\u0438",
  kw: "Kernewek",
  co: "corsu, lingua corsa",
  hr: "hrvatski jezik",
  cs: "\u010De\u0161tina, \u010Desk\xFD jazyk",
  da: "dansk",
  dv: "\u078B\u07A8\u0788\u07AC\u0780\u07A8",
  nl: "Nederlands, Vlaams",
  dz: "\u0F62\u0FAB\u0F7C\u0F44\u0F0B\u0F41",
  en: "English",
  ee: "E\u028Begbe",
  fo: "f\xF8royskt",
  fj: "vosa Vakaviti",
  fi: "suomi, suomen kieli",
  fr: "fran\xE7ais, langue fran\xE7aise",
  gl: "Galego",
  ka: "\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",
  de: "Deutsch",
  el: "\u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",
  gu: "\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",
  ht: "Krey\xF2l ayisyen",
  ha: "(Hausa) \u0647\u064E\u0648\u064F\u0633\u064E",
  hz: "Otjiherero",
  hi: "\u0939\u093F\u0928\u094D\u0926\u0940, \u0939\u093F\u0902\u0926\u0940",
  ho: "Hiri Motu",
  hu: "magyar",
  ga: "Gaeilge",
  ig: "As\u1EE5s\u1EE5 Igbo",
  is: "\xCDslenska",
  it: "Italiano",
  ja: "\u65E5\u672C\u8A9E (\u306B\u307B\u3093\u3054)",
  jv: "\uA9A7\uA9B1\uA997\uA9AE, Basa Jawa",
  kl: "kalaallisut, kalaallit oqaasii",
  kn: "\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",
  ks: "\u0915\u0936\u094D\u092E\u0940\u0930\u0940, \u0643\u0634\u0645\u064A\u0631\u064A",
  kk: "\u049B\u0430\u0437\u0430\u049B \u0442\u0456\u043B\u0456",
  ki: "G\u0129k\u0169y\u0169",
  rw: "Ikinyarwanda",
  ky: "\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430, \u041A\u044B\u0440\u0433\u044B\u0437 \u0442\u0438\u043B\u0438",
  ko: "\uD55C\uAD6D\uC5B4",
  kj: "Kuanyama",
  lb: "L\xEBtzebuergesch",
  lg: "Luganda",
  li: "Limburgs",
  ln: "Ling\xE1la",
  lo: "\u0E9E\u0EB2\u0EAA\u0EB2\u0EA5\u0EB2\u0EA7",
  lt: "lietuvi\u0173 kalba",
  gv: "Gaelg, Gailck",
  mk: "\u043C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438 \u0458\u0430\u0437\u0438\u043A",
  ml: "\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",
  mt: "Malti",
  mh: "Kajin M\u0327aje\u013C",
  nv: "Din\xE9 bizaad",
  ne: "\u0928\u0947\u092A\u093E\u0932\u0940",
  ng: "Owambo",
  oc: "occitan, lenga d'\xF2c",
  os: "\u0438\u0440\u043E\u043D \xE6\u0432\u0437\u0430\u0433",
  pa: "\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",
  pl: "j\u0119zyk polski, polszczyzna",
  pt: "Portugu\xEAs",
  rm: "Rumantsch Grischun",
  ru: "\u0440\u0443\u0441\u0441\u043A\u0438\u0439",
  sd: "\u0938\u093F\u0928\u094D\u0927\u0940, \u0633\u0646\u068C\u064A\u060C \u0633\u0646\u062F\u06BE\u06CC",
  se: "Davvis\xE1megiella",
  sm: "gagana fa'a Samoa",
  sg: "y\xE2ng\xE2 t\xEE s\xE4ng\xF6",
  gd: "G\xE0idhlig",
  sn: "chiShona",
  si: "\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",
  sk: "Sloven\u010Dina, Slovensk\xFD Jazyk",
  so: "Soomaaliga, af Soomaali",
  st: "Sesotho",
  es: "Espa\xF1ol",
  su: "Basa Sunda",
  sv: "Svenska",
  ta: "\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",
  te: "\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",
  tg: "\u0442\u043E\u04B7\u0438\u043A\u04E3, to\xE7ik\u012B, \u062A\u0627\u062C\u06CC\u06A9\u06CC",
  th: "\u0E44\u0E17\u0E22",
  ti: "\u1275\u130D\u122D\u129B",
  tk: "T\xFCrkmen, \u0422\u04AF\u0440\u043A\u043C\u0435\u043D",
  tn: "Setswana",
  to: "Faka Tonga",
  tr: "T\xFCrk\xE7e",
  ts: "Xitsonga",
  tt: "\u0442\u0430\u0442\u0430\u0440 \u0442\u0435\u043B\u0435, tatar tele",
  ug: "\u0626\u06C7\u064A\u063A\u06C7\u0631\u0686\u06D5, Uyghurche",
  uk: "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",
  ur: "\u0627\u0631\u062F\u0648",
  ve: "Tshiven\u1E13a",
  vi: "Ti\u1EBFng Vi\u1EC7t",
  wa: "Walon",
  cy: "Cymraeg",
  wo: "Wollof",
  xh: "isiXhosa",
  yo: "Yor\xF9b\xE1",
  zu: "isiZulu"
};

// src/types.ts
var Events = /* @__PURE__ */ ((Events2) => {
  Events2["RESET"] = "reset";
  Events2["READY"] = "ready";
  Events2["STARTED"] = "started";
  Events2["PLAYHEAD_CHANGE"] = "playheadChange";
  Events2["TIME_CHANGE"] = "timeChange";
  Events2["VOLUME_CHANGE"] = "volumeChange";
  Events2["QUALITIES_CHANGE"] = "qualitiesChange";
  Events2["AUDIO_TRACKS_CHANGE"] = "audioTracksChange";
  Events2["SUBTITLE_TRACKS_CHANGE"] = "subtitleTracksChange";
  Events2["AUTO_QUALITY_CHANGE"] = "autoQualityChange";
  Events2["INTERSTITIAL_CHANGE"] = "interstitialChange";
  Events2["SEEKING_CHANGE"] = "seekingChange";
  Events2["CUEPOINTS_CHANGE"] = "cuePointsChange";
  return Events2;
})(Events || {});

// src/state.ts
var noState = {
  playhead: "idle",
  ready: false,
  started: false,
  time: 0,
  duration: NaN,
  interstitial: null,
  qualities: [],
  autoQuality: false,
  audioTracks: [],
  subtitleTracks: [],
  volume: 1,
  seeking: false,
  cuePoints: []
};
var State = class {
  constructor(params_) {
    this.params_ = params_;
    __publicField(this, "timerId_");
    __publicField(this, "ready", noState.ready);
    __publicField(this, "playhead", noState.playhead);
    __publicField(this, "started", noState.started);
    __publicField(this, "time", noState.time);
    __publicField(this, "duration", noState.duration);
    __publicField(this, "interstitial", noState.interstitial);
    __publicField(this, "qualities", noState.qualities);
    __publicField(this, "autoQuality", noState.autoQuality);
    __publicField(this, "audioTracks", noState.audioTracks);
    __publicField(this, "subtitleTracks", noState.subtitleTracks);
    __publicField(this, "volume", noState.volume);
    __publicField(this, "seeking", noState.seeking);
    __publicField(this, "cuePoints", noState.cuePoints);
    this.requestTimingSync();
  }
  setReady() {
    if (this.ready) {
      return;
    }
    this.ready = true;
    this.requestTimingSync();
    this.params_.onEvent("ready" /* READY */);
  }
  setPlayhead(playhead) {
    if (playhead === this.playhead) {
      return;
    }
    this.playhead = playhead;
    if (playhead === "pause") {
      this.requestTimingSync();
    }
    this.params_.onEvent("playheadChange" /* PLAYHEAD_CHANGE */);
  }
  setStarted() {
    if (this.started) {
      return;
    }
    this.started = true;
    this.params_.onEvent("started" /* STARTED */);
  }
  setInterstitial(interstitial) {
    this.interstitial = interstitial;
    this.setSeeking(false);
    this.params_.onEvent("interstitialChange" /* INTERSTITIAL_CHANGE */);
  }
  setAsset(asset) {
    if (!this.interstitial) {
      return;
    }
    if (asset) {
      this.interstitial.asset = {
        time: 0,
        duration: NaN,
        ...asset
      };
      this.requestTimingSync();
    } else {
      this.interstitial.asset = null;
    }
  }
  setQualities(qualities, autoQuality) {
    const diff = (items) => items.find((item) => item.active)?.height;
    if (diff(this.qualities) !== diff(qualities)) {
      this.qualities = qualities;
      this.params_.onEvent("qualitiesChange" /* QUALITIES_CHANGE */);
    }
    if (autoQuality !== this.autoQuality) {
      this.autoQuality = autoQuality;
      this.params_.onEvent("autoQualityChange" /* AUTO_QUALITY_CHANGE */);
    }
  }
  setAudioTracks(audioTracks) {
    const diff = (items) => items.find((item) => item.active)?.id;
    if (diff(this.audioTracks) !== diff(audioTracks)) {
      this.audioTracks = audioTracks;
      this.params_.onEvent("audioTracksChange" /* AUDIO_TRACKS_CHANGE */);
    }
  }
  setSubtitleTracks(subtitleTracks) {
    const diff = (items) => items.find((item) => item.active)?.id;
    if (
      // TODO: Come up with a generic logical check.
      !this.subtitleTracks.length && subtitleTracks.length || diff(this.subtitleTracks) !== diff(subtitleTracks)
    ) {
      this.subtitleTracks = subtitleTracks;
      this.params_.onEvent("subtitleTracksChange" /* SUBTITLE_TRACKS_CHANGE */);
    }
  }
  setVolume(volume) {
    if (volume === this.volume) {
      return;
    }
    this.volume = volume;
    this.params_.onEvent("volumeChange" /* VOLUME_CHANGE */);
  }
  setSeeking(seeking) {
    if (seeking === this.seeking) {
      return;
    }
    this.seeking = seeking;
    this.requestTimingSync();
    this.params_.onEvent("seekingChange" /* SEEKING_CHANGE */);
  }
  setCuePoints(cuePoints) {
    this.cuePoints = cuePoints;
    this.requestTimingSync();
    this.params_.onEvent("cuePointsChange" /* CUEPOINTS_CHANGE */);
  }
  requestTimingSync() {
    clearTimeout(this.timerId_);
    this.timerId_ = window.setTimeout(() => {
      this.requestTimingSync();
    }, 250);
    const timing = this.params_.getTiming();
    let shouldEmit = false;
    if (this.updateTimeDuration_(this, timing.primary)) {
      shouldEmit = true;
    }
    if (this.interstitial?.asset && this.updateTimeDuration_(this.interstitial.asset, timing.asset)) {
      shouldEmit = true;
    }
    if (shouldEmit) {
      this.params_.onEvent("timeChange" /* TIME_CHANGE */);
    }
  }
  updateTimeDuration_(target, shim) {
    if (!shim) {
      return false;
    }
    if (!Number.isFinite(shim.duration)) {
      return false;
    }
    const oldTime = target.time;
    target.time = preciseFloat(shim.currentTime);
    const oldDuration = target.duration;
    target.duration = preciseFloat(shim.duration);
    if (target.time > target.duration) {
      target.time = target.duration;
    }
    return oldTime !== target.time || oldDuration !== target.duration;
  }
};
function getState(state, name) {
  return state?.[name] ?? noState[name];
}

// src/hls-player.ts
var HlsPlayer = class {
  constructor(container) {
    this.container = container;
    __publicField(this, "media_");
    __publicField(this, "eventManager_", new EventManager());
    __publicField(this, "hls_", null);
    __publicField(this, "state_", null);
    __publicField(this, "emitter_", new import_tseep.EventEmitter());
    __publicField(this, "on", this.emitter_.on.bind(this.emitter_));
    __publicField(this, "off", this.emitter_.off.bind(this.emitter_));
    __publicField(this, "once", this.emitter_.once.bind(this.emitter_));
    this.media_ = this.createMedia_();
  }
  createMedia_() {
    const media = document.createElement("video");
    this.container.appendChild(media);
    media.style.position = "absolute";
    media.style.inset = "0";
    media.style.width = "100%";
    media.style.height = "100%";
    return media;
  }
  load(url) {
    this.unload();
    this.bindMediaListeners_();
    const hls = this.createHls_();
    this.state_ = new State({
      onEvent: (event) => this.emit_(event),
      getTiming: () => ({
        primary: hls.interstitialsManager?.primary ?? hls.media,
        asset: hls.interstitialsManager?.playerQueue.find(
          (player) => player.assetItem === hls.interstitialsManager?.playingAsset
        )
      })
    });
    hls.attachMedia(this.media_);
    hls.loadSource(url);
    this.hls_ = hls;
  }
  unload() {
    this.eventManager_.removeAll();
    this.state_ = null;
    if (this.hls_) {
      this.hls_.destroy();
      this.hls_ = null;
    }
    this.emit_("reset" /* RESET */);
  }
  destroy() {
    this.emitter_.removeAllListeners();
    this.unload();
  }
  playOrPause() {
    if (!this.state_) {
      return;
    }
    const shouldPause = this.state_.playhead === "play" || this.state_.playhead === "playing";
    if (shouldPause) {
      this.media_.pause();
    } else {
      this.media_.play();
    }
  }
  seekTo(time) {
    assert(this.hls_);
    if (this.state_?.interstitial) {
      return false;
    }
    if (this.hls_.interstitialsManager) {
      this.hls_.interstitialsManager.primary.seekTo(time);
    } else {
      this.media_.currentTime = time;
    }
    return true;
  }
  setQuality(height) {
    assert(this.hls_);
    if (height === null) {
      this.hls_.nextLevel = -1;
    } else {
      const loadLevel = this.hls_.levels[this.hls_.loadLevel];
      assert(loadLevel, "No level found for loadLevel index");
      const idx = this.hls_.levels.findIndex((level) => {
        return level.height === height && level.audioCodec?.substring(0, 4) === loadLevel.audioCodec?.substring(0, 4);
      });
      if (idx < 0) {
        throw new Error("Could not find matching level");
      }
      this.hls_.nextLevel = idx;
    }
    this.updateQualities_();
  }
  setAudioTrack(id) {
    assert(this.hls_);
    const audioTrack = this.state_?.audioTracks.find(
      (track) => track.id === id
    );
    assert(audioTrack);
    this.hls_.setAudioOption({
      lang: audioTrack.track.lang,
      channels: audioTrack.track.channels,
      name: audioTrack.track.name
    });
  }
  setSubtitleTrack(id) {
    assert(this.hls_);
    if (id === null) {
      this.hls_.subtitleTrack = -1;
      return;
    }
    const subtitleTrack = this.state_?.subtitleTracks.find(
      (track) => track.id === id
    );
    assert(subtitleTrack);
    this.hls_.setSubtitleOption({
      lang: subtitleTrack.track.lang,
      name: subtitleTrack.track.name
    });
  }
  setVolume(volume) {
    this.media_.volume = volume;
    this.media_.muted = volume === 0;
    this.state_?.setVolume(volume);
  }
  get ready() {
    return getState(this.state_, "ready");
  }
  get playhead() {
    return getState(this.state_, "playhead");
  }
  get started() {
    return getState(this.state_, "started");
  }
  get time() {
    return getState(this.state_, "time");
  }
  get duration() {
    return getState(this.state_, "duration");
  }
  get seeking() {
    return getState(this.state_, "seeking");
  }
  get interstitial() {
    return getState(this.state_, "interstitial");
  }
  get qualities() {
    return getState(this.state_, "qualities");
  }
  get autoQuality() {
    return getState(this.state_, "autoQuality");
  }
  get audioTracks() {
    return getState(this.state_, "audioTracks");
  }
  get subtitleTracks() {
    return getState(this.state_, "subtitleTracks");
  }
  get volume() {
    return getState(this.state_, "volume");
  }
  get seekableStart() {
    if (this.hls_) {
      return this.hls_.interstitialsManager?.primary?.seekableStart ?? 0;
    }
    return NaN;
  }
  get live() {
    return this.hls_?.levels[this.hls_.currentLevel]?.details?.live ?? false;
  }
  get cuePoints() {
    return getState(this.state_, "cuePoints");
  }
  createHls_() {
    const hls = new Hls();
    const listen = this.eventManager_.listen(hls);
    listen(Hls.Events.MANIFEST_LOADED, () => {
      this.updateQualities_();
      this.updateAudioTracks_();
      this.updateSubtitleTracks_();
    });
    listen(Hls.Events.INTERSTITIAL_STARTED, () => {
      this.state_?.setInterstitial({
        asset: null
      });
    });
    listen(Hls.Events.INTERSTITIAL_ASSET_STARTED, (_, data) => {
      const listResponseAsset = data.event.assetListResponse?.ASSETS[data.assetListIndex];
      this.state_?.setAsset({
        type: listResponseAsset["SPRS-KIND"]
      });
    });
    listen(Hls.Events.INTERSTITIAL_ASSET_ENDED, () => {
      this.state_?.setAsset(null);
    });
    listen(Hls.Events.INTERSTITIAL_ENDED, () => {
      this.state_?.setInterstitial(null);
    });
    listen(Hls.Events.LEVELS_UPDATED, () => {
      this.updateQualities_();
    });
    listen(Hls.Events.LEVEL_SWITCHING, () => {
      this.updateQualities_();
    });
    listen(Hls.Events.AUDIO_TRACKS_UPDATED, () => {
      this.updateAudioTracks_();
    });
    listen(Hls.Events.AUDIO_TRACK_SWITCHING, () => {
      this.updateAudioTracks_();
    });
    listen(Hls.Events.SUBTITLE_TRACKS_UPDATED, () => {
      this.updateSubtitleTracks_();
    });
    listen(Hls.Events.SUBTITLE_TRACK_SWITCH, () => {
      this.updateSubtitleTracks_();
    });
    listen(Hls.Events.INTERSTITIALS_UPDATED, (_, data) => {
      const cuePoints = data.schedule.reduce((acc, item) => {
        if (item.event) {
          acc.push(item.start);
        }
        return acc;
      }, []);
      this.state_?.setCuePoints(cuePoints);
    });
    return hls;
  }
  updateQualities_() {
    assert(this.hls_);
    const group = [];
    for (const level2 of this.hls_.levels) {
      let item = group.find((item2) => item2.height === level2.height);
      if (!item) {
        item = {
          height: level2.height,
          levels: []
        };
        group.push(item);
      }
      item.levels.push(level2);
    }
    const level = this.hls_.levels[this.hls_.nextLoadLevel];
    const qualities = group.map((item) => {
      return {
        ...item,
        active: item.height === level.height
      };
    });
    qualities.sort((a, b) => b.height - a.height);
    const autoQuality = this.hls_.autoLevelEnabled;
    this.state_?.setQualities(qualities, autoQuality);
  }
  updateAudioTracks_() {
    assert(this.hls_);
    const tracks = this.hls_.allAudioTracks.map((track, index) => {
      let label = getLangCode(track.lang);
      if (track.channels === "6") {
        label += " 5.1";
      }
      return {
        id: index,
        active: this.hls_?.audioTracks.includes(track) ? track.id === this.hls_.audioTrack : false,
        label,
        track
      };
    });
    this.state_?.setAudioTracks(tracks);
  }
  updateSubtitleTracks_() {
    assert(this.hls_);
    const tracks = this.hls_.allSubtitleTracks.map(
      (track, index) => {
        return {
          id: index,
          active: this.hls_?.subtitleTracks.includes(track) ? track.id === this.hls_.subtitleTrack : false,
          label: getLangCode(track.lang),
          track
        };
      }
    );
    this.state_?.setSubtitleTracks(tracks);
  }
  bindMediaListeners_() {
    const listen = this.eventManager_.listen(this.media_);
    listen("canplay", () => {
      this.state_?.setReady();
    });
    listen("play", () => {
      this.state_?.setPlayhead("play");
    });
    listen("playing", () => {
      this.state_?.setStarted();
      this.state_?.setPlayhead("playing");
    });
    listen("pause", () => {
      this.state_?.setPlayhead("pause");
    });
    listen("volumechange", () => {
      this.state_?.setVolume(this.media_.volume);
    });
    listen("seeking", () => {
      this.state_?.setSeeking(true);
    });
    listen("seeked", () => {
      this.state_?.setSeeking(false);
    });
  }
  emit_(event) {
    this.emitter_.emit(event);
    this.emitter_.emit("*", event);
  }
};
export {
  Events,
  HlsPlayer
};
//# sourceMappingURL=index.js.map