html_digital_item/yantu/yantoo-ava.js
Song367 e2b2228d00
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 3s
添加气泡
2025-06-20 15:00:01 +08:00

20262 lines
2.0 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DUIX = factory());
})(this, (function () { 'use strict';
function _mergeNamespaces(n, m) {
m.forEach(function (e) {
e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
if (k !== 'default' && !(k in n)) {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
});
return Object.freeze(n);
}
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s,
_e,
_x,
_r,
_arr = [],
_n = !0,
_d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return exports;
};
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
defineProperty = Object.defineProperty || function (obj, key, desc) {
obj[key] = desc.value;
},
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function (obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return defineProperty(generator, "_invoke", {
value: makeInvokeMethod(innerFn, self, context)
}), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
defineProperty(this, "_invoke", {
value: function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return {
value: void 0,
done: !0
};
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}
function maybeInvokeDelegate(delegate, context) {
var methodName = context.method,
method = delegate.iterator[methodName];
if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable || "" === iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
throw new TypeError(typeof iterable + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), defineProperty(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (val) {
var object = Object(val),
keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function () {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function (exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function (record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get.bind();
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(arguments.length < 3 ? target : receiver);
}
return desc.value;
};
}
return _get.apply(this, arguments);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function _classPrivateMethodGet(receiver, privateSet, fn) {
if (!privateSet.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return fn;
}
function _checkPrivateRedeclaration(obj, privateCollection) {
if (privateCollection.has(obj)) {
throw new TypeError("Cannot initialize the same private elements twice on an object");
}
}
function _classPrivateMethodInitSpec(obj, privateSet) {
_checkPrivateRedeclaration(obj, privateSet);
privateSet.add(obj);
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var AgoraRTC_NProduction = {exports: {}};
(function(module,exports){!function(e,t){module.exports=t();}(commonjsGlobal,function(){function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i];}});}});}),Object.freeze(e);}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;}var n=function(e){try{return !!e();}catch(e){return !0;}},r=!n(function(){var e=function(){}.bind();return "function"!=typeof e||e.hasOwnProperty("prototype");}),s=r,o=Function.prototype,a=o.call,c=s&&o.bind.bind(a,a),d=s?c:function(e){return function(){return a.apply(e,arguments);};},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math==Math&&e;},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||function(){return this;}()||t||Function("return this")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments);}),g=d,T=g({}.toString),S=g("".slice),R=function(e){return S(T(e),8,-1);},C=R,I=d,v=function(e){if("Function"===C(e))return I(e);},y="object"==typeof document&&document.all,A={all:y,IS_HTMLDDA:void 0===y&&void 0!==y},b=A.all,w=A.IS_HTMLDDA?function(e){return "function"==typeof e||e===b;}:function(e){return "function"==typeof e;},O={},N=!n(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7;}})[1];}),D=r,P=Function.prototype.call,L=D?P.bind(P):function(){return P.apply(P,arguments);},k={},M={}.propertyIsEnumerable,U=Object.getOwnPropertyDescriptor,x=U&&!M.call({1:2},1);k.f=x?function(e){var t=U(this,e);return !!t&&t.enumerable;}:M;var V,F,B=function(e,t){return {enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t};},j=n,G=R,W=Object,H=d("".split),K=j(function(){return !W("z").propertyIsEnumerable(0);})?function(e){return "String"==G(e)?H(e,""):W(e);}:W,Y=function(e){return null==e;},q=Y,z=TypeError,J=function(e){if(q(e))throw z("Can't call method on "+e);return e;},X=K,Q=J,Z=function(e){return X(Q(e));},$=w,ee=A.all,te=A.IS_HTMLDDA?function(e){return "object"==typeof e?null!==e:$(e)||e===ee;}:function(e){return "object"==typeof e?null!==e:$(e);},ie={},ne=ie,re=h,se=w,oe=function(e){return se(e)?e:void 0;},ae=function(e,t){return arguments.length<2?oe(ne[e])||oe(re[e]):ne[e]&&ne[e][t]||re[e]&&re[e][t];},ce="undefined"!=typeof navigator&&String(navigator.userAgent)||"",de=h,le=ce,ue=de.process,he=de.Deno,pe=ue&&ue.versions||he&&he.version,_e=pe&&pe.v8;_e&&(F=(V=_e.split("."))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&le&&(!(V=le.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=le.match(/Chrome\/(\d+)/))&&(F=+V[1]);var Ee=F,me=Ee,fe=n,ge=h.String,Te=!!Object.getOwnPropertySymbols&&!fe(function(){var e=Symbol();return !ge(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41;}),Se=Te&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,Ce=w,Ie=l,ve=Object,ye=Se?function(e){return "symbol"==typeof e;}:function(e){var t=Re("Symbol");return Ce(t)&&Ie(t.prototype,ve(e));},Ae=String,be=function(e){try{return Ae(e);}catch(e){return "Object";}},we=w,Oe=be,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+" is not a function");},Pe=De,Le=Y,ke=function(e,t){var i=e[t];return Le(i)?void 0:Pe(i);},Me=L,Ue=w,xe=te,Ve=TypeError,Fe={exports:{}},Be=h,je=Object.defineProperty,Ge=function(e,t){try{je(Be,e,{value:t,configurable:!0,writable:!0});}catch(i){Be[e]=t;}return t;},We="__core-js_shared__",He=h[We]||Ge(We,{}),Ke=He;(Fe.exports=function(e,t){return Ke[e]||(Ke[e]=void 0!==t?t:{});})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ye=Fe.exports,qe=J,ze=Object,Je=function(e){return ze(qe(e));},Xe=Je,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Xe(e),t);},$e=d,et=0,tt=Math.random(),it=$e(1..toString),nt=function(e){return "Symbol("+(void 0===e?"":e)+")_"+it(++et+tt,36);},rt=Ye,st=Ze,ot=nt,at=Te,ct=Se,dt=h.Symbol,lt=rt("wks"),ut=ct?dt.for||dt:dt&&dt.withoutSetter||ot,ht=function(e){return st(lt,e)||(lt[e]=at&&st(dt,e)?dt[e]:ut("Symbol."+e)),lt[e];},pt=L,_t=te,Et=ye,mt=ke,ft=function(e,t){var i,n;if("string"===t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!xe(n=Me(i,e)))return n;if("string"!==t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;throw Ve("Can't convert object to primitive value");},gt=TypeError,Tt=ht("toPrimitive"),St=function(e,t){if(!_t(e)||Et(e))return e;var i,n=mt(e,Tt);if(n){if(void 0===t&&(t="default"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw gt("Can't convert object to primitive value");}return void 0===t&&(t="number"),ft(e,t);},Rt=ye,Ct=function(e){var t=St(e,"string");return Rt(t)?t:t+"";},It=te,vt=h.document,yt=It(vt)&&It(vt.createElement),At=function(e){return yt?vt.createElement(e):{};},bt=At,wt=!N&&!n(function(){return 7!=Object.defineProperty(bt("div"),"a",{get:function(){return 7;}}).a;}),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=Ct,Mt=Ze,Ut=wt,xt=Object.getOwnPropertyDescriptor;O.f=Ot?xt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return xt(e,t);}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t]);};var Vt=n,Ft=w,Bt=/#|\.prototype\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?Vt(t):!!t);},Gt=jt.normalize=function(e){return String(e).replace(Bt,".").toLowerCase();},Wt=jt.data={},Ht=jt.NATIVE="N",Kt=jt.POLYFILL="P",Yt=jt,qt=De,zt=r,Jt=v(v.bind),Xt=function(e,t){return qt(e),void 0===t?e:zt?Jt(e,t):function(){return e.apply(t,arguments);};},Qt={},Zt=N&&n(function(){return 42!=Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype;}),$t=te,ei=String,ti=TypeError,ii=function(e){if($t(e))return e;throw ti(ei(e)+" is not an object");},ni=N,ri=wt,si=Zt,oi=ii,ai=Ct,ci=TypeError,di=Object.defineProperty,li=Object.getOwnPropertyDescriptor,ui="enumerable",hi="configurable",pi="writable";Qt.f=ni?si?function(e,t,i){if(oi(e),t=ai(t),oi(i),"function"==typeof e&&"prototype"===t&&"value"in i&&pi in i&&!i[pi]){var n=li(e,t);n&&n[pi]&&(e[t]=i.value,i={configurable:hi in i?i[hi]:n[hi],enumerable:ui in i?i[ui]:n[ui],writable:!1});}return di(e,t,i);}:di:function(e,t,i){if(oi(e),t=ai(t),oi(i),ri)try{return di(e,t,i);}catch(e){}if("get"in i||"set"in i)throw ci("Accessors not supported");return "value"in i&&(e[t]=i.value),e;};var _i=Qt,Ei=B,mi=N?function(e,t,i){return _i.f(e,t,Ei(1,i));}:function(e,t,i){return e[t]=i,e;},fi=h,gi=f,Ti=v,Si=w,Ri=O.f,Ci=Yt,Ii=ie,vi=Xt,yi=mi,Ai=Ze,bi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e();case 1:return new e(i);case 2:return new e(i,n);}return new e(i,n,r);}return gi(e,this,arguments);};return t.prototype=e.prototype,t;},wi=function(e,t){var i,n,r,s,o,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?fi:p?fi[u]:(fi[u]||{}).prototype,m=h?Ii:Ii[u]||yi(Ii,u,{})[u],f=m.prototype;for(s in t)n=!(i=Ci(h?s:u+(p?".":"#")+s,e.forced))&&E&&Ai(E,s),a=m[s],n&&(c=e.dontCallGetSet?(l=Ri(E,s))&&l.value:E[s]),o=n&&c?c:t[s],n&&typeof a==typeof o||(d=e.bind&&n?vi(o,fi):e.wrap&&n?bi(o):_&&Si(o)?Ti(o):o,(e.sham||o&&o.sham||a&&a.sham)&&yi(d,"sham",!0),yi(m,s,d),_&&(Ai(Ii,r=u+"Prototype")||yi(Ii,r,{}),yi(Ii[r],s,o),e.real&&f&&(i||!f[s])&&yi(f,s,o)));},Oi=Math.ceil,Ni=Math.floor,Di=Math.trunc||function(e){var t=+e;return (t>0?Ni:Oi)(t);},Pi=function(e){var t=+e;return t!=t||0===t?0:Di(t);},Li=Pi,ki=Math.max,Mi=Math.min,Ui=function(e,t){var i=Li(e);return i<0?ki(i+t,0):Mi(i,t);},xi=Pi,Vi=Math.min,Fi=function(e){return e>0?Vi(xi(e),9007199254740991):0;},Bi=function(e){return Fi(e.length);},ji=Z,Gi=Ui,Wi=Bi,Hi=function(e){return function(t,i,n){var r,s=ji(t),o=Wi(s),a=Gi(n,o);if(e&&i!=i){for(;o>a;)if((r=s[a++])!=r)return !0;}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return !e&&-1;};},Ki={includes:Hi(!0),indexOf:Hi(!1)},Yi=Ki.includes;wi({target:"Array",proto:!0,forced:n(function(){return !Array(1).includes();})},{includes:function(e){return Yi(this,e,arguments.length>1?arguments[1]:void 0);}});var qi=ie,zi=function(e){return qi[e+"Prototype"];},Ji=zi("Array").includes,Xi=te,Qi=R,Zi=ht("match"),$i=function(e){var t;return Xi(e)&&(void 0!==(t=e[Zi])?!!t:"RegExp"==Qi(e));},en=TypeError,tn={};tn[ht("toStringTag")]="z";var nn="[object z]"===String(tn),rn=nn,sn=w,on=R,an=ht("toStringTag"),cn=Object,dn="Arguments"==on(function(){return arguments;}()),ln=rn?on:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t];}catch(e){}}(t=cn(e),an))?i:dn?on(t):"Object"==(n=on(t))&&sn(t.callee)?"Arguments":n;},un=ln,hn=String,pn=function(e){if("Symbol"===un(e))throw TypeError("Cannot convert a Symbol value to a string");return hn(e);},_n=ht("match"),En=wi,mn=function(e){if($i(e))throw en("The method doesn't accept regular expressions");return e;},fn=J,gn=pn,Tn=function(e){var t=/./;try{"/./"[e](t);}catch(i){try{return t[_n]=!1,"/./"[e](t);}catch(e){}}return !1;},Sn=d("".indexOf);En({target:"String",proto:!0,forced:!Tn("includes")},{includes:function(e){return !!~Sn(gn(fn(this)),gn(mn(e)),arguments.length>1?arguments[1]:void 0);}});var Rn=zi("String").includes,Cn=l,In=Ji,vn=Rn,yn=Array.prototype,An=String.prototype,bn=i(function(e){var t=e.includes;return e===yn||Cn(yn,e)&&t===yn.includes?In:"string"==typeof e||e===An||Cn(An,e)&&t===An.includes?vn:t;});let wn=!0,On=!0;function Nn(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10);}function Dn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t));};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map()),this._eventMap[t].set(n,s),r.apply(this,[e,s]);};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n]);},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t];},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e);},enumerable:!0,configurable:!0});}function Pn(e){return "boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(wn=e,e?"adapter.js logging disabled":"adapter.js logging enabled");}function Ln(e){return "boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(On=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"));}function kn(){if("object"==typeof window){if(wn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments);}}function Mn(e,t){On&&console.warn(e+" is deprecated, please use "+t+" instead.");}function Un(e){return "[object Object]"===Object.prototype.toString.call(e);}function xn(e){return Un(e)?Object.keys(e).reduce(function(t,i){const n=Un(e[i]),r=n?xn(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r});},{}):e;}function Vn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?Vn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{Vn(e,e.get(t),i);});}));}function Fn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map();if(null===t)return r;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e);}),s.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&Vn(e,i,r);});}),r;}const Bn=kn;function jn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t;};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e));}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e]);});}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t;},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio);}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return !o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Bn("chrome: "+JSON.stringify(e)),r(e);});}e.video=n(e.video);}return Bn("chrome: "+JSON.stringify(e)),r(e);},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message;}};};if(i.getUserMedia=function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(s(e));});});}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop();}),new DOMException("","NotFoundError");return e;},e=>Promise.reject(s(e))));};}}function Gn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream;}function Wn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack;},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e);},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);});},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments);};}else Dn(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));}function Hn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return {track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf;},_pc:e};};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice();};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r;};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1);};}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e));});};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1);});};}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf;}});}}function Kn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(t=>{i[t]=e.stat(t);}),t[i.id]=i;}),t;},s=function(e){return new Map(Object.keys(e).map(t=>[t,e[t]]));};if(arguments.length>=2){const n=function(e){i(s(r(e)));};return t.apply(this,[n,e]);}return new Promise((e,i)=>{t.apply(this,[function(t){e(s(r(t)));},i]);}).then(i,n);};}function Yn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>Fn(t,e.track,!0));};}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),Dn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>Fn(t,e.track,!1));};}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i);}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"));}return t.apply(this,arguments);};}function qn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0]);};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n;};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError");});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n);};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments);};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t];}),r.apply(this,arguments);};}function zn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return qn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id]);};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError");}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i;}n.apply(this,[t]);};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id);}),new RTCSessionDescription({type:t.type,sdp:i});}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id];},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"));});else {const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n);}return this.getSenders().find(e=>e.track===t);},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i]);},t=>{e[1]&&e[1].apply(null,t);},arguments[2]]):i.apply(this,arguments).then(e=>s(this,e));}};e.RTCPeerConnection.prototype[t]=n[t];});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id);}),new RTCSessionDescription({type:t.type,sdp:i});}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments);};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return ""===e.type?e:s(this,e);}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i]);}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")));};}function Jn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});}function Xn(e,t){Dn(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e;});}var Qn=Object.freeze({__proto__:null,fixNegotiationNeeded:Xn,shimAddTrackRemoveTrack:zn,shimAddTrackRemoveTrackWithNative:qn,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i);});}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"));},shimGetSendersWithDtmf:Hn,shimGetStats:Kn,shimGetUserMedia:jn,shimMediaStream:Gn,shimOnTrack:Wn,shimPeerConnection:Jn,shimSenderReceiverGetStats:Yn});function Zn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Mn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n);},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return "object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i);},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i;};}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return "audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i]);};}}}function $n(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return {receiver:this.receiver};}});}function er(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type;});}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}));});}return e;}).then(r,s);};}function tr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map());};}function ir(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),Dn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track);};}function nr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Mn("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t);});});}function rr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel);}function sr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0");});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings;}).catch(()=>{delete t.sendEncodings;})));}return n;});}function or(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return "encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e;});}function ar(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}function cr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}var dr=Object.freeze({__proto__:null,shimAddTransceiver:sr,shimCreateAnswer:cr,shimCreateOffer:ar,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e);}return !0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i);});},shimGetParameters:or,shimGetUserMedia:Zn,shimOnTrack:$n,shimPeerConnection:er,shimRTCDataChannel:rr,shimReceiverGetStats:ir,shimRemoveStream:nr,shimSenderGetStats:tr});function lr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams;}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e));},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e];}),t.apply(this,arguments);};}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e);});});}}function ur(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[];}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream;},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t);});});}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i);});}),t.apply(e,arguments);};}}function hr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r;},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r;};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.addIceCandidate=a;}function pr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(_r(e));}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n);}.bind(t));}function _r(e){return e&&void 0!==e.video?Object.assign({},e,{video:xn(e.video)}):e;}function Er(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(Mn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i]);}e.iceServers=t;}return new t(e,i);},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate});}function mr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return {receiver:this.receiver};}});}function fr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"});}return t.apply(this,arguments);};}function gr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext);}var Tr=Object.freeze({__proto__:null,shimAudioContext:gr,shimCallbacksAPI:hr,shimConstraints:_r,shimCreateOfferLegacy:fr,shimGetUserMedia:pr,shimLocalStreamsAPI:lr,shimRTCIceServerUrls:Er,shimRemoteStreamsAPI:ur,shimTrackEventTransceiver:mr}),Sr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12);}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim());},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n");},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0];},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i;},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i));},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1]);}return i;},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ");},t.parseIceOptions=function(e){return e.substring(14).split(" ");},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i;},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return "a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n";},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return {id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")};},t.writeExtmap=function(e){return "a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n";},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t;},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t);}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n";}return t;},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return {type:t.shift(),parameter:t.join(" ")};},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n";}),t;},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i;},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return {semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))};},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6);},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return {algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()};},t.getDtlsParameters=function(e,i){return {role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)};},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n";}),i;},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return {tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)};},t.writeCryptoLine=function(e){return "a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n";},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return {keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0};},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"");},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine);},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null;},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t;},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase());}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e));});const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t);});}),i;},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e);});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime);}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e);}),n;},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t));}}),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=l;})),i;},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i;},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t;},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0;},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return {port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return {port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r};}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("");},t.generateSessionId=function(){return Math.random().toString().substr(2,22);},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return "v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n";},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2);}return i?t.getDirection(i):"sendrecv";},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2);},t.isRejected=function(e){return "0"===e.split(" ",2)[1];},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return {kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")};},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return {username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]};},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return !1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return !1;return !0;},e.exports=t;}(Sr);var Rr=Sr.exports,Cr=i(Rr),Ir=e({__proto__:null,default:Cr},[Rr]);function vr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Cr.parseCandidate(e.candidate),r=Object.assign(i,n);return r.toJSON=function(){return {candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment};},r;}return new t(e);},e.RTCIceCandidate.prototype=t.prototype,Dn(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t));}function yr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Dn(e,"icecandidate",e=>{if(e.candidate){const t=Cr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24]);}return e;});}function Ar(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp;}});const i=function(e){if(!e||!e.sdp)return !1;const t=Cr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Cr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP");});},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;const i=parseInt(t[1],10);return i!=i?-1:i;},r=function(e){let i=65536;return "firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i;},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Cr.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n;},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp;},enumerable:!0,configurable:!0});}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a;}return o.apply(this,arguments);};}function br(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments);};}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e;},Dn(e,"datachannel",e=>(t(e.channel,e.target),e));}function wr(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return {completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState;},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null;},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e);},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i);}return e;},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments);};});}function Or(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i;}return i.apply(this,arguments);};}function Nr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve());});}function Dr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer";}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return ("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]));});}var Pr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Or,shimAddIceCandidateNullOrEmpty:Nr,shimConnectionState:wr,shimMaxMessageSize:Ar,shimParameterlessSetLocalDescription:Dr,shimRTCIceCandidate:vr,shimRTCIceCandidateRelayProtocol:yr,shimSendThrowTypeError:br});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=kn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Nn(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Nn(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else {if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Nn(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype;}return t;}(e),r={browserDetails:n,commonShim:Pr,extractVersion:Nn,disableLog:Pn,disableWarnings:Ln,sdp:Ir};switch(n.browser){case"chrome":if(!Qn||!Jn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Qn,Nr(e,n),Dr(e),jn(e,n),Gn(e),Jn(e,n),Wn(e),zn(e,n),Hn(e),Kn(e),Yn(e),Xn(e,n),vr(e),yr(e),wr(e),Ar(e,n),br(e),Or(e,n);break;case"firefox":if(!dr||!er||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=dr,Nr(e,n),Dr(e),Zn(e,n),er(e,n),$n(e),nr(e),tr(e),ir(e),rr(e),sr(e),or(e),ar(e),cr(e),vr(e),wr(e),Ar(e,n),br(e);break;case"safari":if(!Tr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Tr,Nr(e,n),Dr(e),Er(e),fr(e),hr(e),lr(e),ur(e),mr(e),pr(e),gr(e),vr(e),yr(e),Ar(e,n),br(e),Or(e,n);break;default:i("Unsupported browser!");}}({window:"undefined"==typeof window?void 0:window});var Lr={exports:{}},kr=wi,Mr=N,Ur=Qt.f;kr({target:"Object",stat:!0,forced:Object.defineProperty!==Ur,sham:!Mr},{defineProperty:Ur});var xr=ie.Object,Vr=Lr.exports=function(e,t,i){return xr.defineProperty(e,t,i);};xr.defineProperty.sham&&(Vr.sham=!0);var Fr=i(Lr.exports),Br=R,jr=Array.isArray||function(e){return "Array"==Br(e);},Gr=TypeError,Wr=Ct,Hr=Qt,Kr=B,Yr=function(e,t,i){var n=Wr(t);n in e?Hr.f(e,n,Kr(0,i)):e[n]=i;},qr=w,zr=He,Jr=d(Function.toString);qr(zr.inspectSource)||(zr.inspectSource=function(e){return Jr(e);});var Xr=zr.inspectSource,Qr=d,Zr=n,$r=w,es=ln,ts=Xr,is=function(){},ns=[],rs=ae("Reflect","construct"),ss=/^\s*(?:class|function)\b/,os=Qr(ss.exec),as=!ss.exec(is),cs=function(e){if(!$r(e))return !1;try{return rs(is,ns,e),!0;}catch(e){return !1;}},ds=function(e){if(!$r(e))return !1;switch(es(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return !1;}try{return as||!!os(ss,ts(e));}catch(e){return !0;}};ds.sham=!0;var ls=!rs||Zr(function(){var e;return cs(cs.call)||!cs(Object)||!cs(function(){e=!0;})||e;})?ds:cs,us=jr,hs=ls,ps=te,_s=ht("species"),Es=Array,ms=function(e){var t;return us(e)&&(t=e.constructor,(hs(t)&&(t===Es||us(t.prototype))||ps(t)&&null===(t=t[_s]))&&(t=void 0)),void 0===t?Es:t;},fs=function(e,t){return new(ms(e))(0===t?0:t);},gs=n,Ts=Ee,Ss=ht("species"),Rs=wi,Cs=n,Is=jr,vs=te,ys=Je,As=Bi,bs=function(e){if(e>9007199254740991)throw Gr("Maximum allowed index exceeded");return e;},ws=Yr,Os=fs,Ns=function(e){return Ts>=51||!gs(function(){var t=[];return (t.constructor={})[Ss]=function(){return {foo:1};},1!==t[e](Boolean).foo;});},Ds=Ee,Ps=ht("isConcatSpreadable"),Ls=Ds>=51||!Cs(function(){var e=[];return e[Ps]=!1,e.concat()[0]!==e;}),ks=function(e){if(!vs(e))return !1;var t=e[Ps];return void 0!==t?!!t:Is(e);};Rs({target:"Array",proto:!0,arity:1,forced:!Ls||!Ns("concat")},{concat:function(e){var t,i,n,r,s,o=ys(this),a=Os(o,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(ks(s=-1===t?o:arguments[t]))for(r=As(s),bs(c+r),i=0;i<r;i++,c++)i in s&&ws(a,c,s[i]);else bs(c+1),ws(a,c++,s);return a.length=c,a;}});var Ms={},Us={},xs=Ze,Vs=Z,Fs=Ki.indexOf,Bs=Us,js=d([].push),Gs=function(e,t){var i,n=Vs(e),r=0,s=[];for(i in n)!xs(Bs,i)&&xs(n,i)&&js(s,i);for(;t.length>r;)xs(n,i=t[r++])&&(~Fs(s,i)||js(s,i));return s;},Ws=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Hs=Gs,Ks=Ws,Ys=Object.keys||function(e){return Hs(e,Ks);},qs=N,zs=Zt,Js=Qt,Xs=ii,Qs=Z,Zs=Ys;Ms.f=qs&&!zs?Object.defineProperties:function(e,t){Xs(e);for(var i,n=Qs(t),r=Zs(t),s=r.length,o=0;s>o;)Js.f(e,i=r[o++],n[i]);return e;};var $s,eo=ae("document","documentElement"),to=nt,io=Ye("keys"),no=function(e){return io[e]||(io[e]=to(e));},ro=ii,so=Ms,oo=Ws,ao=Us,co=eo,lo=At,uo="prototype",ho="script",po=no("IE_PROTO"),_o=function(){},Eo=function(e){return "<"+ho+">"+e+"</"+ho+">";},mo=function(e){e.write(Eo("")),e.close();var t=e.parentWindow.Object;return e=null,t;},fo=function(){try{$s=new ActiveXObject("htmlfile");}catch(e){}var e,t,i;fo="undefined"!=typeof document?document.domain&&$s?mo($s):(t=lo("iframe"),i="java"+ho+":",t.style.display="none",co.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Eo("document.F=Object")),e.close(),e.F):mo($s);for(var n=oo.length;n--;)delete fo[uo][oo[n]];return fo();};ao[po]=!0;var go=Object.create||function(e,t){var i;return null!==e?(_o[uo]=ro(e),i=new _o(),_o[uo]=null,i[po]=e):i=fo(),void 0===t?i:so.f(i,t);},To={},So=Gs,Ro=Ws.concat("length","prototype");To.f=Object.getOwnPropertyNames||function(e){return So(e,Ro);};var Co={},Io=Ui,vo=Bi,yo=Yr,Ao=Array,bo=Math.max,wo=function(e,t,i){for(var n=vo(e),r=Io(t,n),s=Io(void 0===i?n:i,n),o=Ao(bo(s-r,0)),a=0;r<s;r++,a++)yo(o,a,e[r]);return o.length=a,o;},Oo=R,No=Z,Do=To.f,Po=wo,Lo="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Co.f=function(e){return Lo&&"Window"==Oo(e)?function(e){try{return Do(e);}catch(e){return Po(Lo);}}(e):Do(No(e));};var ko={};ko.f=Object.getOwnPropertySymbols;var Mo=mi,Uo=function(e,t,i,n){return n&&n.enumerable?e[t]=i:Mo(e,t,i),e;},xo=Qt,Vo=function(e,t,i){return xo.f(e,t,i);},Fo={},Bo=ht;Fo.f=Bo;var jo,Go,Wo,Ho=ie,Ko=Ze,Yo=Fo,qo=Qt.f,zo=function(e){var t=Ho.Symbol||(Ho.Symbol={});Ko(t,e)||qo(t,e,{value:Yo.f(e)});},Jo=L,Xo=ae,Qo=ht,Zo=Uo,$o=function(){var e=Xo("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,n=Qo("toPrimitive");t&&!t[n]&&Zo(t,n,function(e){return Jo(i,this);},{arity:1});},ea=ln,ta=nn?{}.toString:function(){return "[object "+ea(this)+"]";},ia=nn,na=Qt.f,ra=mi,sa=Ze,oa=ta,aa=ht("toStringTag"),ca=function(e,t,i,n){if(e){var r=i?e:e.prototype;sa(r,aa)||na(r,aa,{configurable:!0,value:t}),n&&!ia&&ra(r,"toString",oa);}},da=w,la=h.WeakMap,ua=da(la)&&/native code/.test(String(la)),ha=h,pa=te,_a=mi,Ea=Ze,ma=He,fa=no,ga=Us,Ta="Object already initialized",Sa=ha.TypeError,Ra=ha.WeakMap;if(ua||ma.state){var Ca=ma.state||(ma.state=new Ra());Ca.get=Ca.get,Ca.has=Ca.has,Ca.set=Ca.set,jo=function(e,t){if(Ca.has(e))throw Sa(Ta);return t.facade=e,Ca.set(e,t),t;},Go=function(e){return Ca.get(e)||{};},Wo=function(e){return Ca.has(e);};}else {var Ia=fa("state");ga[Ia]=!0,jo=function(e,t){if(Ea(e,Ia))throw Sa(Ta);return t.facade=e,_a(e,Ia,t),t;},Go=function(e){return Ea(e,Ia)?e[Ia]:{};},Wo=function(e){return Ea(e,Ia);};}var va={set:jo,get:Go,has:Wo,enforce:function(e){return Wo(e)?Go(e):jo(e,{});},getterFor:function(e){return function(t){var i;if(!pa(t)||(i=Go(t)).type!==e)throw Sa("Incompatible receiver, "+e+" required");return i;};}},ya=Xt,Aa=K,ba=Je,wa=Bi,Oa=fs,Na=d([].push),Da=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,d,l,u){for(var h,p,_=ba(c),E=Aa(_),m=ya(d,l),f=wa(E),g=0,T=u||Oa,S=t?T(c,f):i||o?T(c,0):void 0;f>g;g++)if((a||g in E)&&(p=m(h=E[g],g,_),e))if(t)S[g]=p;else if(p)switch(e){case 3:return !0;case 5:return h;case 6:return g;case 2:Na(S,h);}else switch(e){case 4:return !1;case 7:Na(S,h);}return s?-1:n||r?r:S;};},Pa={forEach:Da(0),map:Da(1),filter:Da(2),some:Da(3),every:Da(4),find:Da(5),findIndex:Da(6),filterReject:Da(7)},La=wi,ka=h,Ma=L,Ua=d,xa=N,Va=Te,Fa=n,Ba=Ze,ja=l,Ga=ii,Wa=Z,Ha=Ct,Ka=pn,Ya=B,qa=go,za=Ys,Ja=To,Xa=Co,Qa=ko,Za=O,$a=Qt,ec=Ms,tc=k,ic=Uo,nc=Vo,rc=Ye,sc=Us,oc=nt,ac=ht,cc=Fo,dc=zo,lc=$o,uc=ca,hc=va,pc=Pa.forEach,_c=no("hidden"),Ec="Symbol",mc="prototype",fc=hc.set,gc=hc.getterFor(Ec),Tc=Object[mc],Sc=ka.Symbol,Rc=Sc&&Sc[mc],Cc=ka.TypeError,Ic=ka.QObject,vc=Za.f,yc=$a.f,Ac=Xa.f,bc=tc.f,wc=Ua([].push),Oc=rc("symbols"),Nc=rc("op-symbols"),Dc=rc("wks"),Pc=!Ic||!Ic[mc]||!Ic[mc].findChild,Lc=xa&&Fa(function(){return 7!=qa(yc({},"a",{get:function(){return yc(this,"a",{value:7}).a;}})).a;})?function(e,t,i){var n=vc(Tc,t);n&&delete Tc[t],yc(e,t,i),n&&e!==Tc&&yc(Tc,t,n);}:yc,kc=function(e,t){var i=Oc[e]=qa(Rc);return fc(i,{type:Ec,tag:e,description:t}),xa||(i.description=t),i;},Mc=function(e,t,i){e===Tc&&Mc(Nc,t,i),Ga(e);var n=Ha(t);return Ga(i),Ba(Oc,n)?(i.enumerable?(Ba(e,_c)&&e[_c][n]&&(e[_c][n]=!1),i=qa(i,{enumerable:Ya(0,!1)})):(Ba(e,_c)||yc(e,_c,Ya(1,{})),e[_c][n]=!0),Lc(e,n,i)):yc(e,n,i);},Uc=function(e,t){Ga(e);var i=Wa(t),n=za(i).concat(Bc(i));return pc(n,function(t){xa&&!Ma(xc,i,t)||Mc(e,t,i[t]);}),e;},xc=function(e){var t=Ha(e),i=Ma(bc,this,t);return !(this===Tc&&Ba(Oc,t)&&!Ba(Nc,t))&&(!(i||!Ba(this,t)||!Ba(Oc,t)||Ba(this,_c)&&this[_c][t])||i);},Vc=function(e,t){var i=Wa(e),n=Ha(t);if(i!==Tc||!Ba(Oc,n)||Ba(Nc,n)){var r=vc(i,n);return !r||!Ba(Oc,n)||Ba(i,_c)&&i[_c][n]||(r.enumerable=!0),r;}},Fc=function(e){var t=Ac(Wa(e)),i=[];return pc(t,function(e){Ba(Oc,e)||Ba(sc,e)||wc(i,e);}),i;},Bc=function(e){var t=e===Tc,i=Ac(t?Nc:Wa(e)),n=[];return pc(i,function(e){!Ba(Oc,e)||t&&!Ba(Tc,e)||wc(n,Oc[e]);}),n;};Va||(Sc=function(){if(ja(Rc,this))throw Cc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Ka(arguments[0]):void 0,t=oc(e),i=function(e){this===Tc&&Ma(i,Nc,e),Ba(this,_c)&&Ba(this[_c],t)&&(this[_c][t]=!1),Lc(this,t,Ya(1,e));};return xa&&Pc&&Lc(Tc,t,{configurable:!0,set:i}),kc(t,e);},ic(Rc=Sc[mc],"toString",function(){return gc(this).tag;}),ic(Sc,"withoutSetter",function(e){return kc(oc(e),e);}),tc.f=xc,$a.f=Mc,ec.f=Uc,Za.f=Vc,Ja.f=Xa.f=Fc,Qa.f=Bc,cc.f=function(e){return kc(ac(e),e);},xa&&nc(Rc,"description",{configurable:!0,get:function(){return gc(this).description;}})),La({global:!0,constructor:!0,wrap:!0,forced:!Va,sham:!Va},{Symbol:Sc}),pc(za(Dc),function(e){dc(e);}),La({target:Ec,stat:!0,forced:!Va},{useSetter:function(){Pc=!0;},useSimple:function(){Pc=!1;}}),La({target:"Object",stat:!0,forced:!Va,sham:!xa},{create:function(e,t){return void 0===t?qa(e):Uc(qa(e),t);},defineProperty:Mc,defineProperties:Uc,getOwnPropertyDescriptor:Vc}),La({target:"Object",stat:!0,forced:!Va},{getOwnPropertyNames:Fc}),lc(),uc(Sc,Ec),sc[_c]=!0;var jc=Te&&!!Symbol.for&&!!Symbol.keyFor,Gc=wi,Wc=ae,Hc=Ze,Kc=pn,Yc=Ye,qc=jc,zc=Yc("string-to-symbol-registry"),Jc=Yc("symbol-to-string-registry");Gc({target:"Symbol",stat:!0,forced:!qc},{for:function(e){var t=Kc(e);if(Hc(zc,t))return zc[t];var i=Wc("Symbol")(t);return zc[t]=i,Jc[i]=t,i;}});var Xc=wi,Qc=Ze,Zc=ye,$c=be,ed=jc,td=Ye("symbol-to-string-registry");Xc({target:"Symbol",stat:!0,forced:!ed},{keyFor:function(e){if(!Zc(e))throw TypeError($c(e)+" is not a symbol");if(Qc(td,e))return td[e];}});var id=d([].slice),nd=jr,rd=w,sd=R,od=pn,ad=d([].push),cd=wi,dd=ae,ld=f,ud=L,hd=d,pd=n,_d=w,Ed=ye,md=id,fd=function(e){if(rd(e))return e;if(nd(e)){for(var t=e.length,i=[],n=0;n<t;n++){var r=e[n];"string"==typeof r?ad(i,r):"number"!=typeof r&&"Number"!=sd(r)&&"String"!=sd(r)||ad(i,od(r));}var s=i.length,o=!0;return function(e,t){if(o)return o=!1,t;if(nd(this))return t;for(var n=0;n<s;n++)if(i[n]===e)return t;};}},gd=Te,Td=String,Sd=dd("JSON","stringify"),Rd=hd(/./.exec),Cd=hd("".charAt),Id=hd("".charCodeAt),vd=hd("".replace),yd=hd(1..toString),Ad=/[\uD800-\uDFFF]/g,bd=/^[\uD800-\uDBFF]$/,wd=/^[\uDC00-\uDFFF]$/,Od=!gd||pd(function(){var e=dd("Symbol")();return "[null]"!=Sd([e])||"{}"!=Sd({a:e})||"{}"!=Sd(Object(e));}),Nd=pd(function(){return '"\\udf06\\ud834"'!==Sd("\udf06\ud834")||'"\\udead"'!==Sd("\udead");}),Dd=function(e,t){var i=md(arguments),n=fd(t);if(_d(n)||void 0!==e&&!Ed(e))return i[1]=function(e,t){if(_d(n)&&(t=ud(n,this,Td(e),t)),!Ed(t))return t;},ld(Sd,null,i);},Pd=function(e,t,i){var n=Cd(i,t-1),r=Cd(i,t+1);return Rd(bd,e)&&!Rd(wd,r)||Rd(wd,e)&&!Rd(bd,n)?"\\u"+yd(Id(e,0),16):e;};Sd&&cd({target:"JSON",stat:!0,arity:3,forced:Od||Nd},{stringify:function(e,t,i){var n=md(arguments),r=ld(Od?Dd:Sd,null,n);return Nd&&"string"==typeof r?vd(r,Ad,Pd):r;}});var Ld=ko,kd=Je;wi({target:"Object",stat:!0,forced:!Te||n(function(){Ld.f(1);})},{getOwnPropertySymbols:function(e){var t=Ld.f;return t?t(kd(e)):[];}}),zo("asyncIterator"),zo("hasInstance"),zo("isConcatSpreadable"),zo("iterator"),zo("match"),zo("matchAll"),zo("replace"),zo("search"),zo("species"),zo("split");var Md=$o;zo("toPrimitive"),Md();var Ud=ae,xd=ca;zo("toStringTag"),xd(Ud("Symbol"),"Symbol"),zo("unscopables"),ca(h.JSON,"JSON",!0);var Vd,Fd,Bd,jd=ie.Symbol,Gd={},Wd=N,Hd=Ze,Kd=Function.prototype,Yd=Wd&&Object.getOwnPropertyDescriptor,qd=Hd(Kd,"name"),zd={EXISTS:qd,PROPER:qd&&"something"===function(){}.name,CONFIGURABLE:qd&&(!Wd||Wd&&Yd(Kd,"name").configurable)},Jd=!n(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e())!==e.prototype;}),Xd=Ze,Qd=w,Zd=Je,$d=Jd,el=no("IE_PROTO"),tl=Object,il=tl.prototype,nl=$d?tl.getPrototypeOf:function(e){var t=Zd(e);if(Xd(t,el))return t[el];var i=t.constructor;return Qd(i)&&t instanceof i?i.prototype:t instanceof tl?il:null;},rl=n,sl=w,ol=te,al=go,cl=nl,dl=Uo,ll=ht("iterator"),ul=!1;[].keys&&("next"in(Bd=[].keys())?(Fd=cl(cl(Bd)))!==Object.prototype&&(Vd=Fd):ul=!0);var hl=!ol(Vd)||rl(function(){var e={};return Vd[ll].call(e)!==e;});sl((Vd=hl?{}:al(Vd))[ll])||dl(Vd,ll,function(){return this;});var pl={IteratorPrototype:Vd,BUGGY_SAFARI_ITERATORS:ul},_l=pl.IteratorPrototype,El=go,ml=B,fl=ca,gl=Gd,Tl=function(){return this;},Sl=function(e,t,i,n){var r=t+" Iterator";return e.prototype=El(_l,{next:ml(+!n,i)}),fl(e,r,!1,!0),gl[r]=Tl,e;},Rl=d,Cl=De,Il=w,vl=String,yl=TypeError,Al=function(e,t,i){try{return Rl(Cl(Object.getOwnPropertyDescriptor(e,t)[i]));}catch(e){}},bl=ii,wl=function(e){if("object"==typeof e||Il(e))return e;throw yl("Can't set "+vl(e)+" as a prototype");},Ol=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Al(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array;}catch(e){}return function(i,n){return bl(i),wl(n),t?e(i,n):i.__proto__=n,i;};}():void 0),Nl=wi,Dl=L,Pl=zd,Ll=Sl,kl=nl,Ml=ca,Ul=Uo,xl=Gd,Vl=pl,Fl=Pl.PROPER,Bl=Vl.BUGGY_SAFARI_ITERATORS,jl=ht("iterator"),Gl="keys",Wl="values",Hl="entries",Kl=function(){return this;},Yl=function(e,t,i,n,r,s,o){Ll(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Bl&&e in p)return p[e];switch(e){case Gl:case Wl:case Hl:return function(){return new i(this,e);};}return function(){return new i(this);};},u=t+" Iterator",h=!1,p=e.prototype,_=p[jl]||p["@@iterator"]||r&&p[r],E=!Bl&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=kl(m.call(new e())))!==Object.prototype&&a.next&&(Ml(a,u,!0,!0),xl[u]=Kl),Fl&&r==Wl&&_&&_.name!==Wl&&(h=!0,E=function(){return Dl(_,this);}),r)if(c={values:l(Wl),keys:s?E:l(Gl),entries:l(Hl)},o)for(d in c)(Bl||h||!(d in p))&&Ul(p,d,c[d]);else Nl({target:t,proto:!0,forced:Bl||h},c);return o&&p[jl]!==E&&Ul(p,jl,E,{name:r}),xl[t]=E,c;},ql=function(e,t){return {value:e,done:t};},zl=Z,Jl=Gd,Xl=va;Qt.f;var Ql=Yl,Zl=ql,$l="Array Iterator",eu=Xl.set,tu=Xl.getterFor($l);Ql(Array,"Array",function(e,t){eu(this,{type:$l,target:zl(e),index:0,kind:t});},function(){var e=tu(this),t=e.target,i=e.kind,n=e.index++;return !t||n>=t.length?(e.target=void 0,Zl(void 0,!0)):Zl("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1);},"values"),Jl.Arguments=Jl.Array;var iu={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},nu=h,ru=ln,su=mi,ou=Gd,au=ht("toStringTag");for(var cu in iu){var du=nu[cu],lu=du&&du.prototype;lu&&ru(lu)!==au&&su(lu,au,cu),ou[cu]=ou.Array;}var uu=jd,hu=ht,pu=Qt.f,_u=hu("metadata"),Eu=Function.prototype;void 0===Eu[_u]&&pu(Eu,_u,{value:null}),zo("dispose"),zo("metadata");var mu=uu;zo("asyncDispose");var fu=d,gu=ae("Symbol"),Tu=gu.keyFor,Su=fu(gu.prototype.valueOf),Ru=gu.isRegisteredSymbol||function(e){try{return void 0!==Tu(Su(e));}catch(e){return !1;}};wi({target:"Symbol",stat:!0},{isRegisteredSymbol:Ru});for(var Cu=Ye,Iu=ae,vu=d,yu=ye,Au=ht,bu=Iu("Symbol"),wu=bu.isWellKnownSymbol,Ou=Iu("Object","getOwnPropertyNames"),Nu=vu(bu.prototype.valueOf),Du=Cu("wks"),Pu=0,Lu=Ou(bu),ku=Lu.length;Pu<ku;Pu++)try{var Mu=Lu[Pu];yu(bu[Mu])&&Au(Mu);}catch(e){}var Uu=function(e){if(wu&&wu(e))return !0;try{for(var t=Nu(e),i=0,n=Ou(Du),r=n.length;i<r;i++)if(Du[n[i]]==t)return !0;}catch(e){}return !1;};wi({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Uu}),zo("matcher"),zo("observable"),wi({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:Ru}),wi({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Uu}),zo("metadataKey"),zo("patternMatch"),zo("replaceAll");var xu=i(mu),Vu=d,Fu=Pi,Bu=pn,ju=J,Gu=Vu("".charAt),Wu=Vu("".charCodeAt),Hu=Vu("".slice),Ku=function(e){return function(t,i){var n,r,s=Bu(ju(t)),o=Fu(i),a=s.length;return o<0||o>=a?e?"":void 0:(n=Wu(s,o))<55296||n>56319||o+1===a||(r=Wu(s,o+1))<56320||r>57343?e?Gu(s,o):n:e?Hu(s,o,o+2):r-56320+(n-55296<<10)+65536;};},Yu={codeAt:Ku(!1),charAt:Ku(!0)},qu=Yu.charAt,zu=pn,Ju=va,Xu=Yl,Qu=ql,Zu="String Iterator",$u=Ju.set,eh=Ju.getterFor(Zu);Xu(String,"String",function(e){$u(this,{type:Zu,string:zu(e),index:0});},function(){var e,t=eh(this),i=t.string,n=t.index;return n>=i.length?Qu(void 0,!0):(e=qu(i,n),t.index+=e.length,Qu(e,!1));});var th=i(Fo.f("iterator"));function ih(e){return ih="function"==typeof xu&&"symbol"==typeof th?function(e){return typeof e;}:function(e){return e&&"function"==typeof xu&&e.constructor===xu&&e!==xu.prototype?"symbol":typeof e;},ih(e);}var nh=i(Fo.f("toPrimitive"));function rh(e){var t=function(e,t){if("object"!==ih(e)||null===e)return e;var i=e[nh];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==ih(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.");}return ("string"===t?String:Number)(e);}(e,"string");return "symbol"===ih(t)?t:String(t);}function sh(e,t,i){return (t=rh(t))in e?Fr(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e;}var oh=zi("Array").keys,ah=ln,ch=Ze,dh=l,lh=oh,uh=Array.prototype,hh={DOMTokenList:!0,NodeList:!0},ph=i(function(e){var t=e.keys;return e===uh||dh(uh,e)&&t===uh.keys||ch(hh,ah(e))?lh:t;}),_h=be,Eh=TypeError,mh=wo,fh=Math.floor,gh=function(e,t){var i=e.length,n=fh(i/2);return i<8?Th(e,t):Sh(e,gh(mh(e,0,n),t),gh(mh(e,n),t),t);},Th=function(e,t){for(var i,n,r=e.length,s=1;s<r;){for(n=s,i=e[s];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==s++&&(e[n]=i);}return e;},Sh=function(e,t,i,n){for(var r=t.length,s=i.length,o=0,a=0;o<r||a<s;)e[o+a]=o<r&&a<s?n(t[o],i[a])<=0?t[o++]:i[a++]:o<r?t[o++]:i[a++];return e;},Rh=gh,Ch=n,Ih=function(e,t){var i=[][e];return !!i&&Ch(function(){i.call(null,t||function(){return 1;},1);});},vh=ce.match(/firefox\/(\d+)/i),yh=!!vh&&+vh[1],Ah=/MSIE|Trident/.test(ce),bh=ce.match(/AppleWebKit\/(\d+)\./),wh=!!bh&&+bh[1],Oh=wi,Nh=d,Dh=De,Ph=Je,Lh=Bi,kh=function(e,t){if(!delete e[t])throw Eh("Cannot delete property "+_h(t)+" of "+_h(e));},Mh=pn,Uh=n,xh=Rh,Vh=Ih,Fh=yh,Bh=Ah,jh=Ee,Gh=wh,Wh=[],Hh=Nh(Wh.sort),Kh=Nh(Wh.push),Yh=Uh(function(){Wh.sort(void 0);}),qh=Uh(function(){Wh.sort(null);}),zh=Vh("sort"),Jh=!Uh(function(){if(jh)return jh<70;if(!(Fh&&Fh>3)){if(Bh)return !0;if(Gh)return Gh<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2;}for(n=0;n<47;n++)Wh.push({k:t+n,v:i});}for(Wh.sort(function(e,t){return t.v-e.v;}),n=0;n<Wh.length;n++)t=Wh[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return "DGBEFHACIJK"!==r;}});Oh({target:"Array",proto:!0,forced:Yh||!qh||!zh||!Jh},{sort:function(e){void 0!==e&&Dh(e);var t=Ph(this);if(Jh)return void 0===e?Hh(t):Hh(t,e);var i,n,r=[],s=Lh(t);for(n=0;n<s;n++)n in t&&Kh(r,t[n]);for(xh(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Mh(t)>Mh(i)?1:-1;};}(e)),i=Lh(r),n=0;n<i;)t[n]=r[n++];for(;n<s;)kh(t,n++);return t;}});var Xh=zi("Array").sort,Qh=l,Zh=Xh,$h=Array.prototype,ep=i(function(e){var t=e.sort;return e===$h||Qh($h,e)&&t===$h.sort?Zh:t;}),tp=ae,ip=To,np=ko,rp=ii,sp=d([].concat),op=tp("Reflect","ownKeys")||function(e){var t=ip.f(rp(e)),i=np.f;return i?sp(t,i(e)):t;},ap=Ze,cp=op,dp=O,lp=Qt,up=te,hp=mi,pp=Error,_p=d("".replace),Ep=String(pp("zxcasd").stack),mp=/\n\s*at [^:]*:[^\n]*/,fp=mp.test(Ep),gp=B,Tp=!n(function(){var e=Error("a");return !("stack"in e)||(Object.defineProperty(e,"stack",gp(1,7)),7!==e.stack);}),Sp=mi,Rp=function(e,t){if(fp&&"string"==typeof e&&!pp.prepareStackTrace)for(;t--;)e=_p(e,mp,"");return e;},Cp=Tp,Ip=Error.captureStackTrace,vp=Gd,yp=ht("iterator"),Ap=Array.prototype,bp=function(e){return void 0!==e&&(vp.Array===e||Ap[yp]===e);},wp=ln,Op=ke,Np=Y,Dp=Gd,Pp=ht("iterator"),Lp=function(e){if(!Np(e))return Op(e,Pp)||Op(e,"@@iterator")||Dp[wp(e)];},kp=L,Mp=De,Up=ii,xp=be,Vp=Lp,Fp=TypeError,Bp=function(e,t){var i=arguments.length<2?Vp(e):t;if(Mp(i))return Up(kp(i,e));throw Fp(xp(e)+" is not iterable");},jp=L,Gp=ii,Wp=ke,Hp=function(e,t,i){var n,r;Gp(e);try{if(!(n=Wp(e,"return"))){if("throw"===t)throw i;return i;}n=jp(n,e);}catch(e){r=!0,n=e;}if("throw"===t)throw i;if(r)throw n;return Gp(n),i;},Kp=Xt,Yp=L,qp=ii,zp=be,Jp=bp,Xp=Bi,Qp=l,Zp=Bp,$p=Lp,e_=Hp,t_=TypeError,i_=function(e,t){this.stopped=e,this.result=t;},n_=i_.prototype,r_=function(e,t,i){var n,r,s,o,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=Kp(t,l),m=function(e){return n&&e_(n,"normal",e),new i_(!0,e);},f=function(e){return u?(qp(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e);};if(h)n=e.iterator;else if(p)n=e;else {if(!(r=$p(e)))throw t_(zp(e)+" is not iterable");if(Jp(r)){for(s=0,o=Xp(e);o>s;s++)if((a=f(e[s]))&&Qp(n_,a))return a;return new i_(!1);}n=Zp(e,r);}for(c=h?e.next:n.next;!(d=Yp(c,n)).done;){try{a=f(d.value);}catch(e){e_(n,"throw",e);}if("object"==typeof a&&a&&Qp(n_,a))return a;}return new i_(!1);},s_=pn,o_=wi,a_=l,c_=nl,d_=Ol,l_=function(e,t,i){for(var n=cp(t),r=lp.f,s=dp.f,o=0;o<n.length;o++){var a=n[o];ap(e,a)||i&&ap(i,a)||r(e,a,s(t,a));}},u_=go,h_=mi,p_=B,__=function(e,t){up(t)&&"cause"in t&&hp(e,"cause",t.cause);},E_=function(e,t,i,n){Cp&&(Ip?Ip(e,t):Sp(e,"stack",Rp(i,n)));},m_=r_,f_=function(e,t){return void 0===e?arguments.length<2?"":t:s_(e);},g_=ht("toStringTag"),T_=Error,S_=[].push,R_=function(e,t){var i,n=a_(C_,this);d_?i=d_(T_(),n?c_(this):C_):(i=n?this:u_(C_),h_(i,g_,"Error")),void 0!==t&&h_(i,"message",f_(t)),E_(i,R_,i.stack,1),arguments.length>2&&__(i,arguments[2]);var r=[];return m_(e,S_,{that:r}),h_(i,"errors",r),i;};d_?d_(R_,T_):l_(R_,T_,{name:!0});var C_=R_.prototype=u_(T_.prototype,{constructor:p_(1,R_),message:p_(1,""),name:p_(1,"AggregateError")});o_({global:!0,constructor:!0,arity:2},{AggregateError:R_});var I_,v_,y_,A_,b_="undefined"!=typeof process&&"process"==R(process),w_=ae,O_=Vo,N_=N,D_=ht("species"),P_=l,L_=TypeError,k_=function(e,t){if(P_(t,e))return e;throw L_("Incorrect invocation");},M_=ls,U_=be,x_=TypeError,V_=ii,F_=function(e){if(M_(e))return e;throw x_(U_(e)+" is not a constructor");},B_=Y,j_=ht("species"),G_=function(e,t){var i,n=V_(e).constructor;return void 0===n||B_(i=V_(n)[j_])?t:F_(i);},W_=TypeError,H_=function(e,t){if(e<t)throw W_("Not enough arguments");return e;},K_=/(?:ipad|iphone|ipod).*applewebkit/i.test(ce),Y_=h,q_=f,z_=Xt,J_=w,X_=Ze,Q_=n,Z_=eo,$_=id,eE=At,tE=H_,iE=K_,nE=b_,rE=Y_.setImmediate,sE=Y_.clearImmediate,oE=Y_.process,aE=Y_.Dispatch,cE=Y_.Function,dE=Y_.MessageChannel,lE=Y_.String,uE=0,hE={},pE="onreadystatechange";Q_(function(){I_=Y_.location;});var _E=function(e){if(X_(hE,e)){var t=hE[e];delete hE[e],t();}},EE=function(e){return function(){_E(e);};},mE=function(e){_E(e.data);},fE=function(e){Y_.postMessage(lE(e),I_.protocol+"//"+I_.host);};rE&&sE||(rE=function(e){tE(arguments.length,1);var t=J_(e)?e:cE(e),i=$_(arguments,1);return hE[++uE]=function(){q_(t,void 0,i);},v_(uE),uE;},sE=function(e){delete hE[e];},nE?v_=function(e){oE.nextTick(EE(e));}:aE&&aE.now?v_=function(e){aE.now(EE(e));}:dE&&!iE?(A_=(y_=new dE()).port2,y_.port1.onmessage=mE,v_=z_(A_.postMessage,A_)):Y_.addEventListener&&J_(Y_.postMessage)&&!Y_.importScripts&&I_&&"file:"!==I_.protocol&&!Q_(fE)?(v_=fE,Y_.addEventListener("message",mE,!1)):v_=pE in eE("script")?function(e){Z_.appendChild(eE("script"))[pE]=function(){Z_.removeChild(this),_E(e);};}:function(e){setTimeout(EE(e),0);});var gE={set:rE,clear:sE},TE=function(){this.head=null,this.tail=null;};TE.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t;},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item;}};var SE,RE,CE,IE,vE,yE=TE,AE=/ipad|iphone|ipod/i.test(ce)&&"undefined"!=typeof Pebble,bE=/web0s(?!.*chrome)/i.test(ce),wE=h,OE=Xt,NE=O.f,DE=gE.set,PE=yE,LE=K_,kE=AE,ME=bE,UE=b_,xE=wE.MutationObserver||wE.WebKitMutationObserver,VE=wE.document,FE=wE.process,BE=wE.Promise,jE=NE(wE,"queueMicrotask"),GE=jE&&jE.value;if(!GE){var WE=new PE(),HE=function(){var e,t;for(UE&&(e=FE.domain)&&e.exit();t=WE.get();)try{t();}catch(e){throw WE.head&&SE(),e;}e&&e.enter();};LE||UE||ME||!xE||!VE?!kE&&BE&&BE.resolve?((IE=BE.resolve(void 0)).constructor=BE,vE=OE(IE.then,IE),SE=function(){vE(HE);}):UE?SE=function(){FE.nextTick(HE);}:(DE=OE(DE,wE),SE=function(){DE(HE);}):(RE=!0,CE=VE.createTextNode(""),new xE(HE).observe(CE,{characterData:!0}),SE=function(){CE.data=RE=!RE;}),GE=function(e){WE.head||SE(),WE.add(e);};}var KE=GE,YE=function(e){try{return {error:!1,value:e()};}catch(e){return {error:!0,value:e};}},qE=h.Promise,zE="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,JE=!zE&&!b_&&"object"==typeof window&&"object"==typeof document,XE=h,QE=qE,ZE=w,$E=Yt,em=Xr,tm=ht,im=JE,nm=zE,rm=Ee,sm=QE&&QE.prototype,om=tm("species"),am=!1,cm=ZE(XE.PromiseRejectionEvent),dm=$E("Promise",function(){var e=em(QE),t=e!==String(QE);if(!t&&66===rm)return !0;if(!sm.catch||!sm.finally)return !0;if(!rm||rm<51||!/native code/.test(e)){var i=new QE(function(e){e(1);}),n=function(e){e(function(){},function(){});};if((i.constructor={})[om]=n,!(am=i.then(function(){})instanceof n))return !0;}return !t&&(im||nm)&&!cm;}),lm={CONSTRUCTOR:dm,REJECTION_EVENT:cm,SUBCLASSING:am},um={},hm=De,pm=TypeError,_m=function(e){var t,i;this.promise=new e(function(e,n){if(void 0!==t||void 0!==i)throw pm("Bad Promise constructor");t=e,i=n;}),this.resolve=hm(t),this.reject=hm(i);};um.f=function(e){return new _m(e);};var Em,mm,fm=wi,gm=b_,Tm=h,Sm=L,Rm=Uo,Cm=ca,Im=function(e){var t=w_(e);N_&&t&&!t[D_]&&O_(t,D_,{configurable:!0,get:function(){return this;}});},vm=De,ym=w,Am=te,bm=k_,wm=G_,Om=gE.set,Nm=KE,Dm=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t);}catch(e){}},Pm=YE,Lm=yE,km=va,Mm=qE,Um=lm,xm=um,Vm="Promise",Fm=Um.CONSTRUCTOR,Bm=Um.REJECTION_EVENT,jm=km.getterFor(Vm),Gm=km.set,Wm=Mm&&Mm.prototype,Hm=Mm,Km=Wm,Ym=Tm.TypeError,qm=Tm.document,zm=Tm.process,Jm=xm.f,Xm=Jm,Qm=!!(qm&&qm.createEvent&&Tm.dispatchEvent),Zm="unhandledrejection",$m=function(e){var t;return !(!Am(e)||!ym(t=e.then))&&t;},ef=function(e,t){var i,n,r,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(o||(2===t.rejection&&of(t),t.rejection=1),!0===a?i=s:(l&&l.enter(),i=a(s),l&&(l.exit(),r=!0)),i===e.promise?d(Ym("Promise-chain cycle")):(n=$m(i))?Sm(n,i,c,d):c(i)):d(s);}catch(e){l&&!r&&l.exit(),d(e);}},tf=function(e,t){e.notified||(e.notified=!0,Nm(function(){for(var i,n=e.reactions;i=n.get();)ef(i,e);e.notified=!1,t&&!e.rejection&&rf(e);}));},nf=function(e,t,i){var n,r;Qm?((n=qm.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),Tm.dispatchEvent(n)):n={promise:t,reason:i},!Bm&&(r=Tm["on"+e])?r(n):e===Zm&&Dm("Unhandled promise rejection",i);},rf=function(e){Sm(Om,Tm,function(){var t,i=e.facade,n=e.value;if(sf(e)&&(t=Pm(function(){gm?zm.emit("unhandledRejection",n,i):nf(Zm,i,n);}),e.rejection=gm||sf(e)?2:1,t.error))throw t.value;});},sf=function(e){return 1!==e.rejection&&!e.parent;},of=function(e){Sm(Om,Tm,function(){var t=e.facade;gm?zm.emit("rejectionHandled",t):nf("rejectionhandled",t,e.value);});},af=function(e,t,i){return function(n){e(t,n,i);};},cf=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,tf(e,!0));},df=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Ym("Promise can't be resolved itself");var n=$m(t);n?Nm(function(){var i={done:!1};try{Sm(n,t,af(df,i,e),af(cf,i,e));}catch(t){cf(i,t,e);}}):(e.value=t,e.state=1,tf(e,!1));}catch(t){cf({done:!1},t,e);}}};Fm&&(Km=(Hm=function(e){bm(this,Km),vm(e),Sm(Em,this);var t=jm(this);try{e(af(df,t),af(cf,t));}catch(e){cf(t,e);}}).prototype,(Em=function(e){Gm(this,{type:Vm,done:!1,notified:!1,parent:!1,reactions:new Lm(),rejection:!1,state:0,value:void 0});}).prototype=Rm(Km,"then",function(e,t){var i=jm(this),n=Jm(wm(this,Hm));return i.parent=!0,n.ok=!ym(e)||e,n.fail=ym(t)&&t,n.domain=gm?zm.domain:void 0,0==i.state?i.reactions.add(n):Nm(function(){ef(n,i);}),n.promise;}),mm=function(){var e=new Em(),t=jm(e);this.promise=e,this.resolve=af(df,t),this.reject=af(cf,t);},xm.f=Jm=function(e){return e===Hm||undefined===e?new mm(e):Xm(e);}),fm({global:!0,constructor:!0,wrap:!0,forced:Fm},{Promise:Hm}),Cm(Hm,Vm,!1,!0),Im(Vm);var lf=ht("iterator"),uf=!1;try{var hf=0,pf={next:function(){return {done:!!hf++};},return:function(){uf=!0;}};pf[lf]=function(){return this;},Array.from(pf,function(){throw 2;});}catch(e){}var _f=qE,Ef=function(e,t){if(!t&&!uf)return !1;var i=!1;try{var n={};n[lf]=function(){return {next:function(){return {done:i=!0};}};},e(n);}catch(e){}return i;},mf=lm.CONSTRUCTOR||!Ef(function(e){_f.all(e).then(void 0,function(){});}),ff=L,gf=De,Tf=um,Sf=YE,Rf=r_;wi({target:"Promise",stat:!0,forced:mf},{all:function(e){var t=this,i=Tf.f(t),n=i.resolve,r=i.reject,s=Sf(function(){var i=gf(t.resolve),s=[],o=0,a=1;Rf(e,function(e){var c=o++,d=!1;a++,ff(i,t,e).then(function(e){d||(d=!0,s[c]=e,--a||n(s));},r);}),--a||n(s);});return s.error&&r(s.value),i.promise;}});var Cf=wi,If=lm.CONSTRUCTOR;qE&&qE.prototype,Cf({target:"Promise",proto:!0,forced:If,real:!0},{catch:function(e){return this.then(void 0,e);}});var vf=L,yf=De,Af=um,bf=YE,wf=r_;wi({target:"Promise",stat:!0,forced:mf},{race:function(e){var t=this,i=Af.f(t),n=i.reject,r=bf(function(){var r=yf(t.resolve);wf(e,function(e){vf(r,t,e).then(i.resolve,n);});});return r.error&&n(r.value),i.promise;}});var Of=L,Nf=um;wi({target:"Promise",stat:!0,forced:lm.CONSTRUCTOR},{reject:function(e){var t=Nf.f(this);return Of(t.reject,void 0,e),t.promise;}});var Df=ii,Pf=te,Lf=um,kf=function(e,t){if(Df(e),Pf(t)&&t.constructor===e)return t;var i=Lf.f(e);return (0, i.resolve)(t),i.promise;},Mf=wi,Uf=qE,xf=lm.CONSTRUCTOR,Vf=kf,Ff=ae("Promise"),Bf=!xf;Mf({target:"Promise",stat:!0,forced:true},{resolve:function(e){return Vf(Bf&&this===Ff?Uf:this,e);}});var jf=L,Gf=De,Wf=um,Hf=YE,Kf=r_;wi({target:"Promise",stat:!0,forced:mf},{allSettled:function(e){var t=this,i=Wf.f(t),n=i.resolve,r=i.reject,s=Hf(function(){var i=Gf(t.resolve),r=[],s=0,o=1;Kf(e,function(e){var a=s++,c=!1;o++,jf(i,t,e).then(function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--o||n(r));},function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--o||n(r));});}),--o||n(r);});return s.error&&r(s.value),i.promise;}});var Yf=L,qf=De,zf=ae,Jf=um,Xf=YE,Qf=r_,Zf="No one promise resolved";wi({target:"Promise",stat:!0,forced:mf},{any:function(e){var t=this,i=zf("AggregateError"),n=Jf.f(t),r=n.resolve,s=n.reject,o=Xf(function(){var n=qf(t.resolve),o=[],a=0,c=1,d=!1;Qf(e,function(e){var l=a++,u=!1;c++,Yf(n,t,e).then(function(e){u||d||(d=!0,r(e));},function(e){u||d||(u=!0,o[l]=e,--c||s(new i(o,Zf)));});}),--c||s(new i(o,Zf));});return o.error&&s(o.value),n.promise;}});var $f=wi,eg=qE,tg=n,ig=ae,ng=w,rg=G_,sg=kf,og=eg&&eg.prototype;$f({target:"Promise",proto:!0,real:!0,forced:!!eg&&tg(function(){og.finally.call({then:function(){}},function(){});})},{finally:function(e){var t=rg(this,ig("Promise")),i=ng(e);return this.then(i?function(i){return sg(t,e()).then(function(){return i;});}:e,i?function(i){return sg(t,e()).then(function(){throw i;});}:e);}});var ag=ie.Promise,cg=i(ag);const dg=()=>{};function lg(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:dg};return e.promise=new cg((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i);},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t));};}),e;}const ug=new Map(),hg=new Map(),pg=new Map();var _g,Eg;!function(e){e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot";}(_g||(_g={})),function(e){e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger";}(Eg||(Eg={}));var mg={exports:{}};!function(e,i){!function(t,n){var r="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",h="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",g="smarttv",T="wearable",S="embedded",R="Amazon",C="Apple",I="ASUS",v="BlackBerry",y="Browser",A="Chrome",b="Firefox",w="Google",O="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",x="Xiaomi",V="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t;},W=function(e,t){return typeof e===a&&-1!==H(t).indexOf(H(e));},H=function(e){return e.toLowerCase();},K=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,350);},Y=function(e,t){for(var i,s,a,c,d,l,u=0;u<t.length&&!d;){var h=t[u],p=t[u+1];for(i=s=0;i<h.length&&!d&&h[i];)if(d=h[i++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===o&&c.length>0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2;}},q=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(W(t[i][r],e))return "?"===i?n:i;}else if(W(t[i],e))return "?"===i?n:i;return e;},z={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},J={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+y],p],[/\bfocus\/([\w\.]+)/i],[p,[l,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[p,[l,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+y],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,A+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,A+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,q,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,H]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[h,k],[u,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[h,k],[u,m]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[h,C],[u,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[h,C],[u,f]],[/(macintosh);/i],[d,[h,C]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[h,M],[u,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[h,O],[u,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[h,O],[u,m]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[h,x],[u,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[h,x],[u,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[h,"OPPO"],[u,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[h,"Vivo"],[u,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[h,"Realme"],[u,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[h,P],[u,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[h,P],[u,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[h,N],[u,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[h,N],[u,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[h,"Lenovo"],[u,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[h,"Nokia"],[u,m]],[/(pixel c)\b/i],[d,[h,w],[u,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[h,w],[u,m]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[h,U],[u,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[h,U],[u,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[h,"OnePlus"],[u,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[h,R],[u,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[h,R],[u,m]],[/(playbook);[-\w\),; ]+(rim)/i],[d,h,[u,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[h,v],[u,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[h,I],[u,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[h,I],[u,m]],[/(nexus 9)/i],[d,[h,"HTC"],[u,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[d,/_/g," "],[u,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[h,"Acer"],[u,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[h,"Meizu"],[u,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[h,d,[u,m]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[h,d,[u,f]],[/(surface duo)/i],[d,[h,D],[u,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[h,"Fairphone"],[u,m]],[/(u304aa)/i],[d,[h,"AT&T"],[u,m]],[/\bsie-(\w*)/i],[d,[h,"Siemens"],[u,m]],[/\b(rct\w+) b/i],[d,[h,"RCA"],[u,f]],[/\b(venue[\d ]{2,7}) b/i],[d,[h,"Dell"],[u,f]],[/\b(q(?:mv|ta)\w+) b/i],[d,[h,"Verizon"],[u,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[h,"Barnes & Noble"],[u,f]],[/\b(tm\d{3}\w+) b/i],[d,[h,"NuVision"],[u,f]],[/\b(k88) b/i],[d,[h,"ZTE"],[u,f]],[/\b(nx\d{3}j) b/i],[d,[h,"ZTE"],[u,m]],[/\b(gen\d{3}) b.+49h/i],[d,[h,"Swiss"],[u,m]],[/\b(zur\d{3}) b/i],[d,[h,"Swiss"],[u,f]],[/\b((zeki)?tb.*\b) b/i],[d,[h,"Zeki"],[u,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],d,[u,f]],[/\b(ns-?\w{0,9}) b/i],[d,[h,"Insignia"],[u,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[h,"NextBook"],[u,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],d,[u,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],d,[u,m]],[/\b(ph-1) /i],[d,[h,"Essential"],[u,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[h,"Envizen"],[u,f]],[/\b(trio[-\w\. ]+) b/i],[d,[h,"MachSpeed"],[u,f]],[/\btu_(1491) b/i],[d,[h,"Rotor"],[u,f]],[/(shield[\w ]+) b/i],[d,[h,"Nvidia"],[u,f]],[/(sprint) (\w+)/i],[h,d,[u,m]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[h,D],[u,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[h,V],[u,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[h,V],[u,m]],[/smart-tv.+(samsung)/i],[h,[u,g]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[h,k],[u,g]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,N],[u,g]],[/(apple) ?tv/i],[h,[d,C+" TV"],[u,g]],[/crkey/i],[[d,A+"cast"],[h,w],[u,g]],[/droid.+aft(\w)( bui|\))/i],[d,[h,R],[u,g]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[h,M],[u,g]],[/(bravia[\w ]+)( bui|\))/i],[d,[h,U],[u,g]],[/(mitv-\w{5}) bui/i],[d,[h,x],[u,g]],[/Hbbtv.*(technisat) (.*);/i],[h,d,[u,g]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,K],[d,K],[u,g]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,d,[u,E]],[/droid.+; (shield) bui/i],[d,[h,"Nvidia"],[u,E]],[/(playstation [345portablevi]+)/i],[d,[h,U],[u,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[h,D],[u,E]],[/((pebble))app/i],[h,d,[u,T]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[h,C],[u,T]],[/droid.+; (glass) \d/i],[d,[h,w],[u,T]],[/droid.+; (wt63?0{2,3})\)/i],[d,[h,V],[u,T]],[/(quest( 2| pro)?)/i],[d,[h,F],[u,T]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,S]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[u,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,m]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,q,z]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,q,z]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,j],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,v]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,A+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},X=function(e,i){if(typeof e===o&&(i=e,e=n),!(this instanceof X))return new X(e,i).getResult();var E=typeof t!==s&&t.navigator?t.navigator:n,g=e||(E&&E.userAgent?E.userAgent:""),T=E&&E.userAgentData?E.userAgentData:n,S=i?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i;}(J,i):J;return this.getBrowser=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.browser),e[c]=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n;}(e[p]),E&&E.brave&&typeof E.brave.isBrave==r&&(e[l]="Brave"),e;},this.getCPU=function(){var e={};return e[_]=n,Y.call(e,g,S.cpu),e;},this.getDevice=function(){var e={};return e[h]=n,e[d]=n,e[u]=n,Y.call(e,g,S.device),!e[u]&&T&&T.mobile&&(e[u]=m),"Macintosh"==e[d]&&E&&typeof E.standalone!==s&&E.maxTouchPoints&&E.maxTouchPoints>2&&(e[d]="iPad",e[u]=f),e;},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.engine),e;},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.os),!e[l]&&T&&"Unknown"!=T.platform&&(e[l]=T.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e;},this.getResult=function(){return {ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()};},this.getUA=function(){return g;},this.setUA=function(e){return g=typeof e===a&&e.length>350?K(e,350):e,this;},this.setUA(g),this;};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,h,u,E,m,g,f,T,S]),X.ENGINE=X.OS=G([l,p]),e.exports&&(i=e.exports=X),i.UAParser=X;var Q=typeof t!==s&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new X();Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA();},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i];};}}("object"==typeof window?window:t);}(mg,mg.exports);const fg=new(i(mg.exports))();let gg=fg.getResult(),Tg=null;function Sg(e){if(!Tg){e&&fg.setUA(e),gg=fg.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return Eg.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return Eg.CHROME;case"Safari":case"Mobile Safari":return Eg.SAFARI;case"Edge":return Eg.EDGE;case"Firefox":return Eg.FIREFOX;case"QQBrowser":return Eg.QQ;case"Opera":return Eg.OPERA;case"WeChat":return Eg.WECHAT;default:return e.browser.name||"";}}(gg),i=function(e){let t;t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"";return t.split(".")[0];}(gg),n=function(e){if("Windows"===e.os.name)return e.os.version?e.os.name+" "+e.os.version:e.os.name;return e.os.name||"";}(gg),r=gg.os.version;if(!(t&&i&&n&&r))return {name:t,version:i,os:n,osVersion:r};Tg={name:t,version:i,os:n,osVersion:r};}return Tg;}function Rg(){return Sg().os;}function Cg(){const e=Sg();return "".concat(e.os," ").concat(e.osVersion);}function Ig(){const e=Sg();return !!("WebKit"===gg.engine.name&&e.os===_g.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Eg.SAFARI||Og()&&e.name!==Eg.SAFARI);}function vg(){const e=Sg();if(Ig()){if(e.os===_g.MAC_OS)return !0;if(e.os===_g.IOS){const e=gg.os.version&&gg.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return !0;if(e&&Number(e[0])>14)return !0;}}return !1;}function yg(){return "WebKit"===gg.engine.name;}function Ag(){return Sg().name===Eg.CHROME;}function bg(){return Sg().name===Eg.SAFARI;}function wg(){return Sg().name===Eg.FIREFOX;}function Og(){return Sg().os===_g.IOS;}function Ng(e){const t=Sg();return !(t.name!==Eg.CHROME||!t.osVersion)&&Number(t.version)>=e;}function Dg(e){const t=Sg();return !(t.name!==Eg.EDGE||!t.osVersion)&&Number(t.version)>=e;}function Pg(e){const t=Sg();return !(t.name!==Eg.OPERA||!t.osVersion)&&Number(t.version)>=e;}function Lg(){const e=Sg();return !(e.name!==Eg.CHROME||!e.osVersion)&&Number(e.version)<=90;}function kg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6;}function Mg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0]);}function Ug(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 16===Number(t[0]);}function xg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1;}function Vg(){return bg()&&navigator.maxTouchPoints>0;}function Fg(){return Sg().name===Eg.WECHAT;}function Bg(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35;}function jg(){const e=Sg();if(e.name===Eg.EDGE||e.name===Eg.SAFARI)return !1;return !!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i);}function Gg(){return Rg()===_g.ANDROID;}function Wg(){const e=Sg();return Gg()&&(e.name===Eg.CHROME||e.name===Eg.WECHAT||/chrome|chromium/i.test(navigator.userAgent));}var Hg;!function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED";}(Hg||(Hg={}));let Kg=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),sh(this,"code",void 0),sh(this,"message",void 0),sh(this,"data",void 0),sh(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i;}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack);}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return "error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this;}throw(e){throw this.print("error",e),this;}};function Yg(e,t){if("boolean"!=typeof e)throw new Kg(Hg.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."));}function qg(e,t,i){if(bn(i).call(i,e))return;throw new Kg(Hg.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)));}function zg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<i||e>n||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return "number"==typeof e&&e%1==0;}(e)){throw new Kg(Hg.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"));}}function Jg(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact)){throw new Kg(Hg.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));}void 0!==e.min&&zg(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&zg(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&zg(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&zg(e.ideal,"".concat(t,".ideal"),1,1/0);}else zg(e,t,1,1/0);}function Xg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Kg(Hg.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!$g(e,i,n,r))throw new Kg(Hg.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""));}function Qg(e,t){if(!Array.isArray(e))throw new Kg(Hg.INVALID_PARAMS,"".concat(t," should be an array"));}function Zg(e){return null==e;}function $g(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return "string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return !1;for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return !1;}return !0;}(e));}function eT(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),s=Number(!!i),o=Number(!i);return BigInt(n*o+r*s)<<BigInt(32)|BigInt(n*s+r*o);}function tT(e,t,i,n){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,n);const r=Number(i>>BigInt(32)),s=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,s,n)):(e.setUint32(t,r,n),e.setUint32(t+4,s,n));}var iT,nT;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE";}(iT||(iT={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT";}(nT||(nT={}));const rT=new class{constructor(){sh(this,"_clientSize",null),sh(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),sh(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),sh(this,"getStyle",e=>window.getComputedStyle(e,null)),sh(this,"checkCssVisibleProperty",e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:s,opacity:o,filter:a}=n;if(("none"===r||bn(t=["hidden","collapse"]).call(t,s)||Number(o)<.1)&&(i=!1),!i)return !1;if(a){a.split(" ").filter(e=>{var t;const i=e.split("(")[0];return bn(t=["brightness","blur","opacity"]).call(t,i);}).map(e=>{const[t,i]=e.split(/\(|\)/);return [t,Number(i.match(/^[0-9\.]+/))];}).forEach(e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1);}});}return i;}),sh(this,"checkPropertyUpToAllParentNodes",(e,t)=>{let i=!0,n=!0;const r=e=>t(e);let s=e;for(;s&&n;){r(s)||(i=!1,n=!1),s=s.parentElement,s||(n=!1);}return i;}),sh(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),sh(this,"getSizeAboutClient",e=>{const{width:t,height:i,left:n,right:r,top:s,bottom:o}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return {width:t,height:i,left:n,right:r,top:s,bottom:o,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)};}),sh(this,"checkActualSize",()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i);}),sh(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),sh(this,"checkCoverForAPoint",(e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i;}),sh(this,"getPointPositionList",()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,s=t/6,o=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(s*t*a-1e5)/a:s*t)*a)/a;o.push({x:c,y:d});}return [...o];}),sh(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),sh(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),sh(this,"checkSizeOfPartInClient",()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:s,clientMin:o}=this._clientSize;let a,c,d,l;if(e<0)a=0;else {if(!(e<s))return !1;a=e;}if(t<0)return !1;if(c=t<s?t:s,i<0)d=0;else {if(!(i<r))return !1;d=i;}if(n<0)return !1;l=n<r?n:r;const u=c-a,h=l-d;return this.checkSizeIsVisible(u,h,o);}),sh(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),sh(this,"checkOneElementVisible",e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(iT.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(iT.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(iT.SIZE);}}return this.returnHiddenResult(iT.STYLE);}return this.returnHiddenResult(nT.UNMOUNTED);}return this.returnHiddenResult(nT.INVALID_HTML_ELEMENT);}),sh(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement));}}();function sT(e){return new TextEncoder().encode(e);}const oT=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i;};const aT=async e=>{const t=function(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i;}("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=sT(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return function(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t);}(new Uint8Array(r));},cT=async e=>function(e,t){let i="";return new Uint8Array(e).forEach(e=>{i+=e.toString(t).padStart(2,"0");}),i;}(await crypto.subtle.digest("SHA-256",sT(e)),16);class dT{constructor(){sh(this,"_events",{}),sh(this,"addListener",this.on);}getListeners(e){return this._events[e]?this._events[e].map(e=>e.listener):[];}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1});}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0});}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e];}removeAllListeners(e){e?delete this._events[e]:this._events={};}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map(e=>e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[]);}}safeEmit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];[...(this._events[e]||[])].forEach(t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i);}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()));}});}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return -1;}}let lT=null;function uT(){if(lT)return lT;if(window.electron)return lT=window.electron;if(!window.require)return null;try{return lT=window.require("electron"),lT;}catch(e){return null;}}var hT,pT,_T,ET,mT,fT,gT,TT;function ST(e){return zg(e.timeout,"config.timeout",0,1e5),zg(e.timeoutFactor,"config.timeoutFactor",0,100,!1),zg(e.maxRetryCount,"config.maxRetryConfig",0,1/0),zg(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0;}function RT(e){if(!Array.isArray(e)||e.length<1)return !1;try{e.forEach(e=>{if(!e.urls)throw Error();});}catch(e){return !1;}return !0;}function CT(e){return Xg(e.turnServerURL,"turnServerURL"),Xg(e.username,"username"),Xg(e.password,"password"),e.udpport&&zg(e.udpport,"udpport",1,99999,!0),e.forceturn&&Yg(e.forceturn,"forceturn"),e.security&&Yg(e.security,"security"),e.tcpport&&zg(e.tcpport,"tcpport",1,99999,!0),!0;}function IT(e){return void 0!==e.level&&qg(e.level,"level",[1,2,3]),void 0!==e.delay&&zg(e.delay,"delay",0,3e3,!0),!0;}function vT(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?cg.reject(new Kg(Hg.UNEXPECTED_ERROR,"can not emit promise")):new cg((i,r)=>{e.emit(t,...n,i,r);});}function yT(e,t){if(0===e.getListeners(t).length)return cg.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return vT(e,t,...n);}function AT(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return bT(e,t,...n);}function bT(e,t){let i=null,n=null;for(var r=arguments.length,s=new Array(r>2?r-2:0),o=2;o<r;o++)s[o-2]=arguments[o];if(e.emit(t,...s,e=>{i=e;},e=>{n=e;}),null!==n)throw n;if(null===i)throw new Kg(Hg.UNEXPECTED_ERROR,"handler is not sync");return i;}!function(e){e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.DATACHANNEL_FAILBACK="Client._datachannelFailback",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload";}(hT||(hT={})),function(e){e.TRACER="tracer";}(pT||(pT={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY";}(_T||(_T={})),function(e){e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.FALLBACK="FALLBACK",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE";}(ET||(ET={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.INJECT_STREAM_STATUS="stream-inject-status",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change";}(mT||(mT={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK";}(fT||(fT={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE";}(gT||(gT={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE";}(TT||(TT={}));const wT=new class extends dT{set networkState(e){this.emit(TT.NETWORK_STATE_CHANGE,e,this._networkState),e===gT.ONLINE?this.emit(TT.ONLINE):e===gT.OFFLINE&&(this.onlineWaiter=new cg(e=>{this.once(TT.ONLINE,()=>{this.onlineWaiter=void 0,e(gT.ONLINE);});}),this.emit(TT.OFFLINE)),this._networkState=e;}get networkState(){return this._networkState;}get isOnline(){return this._networkState===gT.ONLINE;}constructor(){super(),sh(this,"_moduleName","network-indicator"),sh(this,"_networkState",gT.ONLINE),sh(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=gT.ONLINE;}),window.addEventListener("offline",()=>{this.networkState=gT.OFFLINE;});}}();var OT=De,NT=Je,DT=K,PT=Bi,LT=TypeError,kT=function(e){return function(t,i,n,r){OT(i);var s=NT(t),o=DT(s),a=PT(s),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in o){r=o[c],c+=d;break;}if(c+=d,e?c<0:a<=c)throw LT("Reduce of empty array with no initial value");}for(;e?c>=0:a>c;c+=d)c in o&&(r=i(r,o[c],c,s));return r;};},MT={left:kT(!1),right:kT(!0)}.left;wi({target:"Array",proto:!0,forced:!b_&&Ee>79&&Ee<83||!Ih("reduce")},{reduce:function(e){var t=arguments.length;return MT(this,e,t,t>1?arguments[1]:void 0);}});var UT=zi("Array").reduce,xT=l,VT=UT,FT=Array.prototype,BT=i(function(e){var t=e.reduce;return e===FT||xT(FT,e)&&t===FT.reduce?VT:t;});function jT(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function GT(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?jT(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):jT(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function WT(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1);}function HT(e){const t=[];return e.forEach(e=>{-1===t.indexOf(e)&&t.push(e);}),t;}function KT(e){void 0!==cg?cg.resolve().then(e):setTimeout(e,0);}function YT(e){return JSON.parse(JSON.stringify(e));}function qT(e){try{return YT(e);}catch(t){return e;}}const zT={};function JT(e,t){zT[t]||(zT[t]=!0,e());}function XT(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i;}function QT(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t);}function ZT(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=BT(t).call(t,(e,t)=>e+t.length,0),r=new Uint8Array(new ArrayBuffer(n));let s=0;return t.forEach(e=>{r.set(e,s),s+=e.length;}),r;}function $T(e){return window.TextEncoder?new TextEncoder().encode(e).length:e.length;}function eS(e){let t=0;return /DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData),e.forEach(e=>{t+="string"==typeof e?$T(e):e.size;}),t+138;}function tS(e){const t=new Kg(Hg.TIMEOUT,"timeout");return new cg((i,n)=>{window.setTimeout(()=>n(t),e);});}function iS(e){return new cg(t=>{window.setTimeout(t,e);});}function nS(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+nS(e-i.length,"");}function rS(){return nS(32,"").toUpperCase();}const sS=()=>{};const oS=new class{constructor(){sh(this,"fnMap",new Map());}throttleByKey(e,t,i,n){for(var r=arguments.length,s=new Array(r>4?r-4:0),o=4;o<r;o++)s[o-4]=arguments[o];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const o=window.setTimeout(()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t);},i);this.fnMap.set(t,{fn:e,threshold:i,timer:o,args:s,skipFn:n});}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,GT(GT({},r),{},{fn:e,args:s,skipFn:n}));}else {const r=window.setTimeout(()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t);},i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:s,skipFn:n});}}}(),aS=oS.throttleByKey.bind(oS);function cS(e){return "object"==typeof e&&null!==e&&!(e instanceof RegExp);}function dS(e,t){if(!cS(e)||!cS(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n<t.length;n++)i[n]=dS(e[n],t[n]);return i;}{const i=GT({},e);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)?i[n]=dS(e[n],t[n]):i[n]=t[n]);return i;}}function lS(e,t){let i=[0];if(t&&(i=new Array(t).fill(0)),0===e)return i;let n=0;for(;e>0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i;}let uS=1,hS=console;class pS{static setLogger(e){hS=e;}constructor(e){sh(this,"lockingPromise",cg.resolve()),sh(this,"locks",0),sh(this,"name",""),sh(this,"lockId",void 0),this.lockId=uS++,e&&(this.name=e),hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."));}get isLocked(){return this.locks>0;}lock(e){let t;this.locks+=1,hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new cg(i=>{t=()=>{this.locks-=1,hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i();};}),n=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>i),n;}}function _S(e,t){return function(i,n,r){const s=r.value;if("function"!=typeof s)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return await s.apply(this,a);}finally{r();}},r;};}const ES={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function mS(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i);}function fS(e,t,i,n){const r=Object.assign({},ES,n);let s=r.timeout;const o=async()=>{await function(e){return new cg(t=>{window.setTimeout(t,e);});}(s),s*=r.timeoutFactor,s=Math.min(r.maxRetryTimeout,s);};let a=!1;const c=new cg(async(n,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return s(new Kg(Hg.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await o();}catch(e){if(!i(e,c))return s(e);if(c+1===r.maxRetryCount)return s(e);await o();}}});return c.cancel=()=>a=!0,c;}let gS=class{constructor(e){sh(this,"input",[]),sh(this,"size",void 0),this.size=e;}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1);}mean(){var e;return 0===this.input.length?0:BT(e=this.input).call(e,(e,t)=>e+t)/this.input.length;}};function TS(e,t){return function(){return e.apply(t,arguments);};}const{toString:SS}=Object.prototype,{getPrototypeOf:RS}=Object,CS=(IS=Object.create(null),e=>{const t=SS.call(e);return IS[t]||(IS[t]=t.slice(8,-1).toLowerCase());});var IS;const vS=e=>(e=e.toLowerCase(),t=>CS(t)===e),yS=e=>t=>typeof t===e,{isArray:AS}=Array,bS=yS("undefined");const wS=vS("ArrayBuffer");const OS=yS("string"),NS=yS("function"),DS=yS("number"),PS=e=>null!==e&&"object"==typeof e,LS=e=>{if("object"!==CS(e))return !1;const t=RS(e);return !(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e);},kS=vS("Date"),MS=vS("File"),US=vS("Blob"),xS=vS("FileList"),VS=vS("URLSearchParams");function FS(e,t,{allOwnKeys:i=!1}={}){if(null==e)return;let n,r;if("object"!=typeof e&&(e=[e]),AS(e))for(n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else {const r=i?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let o;for(n=0;n<s;n++)o=r[n],t.call(null,e[o],o,e);}}function BS(e,t){t=t.toLowerCase();const i=Object.keys(e);let n,r=i.length;for(;r-->0;)if(n=i[r],t===n.toLowerCase())return n;return null;}const jS="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:commonjsGlobal,GS=e=>!bS(e)&&e!==jS;const WS=(HS="undefined"!=typeof Uint8Array&&RS(Uint8Array),e=>HS&&e instanceof HS);var HS;const KS=vS("HTMLFormElement"),YS=(({hasOwnProperty:e})=>(t,i)=>e.call(t,i))(Object.prototype),qS=vS("RegExp"),zS=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};FS(i,(i,r)=>{let s;!1!==(s=t(i,r,e))&&(n[r]=s||i);}),Object.defineProperties(e,n);},JS="abcdefghijklmnopqrstuvwxyz",XS="0123456789",QS={DIGIT:XS,ALPHA:JS,ALPHA_DIGIT:JS+JS.toUpperCase()+XS};const ZS=vS("AsyncFunction");var $S={isArray:AS,isArrayBuffer:wS,isBuffer:function(e){return null!==e&&!bS(e)&&null!==e.constructor&&!bS(e.constructor)&&NS(e.constructor.isBuffer)&&e.constructor.isBuffer(e);},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||NS(e.append)&&("formdata"===(t=CS(e))||"object"===t&&NS(e.toString)&&"[object FormData]"===e.toString()));},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&wS(e.buffer),t;},isString:OS,isNumber:DS,isBoolean:e=>!0===e||!1===e,isObject:PS,isPlainObject:LS,isUndefined:bS,isDate:kS,isFile:MS,isBlob:US,isRegExp:qS,isFunction:NS,isStream:e=>PS(e)&&NS(e.pipe),isURLSearchParams:VS,isTypedArray:WS,isFileList:xS,forEach:FS,merge:function e(){const{caseless:t}=GS(this)&&this||{},i={},n=(n,r)=>{const s=t&&BS(i,r)||r;LS(i[s])&&LS(n)?i[s]=e(i[s],n):LS(n)?i[s]=e({},n):AS(n)?i[s]=n.slice():i[s]=n;};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&FS(arguments[e],n);return i;},extend:(e,t,i,{allOwnKeys:n}={})=>(FS(t,(t,n)=>{i&&NS(t)?e[n]=TS(t,i):e[n]=t;},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),i&&Object.assign(e.prototype,i);},toFlatObject:(e,t,i,n)=>{let r,s,o;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-->0;)o=r[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==i&&RS(e);}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t;},kindOf:CS,kindOfTest:vS,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return -1!==n&&n===i;},toArray:e=>{if(!e)return null;if(AS(e))return e;let t=e.length;if(!DS(t))return null;const i=new Array(t);for(;t-->0;)i[t]=e[t];return i;},forEachEntry:(e,t)=>{const i=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1]);}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n;},isHTMLForm:KS,hasOwnProperty:YS,hasOwnProp:YS,reduceDescriptors:zS,freezeMethods:e=>{zS(e,(t,i)=>{if(NS(e)&&-1!==["arguments","caller","callee"].indexOf(i))return !1;const n=e[i];NS(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'");}));});},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach(e=>{i[e]=!0;});};return AS(e)?n(e):n(String(e).split(t)),i;},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,i){return t.toUpperCase()+i;}),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:BS,global:jS,isContextDefined:GS,ALPHABET:QS,generateString:(e=16,t=QS.ALPHA_DIGIT)=>{let i="";const{length:n}=t;for(;e--;)i+=t[Math.random()*n|0];return i;},isSpecCompliantForm:function(e){return !!(e&&NS(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator]);},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(PS(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const r=AS(e)?[]:{};return FS(e,(e,t)=>{const s=i(e,n+1);!bS(s)&&(r[t]=s);}),t[n]=void 0,r;}}return e;};return i(e,0);},isAsyncFn:ZS,isThenable:e=>e&&(PS(e)||NS(e))&&NS(e.then)&&NS(e.catch)};function eR(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r);}$S.inherits(eR,Error,{toJSON:function(){return {message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$S.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null};}});const tR=eR.prototype,iR={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{iR[e]={value:e};}),Object.defineProperties(eR,iR),Object.defineProperty(tR,"isAxiosError",{value:!0}),eR.from=(e,t,i,n,r,s)=>{const o=Object.create(tR);return $S.toFlatObject(e,o,function(e){return e!==Error.prototype;},e=>"isAxiosError"!==e),eR.call(o,e.message,t,i,n,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o;};function nR(e){return $S.isPlainObject(e)||$S.isArray(e);}function rR(e){return $S.endsWith(e,"[]")?e.slice(0,-2):e;}function sR(e,t,i){return e?e.concat(t).map(function(e,t){return e=rR(e),!i&&t?"["+e+"]":e;}).join(i?".":""):t;}const oR=$S.toFlatObject($S,{},null,function(e){return /^is[A-Z]/.test(e);});function aR(e,t,i){if(!$S.isObject(e))throw new TypeError("target must be an object");t=t||new FormData();const n=(i=$S.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return !$S.isUndefined(t[e]);})).metaTokens,r=i.visitor||d,s=i.dots,o=i.indexes,a=(i.Blob||"undefined"!=typeof Blob&&Blob)&&$S.isSpecCompliantForm(t);if(!$S.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return "";if($S.isDate(e))return e.toISOString();if(!a&&$S.isBlob(e))throw new eR("Blob is not supported. Use a Buffer instead.");return $S.isArrayBuffer(e)||$S.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e;}function d(e,i,r){let a=e;if(e&&!r&&"object"==typeof e)if($S.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if($S.isArray(e)&&function(e){return $S.isArray(e)&&!e.some(nR);}(e)||($S.isFileList(e)||$S.endsWith(i,"[]"))&&(a=$S.toArray(e)))return i=rR(i),a.forEach(function(e,n){!$S.isUndefined(e)&&null!==e&&t.append(!0===o?sR([i],n,s):null===o?i:i+"[]",c(e));}),!1;return !!nR(e)||(t.append(sR(r,i,s),c(e)),!1);}const l=[],u=Object.assign(oR,{defaultVisitor:d,convertValue:c,isVisitable:nR});if(!$S.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!$S.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),$S.forEach(i,function(i,s){!0===(!($S.isUndefined(i)||null===i)&&r.call(t,i,$S.isString(s)?s.trim():s,n,u))&&e(i,n?n.concat(s):[s]);}),l.pop();}}(e),t;}function cR(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e];});}function dR(e,t){this._pairs=[],e&&aR(e,this,t);}const lR=dR.prototype;function uR(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]");}function hR(e,t,i){if(!t)return e;const n=i&&i.encode||uR,r=i&&i.serialize;let s;if(s=r?r(t,i):$S.isURLSearchParams(t)?t.toString():new dR(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s;}return e;}lR.append=function(e,t){this._pairs.push([e,t]);},lR.toString=function(e){const t=e?function(t){return e.call(this,t,cR);}:cR;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1]);},"").join("&");};var pR=class{constructor(){this.handlers=[];}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1;}eject(e){this.handlers[e]&&(this.handlers[e]=null);}clear(){this.handlers&&(this.handlers=[]);}forEach(e){$S.forEach(this.handlers,function(t){null!==t&&e(t);});}},_R={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ER={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:dR,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const mR="undefined"!=typeof window&&"undefined"!=typeof document,fR=(gR="undefined"!=typeof navigator&&navigator.product,mR&&["ReactNative","NativeScript","NS"].indexOf(gR)<0);var gR;const TR="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var SR={...Object.freeze({__proto__:null,hasBrowserEnv:mR,hasStandardBrowserEnv:fR,hasStandardBrowserWebWorkerEnv:TR}),...ER};function RR(e){function t(e,i,n,r){let s=e[r++];if("__proto__"===s)return !0;const o=Number.isFinite(+s),a=r>=e.length;if(s=!s&&$S.isArray(n)?n.length:s,a)return $S.hasOwnProp(n,s)?n[s]=[n[s],i]:n[s]=i,!o;n[s]&&$S.isObject(n[s])||(n[s]=[]);return t(e,i,n[s],r)&&$S.isArray(n[s])&&(n[s]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let s;for(n=0;n<r;n++)s=i[n],t[s]=e[s];return t;}(n[s])),!o;}if($S.isFormData(e)&&$S.isFunction(e.entries)){const i={};return $S.forEachEntry(e,(e,n)=>{t(function(e){return $S.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0]);}(e),n,i,0);}),i;}return null;}const CR={transitional:_R,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=$S.isObject(e);r&&$S.isHTMLForm(e)&&(e=new FormData(e));if($S.isFormData(e))return n?JSON.stringify(RR(e)):e;if($S.isArrayBuffer(e)||$S.isBuffer(e)||$S.isStream(e)||$S.isFile(e)||$S.isBlob(e))return e;if($S.isArrayBufferView(e))return e.buffer;if($S.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return aR(e,new SR.classes.URLSearchParams(),Object.assign({visitor:function(e,t,i,n){return SR.isNode&&$S.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments);}},t));}(e,this.formSerializer).toString();if((s=$S.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return aR(s?{"files[]":e}:e,t&&new t(),this.formSerializer);}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if($S.isString(e))try{return (t||JSON.parse)(e),$S.trim(e);}catch(e){if("SyntaxError"!==e.name)throw e;}return (i||JSON.stringify)(e);}(e)):e;}],transformResponse:[function(e){const t=this.transitional||CR.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&$S.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e);}catch(e){if(i){if("SyntaxError"===e.name)throw eR.from(e,eR.ERR_BAD_RESPONSE,this,null,this.response);throw e;}}}return e;}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:SR.classes.FormData,Blob:SR.classes.Blob},validateStatus:function(e){return e>=200&&e<300;},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$S.forEach(["delete","get","head","post","put","patch"],e=>{CR.headers[e]={};});var IR=CR;const vR=$S.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const yR=Symbol("internals");function AR(e){return e&&String(e).trim().toLowerCase();}function bR(e){return !1===e||null==e?e:$S.isArray(e)?e.map(bR):String(e);}function wR(e,t,i,n,r){return $S.isFunction(n)?n.call(this,t,i):(r&&(t=i),$S.isString(t)?$S.isString(n)?-1!==t.indexOf(n):$S.isRegExp(n)?n.test(t):void 0:void 0);}class OR{constructor(e){e&&this.set(e);}set(e,t,i){const n=this;function r(e,t,i){const r=AR(t);if(!r)throw new Error("header name must be a non-empty string");const s=$S.findKey(n,r);(!s||void 0===n[s]||!0===i||void 0===i&&!1!==n[s])&&(n[s||t]=bR(e));}const s=(e,t)=>$S.forEach(e,(e,i)=>r(e,i,t));return $S.isPlainObject(e)||e instanceof this.constructor?s(e,t):$S.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let i,n,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),i=e.substring(0,r).trim().toLowerCase(),n=e.substring(r+1).trim(),!i||t[i]&&vR[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n);}),t;})(e),t):null!=e&&r(t,e,i),this;}get(e,t){if(e=AR(e)){const i=$S.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t;}(e);if($S.isFunction(t))return t.call(this,e,i);if($S.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function");}}}has(e,t){if(e=AR(e)){const i=$S.findKey(this,e);return !(!i||void 0===this[i]||t&&!wR(0,this[i],i,t));}return !1;}delete(e,t){const i=this;let n=!1;function r(e){if(e=AR(e)){const r=$S.findKey(i,e);!r||t&&!wR(0,i[r],r,t)||(delete i[r],n=!0);}}return $S.isArray(e)?e.forEach(r):r(e),n;}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!wR(0,this[r],r,e,!0)||(delete this[r],n=!0);}return n;}normalize(e){const t=this,i={};return $S.forEach(this,(n,r)=>{const s=$S.findKey(i,r);if(s)return t[s]=bR(n),void delete t[r];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i);}(r):String(r).trim();o!==r&&delete t[r],t[o]=bR(n),i[o]=!0;}),this;}concat(...e){return this.constructor.concat(this,...e);}toJSON(e){const t=Object.create(null);return $S.forEach(this,(i,n)=>{null!=i&&!1!==i&&(t[n]=e&&$S.isArray(i)?i.join(", "):i);}),t;}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]();}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n");}get[Symbol.toStringTag](){return "AxiosHeaders";}static from(e){return e instanceof this?e:new this(e);}static concat(e,...t){const i=new this(e);return t.forEach(e=>i.set(e)),i;}static accessor(e){const t=(this[yR]=this[yR]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=AR(e);t[n]||(!function(e,t){const i=$S.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+i,{value:function(e,i,r){return this[n].call(this,t,e,i,r);},configurable:!0});});}(i,e),t[n]=!0);}return $S.isArray(e)?e.forEach(n):n(e),this;}}OR.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$S.reduceDescriptors(OR.prototype,({value:e},t)=>{let i=t[0].toUpperCase()+t.slice(1);return {get:()=>e,set(e){this[i]=e;}};}),$S.freezeMethods(OR);var NR=OR;function DR(e,t){const i=this||IR,n=t||i,r=NR.from(n.headers);let s=n.data;return $S.forEach(e,function(e){s=e.call(i,s,r.normalize(),t?t.status:void 0);}),r.normalize(),s;}function PR(e){return !(!e||!e.__CANCEL__);}function LR(e,t,i){eR.call(this,null==e?"canceled":e,eR.ERR_CANCELED,t,i),this.name="CanceledError";}$S.inherits(LR,eR,{__CANCEL__:!0});var kR=SR.hasStandardBrowserEnv?{write(e,t,i,n,r,s){const o=[e+"="+encodeURIComponent(t)];$S.isNumber(i)&&o.push("expires="+new Date(i).toGMTString()),$S.isString(n)&&o.push("path="+n),$S.isString(r)&&o.push("domain="+r),!0===s&&o.push("secure"),document.cookie=o.join("; ");},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null;},remove(e){this.write(e,"",Date.now()-864e5);}}:{write(){},read:()=>null,remove(){}};function MR(e,t){return e&&!function(e){return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(e);}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e;}(e,t):t;}var UR=SR.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function n(i){let n=i;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname};}return i=n(window.location.href),function(e){const t=$S.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host;};}():function(){return !0;};function xR(e,t){let i=0;const n=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];r||(r=c),i[s]=a,n[s]=c;let l=o,u=0;for(;l!==s;)u+=i[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0;};}(50,250);return r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-i,c=n(a);i=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r};d[t?"download":"upload"]=!0,e(d);};}var VR="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,i){let n=e.data;const r=NR.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s);}if($S.isFormData(n))if(SR.hasStandardBrowserEnv||SR.hasStandardBrowserWebWorkerEnv)r.setContentType(!1);else if(!1!==(o=r.getContentType())){const[e,...t]=o?o.split(";").map(e=>e.trim()).filter(Boolean):[];r.setContentType([e||"multipart/form-data",...t].join("; "));}let l=new XMLHttpRequest();if(e.auth){const t=e.auth.username||"",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";r.set("Authorization","Basic "+btoa(t+":"+i));}const u=MR(e.baseURL,e.url);function h(){if(!l)return;const n=NR.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new eR("Request failed with status code "+i.status,[eR.ERR_BAD_REQUEST,eR.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i);}(function(e){t(e),d();},function(e){i(e),d();},{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null;}if(l.open(e.method.toUpperCase(),hR(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=h:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(h);},l.onabort=function(){l&&(i(new eR("Request aborted",eR.ECONNABORTED,e,l)),l=null);},l.onerror=function(){i(new eR("Network Error",eR.ERR_NETWORK,e,l)),l=null;},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||_R;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new eR(t,n.clarifyTimeoutError?eR.ETIMEDOUT:eR.ECONNABORTED,e,l)),l=null;},SR.hasStandardBrowserEnv&&(c&&$S.isFunction(c)&&(c=c(e)),c||!1!==c&&UR(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&kR.read(e.xsrfCookieName);t&&r.set(e.xsrfHeaderName,t);}void 0===n&&r.setContentType(null),"setRequestHeader"in l&&$S.forEach(r.toJSON(),function(e,t){l.setRequestHeader(t,e);}),$S.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",xR(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",xR(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(i(!t||t.type?new LR(null,e,l):t),l.abort(),l=null);},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const p=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||"";}(u);p&&-1===SR.protocols.indexOf(p)?i(new eR("Unsupported protocol "+p+":",eR.ERR_BAD_REQUEST,e)):l.send(n||null);});};const FR={http:null,xhr:VR};$S.forEach(FR,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t});}catch(e){}Object.defineProperty(e,"adapterName",{value:t});}});const BR=e=>`- ${e}`,jR=e=>$S.isFunction(e)||null===e||!1===e;var GR={getAdapter:e=>{e=$S.isArray(e)?e:[e];const{length:t}=e;let i,n;const r={};for(let s=0;s<t;s++){let t;if(i=e[s],n=i,!jR(i)&&(n=FR[(t=String(i)).toLowerCase()],void 0===n))throw new eR(`Unknown adapter '${t}'`);if(n)break;r[t||"#"+s]=n;}if(!n){const e=Object.entries(r).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new eR("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(BR).join("\n"):" "+BR(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT");}return n;},adapters:FR};function WR(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new LR(null,e);}function HR(e){WR(e),e.headers=NR.from(e.headers),e.data=DR.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return GR.getAdapter(e.adapter||IR.adapter)(e).then(function(t){return WR(e),t.data=DR.call(e,e.transformResponse,t),t.headers=NR.from(t.headers),t;},function(t){return PR(t)||(WR(e),t&&t.response&&(t.response.data=DR.call(e,e.transformResponse,t.response),t.response.headers=NR.from(t.response.headers))),Promise.reject(t);});}const KR=e=>e instanceof NR?e.toJSON():e;function YR(e,t){t=t||{};const i={};function n(e,t,i){return $S.isPlainObject(e)&&$S.isPlainObject(t)?$S.merge.call({caseless:i},e,t):$S.isPlainObject(t)?$S.merge({},t):$S.isArray(t)?t.slice():t;}function r(e,t,i){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e,i):n(e,t,i);}function s(e,t){if(!$S.isUndefined(t))return n(void 0,t);}function o(e,t){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e):n(void 0,t);}function a(i,r,s){return s in t?n(i,r):s in e?n(void 0,i):void 0;}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>r(KR(e),KR(t),!0)};return $S.forEach(Object.keys(Object.assign({},e,t)),function(n){const s=c[n]||r,o=s(e[n],t[n],n);$S.isUndefined(o)&&s!==a||(i[n]=o);}),i;}const qR="1.6.7",zR={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{zR[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e;};});const JR={};zR.transitional=function(e,t,i){function n(e,t){return "[Axios v"+qR+"] Transitional option '"+e+"'"+t+(i?". "+i:"");}return (i,r,s)=>{if(!1===e)throw new eR(n(r," has been removed"+(t?" in "+t:"")),eR.ERR_DEPRECATED);return t&&!JR[r]&&(JR[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s);};};var XR={assertOptions:function(e,t,i){if("object"!=typeof e)throw new eR("options must be an object",eR.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-->0;){const s=n[r],o=t[s];if(o){const t=e[s],i=void 0===t||o(t,s,e);if(!0!==i)throw new eR("option "+s+" must be "+i,eR.ERR_BAD_OPTION_VALUE);}else if(!0!==i)throw new eR("Unknown option "+s,eR.ERR_BAD_OPTION);}},validators:zR};const QR=XR.validators;let ZR=class{constructor(e){this.defaults=e,this.interceptors={request:new pR(),response:new pR()};}async request(e,t){try{return await this._request(e,t);}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error();const i=t.stack?t.stack.replace(/^.+\n/,""):"";e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i;}throw e;}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=YR(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&XR.assertOptions(i,{silentJSONParsing:QR.transitional(QR.boolean),forcedJSONParsing:QR.transitional(QR.boolean),clarifyTimeoutError:QR.transitional(QR.boolean)},!1),null!=n&&($S.isFunction(n)?t.paramsSerializer={serialize:n}:XR.assertOptions(n,{encode:QR.function,serialize:QR.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&$S.merge(r.common,r[t.method]);r&&$S.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e];}),t.headers=NR.concat(s,r);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected));});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected);});let l,u=0;if(!a){const e=[HR.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d;}l=o.length;let h=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{h=e(h);}catch(e){t.call(this,e);break;}}try{d=HR.call(this,h);}catch(e){return Promise.reject(e);}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d;}getUri(e){return hR(MR((e=YR(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer);}};$S.forEach(["delete","get","head","options"],function(e){ZR.prototype[e]=function(t,i){return this.request(YR(i||{},{method:e,url:t,data:(i||{}).data}));};}),$S.forEach(["post","put","patch"],function(e){function t(t){return function(i,n,r){return this.request(YR(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}));};}ZR.prototype[e]=t(),ZR.prototype[e+"Form"]=t(!0);});var $R=ZR;class eC{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e;});const i=this;this.promise.then(e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-->0;)i._listeners[t](e);i._listeners=null;}),this.promise.then=e=>{let t;const n=new Promise(e=>{i.subscribe(e),t=e;}).then(e);return n.cancel=function(){i.unsubscribe(t);},n;},e(function(e,n,r){i.reason||(i.reason=new LR(e,n,r),t(i.reason));});}throwIfRequested(){if(this.reason)throw this.reason;}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e];}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1);}static source(){let e;return {token:new eC(function(t){e=t;}),cancel:e};}}var tC=eC;const iC={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(iC).forEach(([e,t])=>{iC[t]=e;});var nC=iC;const rC=function e(t){const i=new $R(t),n=TS($R.prototype.request,i);return $S.extend(n,$R.prototype,i,{allOwnKeys:!0}),$S.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(YR(t,i));},n;}(IR);rC.Axios=$R,rC.CanceledError=LR,rC.CancelToken=tC,rC.isCancel=PR,rC.VERSION=qR,rC.toFormData=aR,rC.AxiosError=eR,rC.Cancel=rC.CanceledError,rC.all=function(e){return Promise.all(e);},rC.spread=function(e){return function(t){return e.apply(null,t);};},rC.isAxiosError=function(e){return $S.isObject(e)&&!0===e.isAxiosError;},rC.mergeConfig=YR,rC.AxiosHeaders=NR,rC.formToJSON=e=>RR($S.isHTMLForm(e)?new FormData(e):e),rC.getAdapter=GR.getAdapter,rC.HttpStatusCode=nC,rC.default=rC;var sC=rC;function oC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function aC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?oC(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):oC(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}let cC,dC=0,lC=0;function uC(e,t,i,n){return new cg((r,s)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),dC+=$T(t.data)):i&&(t.data.size?dC+=t.data.size:t.data instanceof FormData?dC+=eS(t.data):dC+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,sC.request(t).then(e=>{"string"==typeof e.data?lC+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?lC+=e.data.byteLength:lC+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data);}).catch(e=>{sC.isCancel(e)?s(new Kg(Hg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Kg(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new Kg(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Kg(Hg.NETWORK_ERROR,e.message));});});}async function hC(e,t){const i=new Blob([t.data],{type:"buffer"});return await uC(e,aC(aC({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0);}const pC=()=>"HTTPS"===(cC||cC||(cC=(window.location.protocol.split(":")[0]||"").toUpperCase(),cC)),_C=()=>void 0!==window.isSecureContext;const EC=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return "".concat(e,".").concat(i);}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return "".concat(e,".").concat(100*(Number(t)+1));}return "4.0.0.999";}("4.20.2"),mC=function(){try{return !0===JSON.parse("true");}catch(e){return !0;}}();var fC;!function(e){e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn";}(fC||(fC={}));const gC="v4.20.2-0-g8ae7fdad(3/20/2024, 4:48:46 PM)",TC={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:100,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],PLUGIN_INFO:[]};function SC(e,t,i){var n,r;bn(n=Object.keys(TC)).call(n,e)&&(!i&&bn(r=Object.keys(CC)).call(r,e)||(TC[e]=t,"ENABLE_VIDEO_SEI"===e&&!0===t&&(TC.ENABLE_ENCODED_TRANSFORM=!0)));}function RC(e){return TC[e];}const CC={};function IC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function vC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?IC(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):IC(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}var yC;!function(e){e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_DATACHANNEL="SET_USE_DATACHANNEL",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE";}(yC||(yC={}));class AC{constructor(e,t,i,n){sh(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useDataChannel:!1,useP2P:!1,p2pTransport:fC.Default};}dispatch(e){this.state=function(e,t){switch(t.type){case yC.SET_SESSION_ID:return vC(vC({},e),{},{sessionId:t.sessionId});case yC.SET_P2P_ID:return vC(vC({},e),{},{p2pId:t.p2pId});case yC.SET_UID:return vC(vC({},e),{},{uid:t.uid});case yC.SET_INT_UID:return vC(vC({},e),{},{intUid:t.intUid});case yC.SET_PUB_ID:return vC(vC({},e),{},{pubId:t.pubId});case yC.KEY_METRIC_CLIENT_CREATED:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{clientCreated:t.metric})});case yC.KEY_METRIC_JOIN_START:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{joinStart:t.metric})});case yC.AVOID_JOIN_START:return vC(vC({},e),{},{avoidJoinStart:t.avoidJoinStart});case yC.KEY_METRIC_JOIN_END:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{joinEnd:t.metric})});case yC.KEY_METRIC_REQUEST_AP_START:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{requestAPStart:t.metric})});case yC.KEY_METRIC_REQUEST_AP_END:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{requestAPEnd:t.metric})});case yC.KEY_METRIC_JOIN_GATEWAY_START:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case yC.KEY_METRIC_JOIN_GATEWAY_END:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case yC.KEY_METRIC_PEER_CONNECTION_START:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case yC.KEY_METRIC_PEER_CONNECTION_END:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case yC.KEY_METRIC_DESCRIPTION_START:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{descriptionStart:t.metric})});case yC.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case yC.KEY_METRIC_ICE_CONNECTION_END:return vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case yC.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex(e=>e.trackId===t.metric.trackId);return -1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})});}case yC.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex(e=>e.userId===t.metric.userId&&e.type===t.metric.type);return -1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})});}case yC.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case yC.RECORD_JOIN_CHANNEL_SERVICE:return "number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=vC(vC({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case yC.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case yC.SET_USE_DATACHANNEL:return vC(vC({},e),{},{useDataChannel:t.val});case yC.SET_USE_P2P:return vC(vC({},e),{},{useP2P:t.val});case yC.SET_TRANSPORT_TYPE:return vC(vC({},e),{},{p2pTransport:t.val});default:return e;}}(this.state,e);}set sessionId(e){this.dispatch({type:yC.SET_SESSION_ID,sessionId:e});}get sessionId(){return this.state.sessionId;}set codec(e){this.state.codec=e;}get codec(){return this.state.codec;}get mode(){return this.state.mode;}get audioCodec(){return this.state.audioCodec;}get clientId(){return this.state.clientId;}set p2pId(e){this.dispatch({type:yC.SET_P2P_ID,p2pId:e});}get p2pId(){return this.state.p2pId;}set dcId(e){this.dispatch({type:yC.SET_DC_ID,dcId:e});}get dcId(){return this.state.dcId;}set uid(e){this.dispatch({type:yC.SET_UID,uid:e});}get uid(){return this.state.uid;}set intUid(e){this.dispatch({type:yC.SET_INT_UID,intUid:e});}get intUid(){return this.state.intUid;}set pubId(e){this.dispatch({type:yC.SET_PUB_ID,pubId:e});}get pubId(){return this.state.pubId;}set cloudProxyServerMode(e){this.dispatch({type:yC.SET_CLOUD_PROXY_SERVER_MODE,mode:e});}get cloudProxyServerMode(){return this.state.cloudProxyServerMode;}set useDataChannel(e){this.dispatch({type:yC.SET_USE_DATACHANNEL,val:e});}get useDataChannel(){return this.state.useDataChannel;}set useP2P(e){this.dispatch({type:yC.SET_USE_P2P,val:e});}get useP2P(){return this.state.useP2P;}set p2pTransport(e){this.dispatch({type:yC.SET_TRANSPORT_TYPE,val:e});}get p2pTransport(){return this.state.p2pTransport;}clientCreated(){this.dispatch({type:yC.KEY_METRIC_CLIENT_CREATED,metric:Date.now()});}joinStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_START,metric:Date.now()});}joinEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_END,metric:Date.now()});}requestAPStart(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_START,metric:Date.now()});}requestAPEnd(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_END,metric:Date.now()});}joinGatewayStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()});}joinGatewayEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()});}peerConnectionStart(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()});}peerConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()});}descriptionStart(){this.dispatch({type:yC.KEY_METRIC_DESCRIPTION_START,metric:Date.now()});}signalChannelOpen(){this.dispatch({type:yC.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()});}iceConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()});}publish(e,t,i,n){this.dispatch({type:yC.KEY_METRIC_PUBLISH,metric:vC(vC({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})});}subscribe(e,t,i,n,r,s,o){this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC(vC(vC({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),s&&{streamAdded:s}),o&&{firstDecoded:o})});}massSubscribe(e,t,i,n){e.forEach(e=>{this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})});});}get keyMetrics(){return this.state.keyMetrics;}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map(e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return "number"!=typeof t?(this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:vC(vC({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t);}catch(e){return 0;}}resetJoinChannelServiceRecords(){this.dispatch({type:yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS});}resetKeyMetrics(){this.dispatch({type:yC.RESET_KEY_METRICS});}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords;}catch(e){return [];}}get avoidJoinStart(){return this.state.avoidJoinStart;}set avoidJoinStart(e){this.dispatch({type:yC.AVOID_JOIN_START,avoidJoinStart:e});}}var bC,wC;!function(e){e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1";}(bC||(bC={})),function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722";}(wC||(wC={}));const OC=128,NC=96,DC=1e3,PC=10;let LC=0;const kC=new class extends dT{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e);}}();class MC{constructor(e){sh(this,"logger",void 0),sh(this,"prefixLists",[]),this.logger=e;}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t);}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t);}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t);}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t);}prefix(e){return this.prefixLists.push(e),this;}popPrefix(){return this.prefixLists.pop(),this;}}function UC(){const e=new Date();return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds();}function xC(){const e=new Date(),t=/((\d+:){2}\d+)/.exec(new Date().toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds();}const VC={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},FC=Date.now(),BC=e=>{for(const t in VC)if(Object.prototype.hasOwnProperty.call(VC,t)&&VC[t]===e)return t;return "DEFAULT";};const jC=new class{constructor(){sh(this,"proxyServerURL",void 0),sh(this,"logLevel",VC.DEBUG),sh(this,"uploadState","collecting"),sh(this,"uploadLogWaitingList",[]),sh(this,"uploadLogUploadingList",[]),sh(this,"uploadErrorCount",0),sh(this,"currentLogID",0),sh(this,"url",void 0),sh(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t);});}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[VC.DEBUG].concat(t);this.log.apply(this,n);}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[VC.INFO].concat(t);this.log.apply(this,n);}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[VC.WARNING].concat(t);this.log.apply(this,n);}warn(){this.warning(...arguments);}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[VC.ERROR].concat(t);this.log.apply(this,n);}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[VC.DEBUG].concat(t);this.uploadLog.apply(this,n);}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e;}enableLogUpload(){SC("UPLOAD_LOG",!0);}disableLogUpload(){SC("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[];}setProxyServer(e){this.proxyServerURL=e;}prefix(e){return new MC(this).prefix(e);}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-FC<100)return void setTimeout(()=>{this.log(...t);},Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=UC()+" Agora-SDK [".concat(BC(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=UC()+" %cAgora-SDK [".concat(BC(n),"]:");let s=[];if(!RC("USE_NEW_LOG"))switch(n){case VC.DEBUG:s=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,s);break;case VC.INFO:s=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,s);break;case VC.WARNING:s=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,s);break;case VC.ERROR:s=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,s);}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-FC<100)return void setTimeout(()=>{this.uploadLog(...t);},Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));t[0]=UC()+" Agora-SDK [".concat(BC(n),"]:"),this.appendLogToWaitingList(n,...t);}appendLogToWaitingList(e){if(!RC("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=xC()+" Agora-SDK [".concat(BC(e),"]:"):i[0]=xC()+" Agora-SDK [".concat(BC(e),"]:");let r="";i.forEach(e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ");}),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval();}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval();}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:EC,process_id:RC("PROCESS_ID"),payload:JSON.stringify(e)};return fS(async()=>{const e=await sC.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(RC("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(RC("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t;}},()=>(this.uploadLogUploadingList=[],!1),e=>(e.response?kC.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?kC.reportLogUploadError({status:e.request.status,message:e.message}):kC.reportLogUploadError({status:-1,message:e.message}),!0),{timeout:RC("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:RC("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")});}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,RC("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_INTERVAL"));}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_RETRY_INTERVAL_V1"));}));}}();var GC,WC;function HC(e){return Xg(e.reportId,"params.reportId",0,100,!1),Xg(e.category,"params.category",0,100,!1),Xg(e.event,"params.event",0,100,!1),Xg(e.label,"params.label",0,100,!1),zg(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0;}!function(e){e.FREE="free",e.UPLOADING="uploading";}(GC||(GC={})),function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API";}(WC||(WC={}));const KC={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var YC,qC,zC,JC;function XC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function QC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?XC(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):XC(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities";}(YC||(YC={})),function(e){e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities";}(qC||(qC={})),function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT";}(zC||(zC={})),function(e){e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED";}(JC||(JC={}));class ZC{constructor(){sh(this,"baseInfoMap",new Map()),sh(this,"proxyServer",void 0),sh(this,"eventUploadTimer",void 0),sh(this,"setSessionIdTimer",void 0),sh(this,"url",void 0),sh(this,"backupUrl",void 0),sh(this,"_appId",void 0),sh(this,"keyEventUploadPendingItems",[]),sh(this,"normalEventUploadPendingItems",[]),sh(this,"apiInvokeUploadPendingItems",[]),sh(this,"apiInvokeCount",0),sh(this,"ltsList",[]),sh(this,"lastSendNormalEventTime",Date.now()),sh(this,"customReportCounterTimer",void 0),sh(this,"customReportCount",0),sh(this,"extApiInvoke",async e=>{for(const t of e){const e=QC(QC({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:pT.TRACER});this.sendApiInvoke(e);}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),RC("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),RC("EVENT_REPORT_SEND_INTERVAL"));}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e);}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void jC.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,jC.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"ms")),this.baseInfoMap.set(e,t);}setAppId(e){this._appId=e;}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,s=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),o=!!RC("SHOW_REPORT_INVOKER_LOG");o&&jC.info("".concat(t.name," start"),t.options);let a=!1;iS(t.timeout).then(()=>{a||(this.sendApiInvoke(QC(QC({},s()),{},{error:Hg.API_INVOKE_TIMEOUT,success:!1})),jC.debug("".concat(t.name," timeout")));});const c=new Kg(Hg.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return {onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!0},t.reportResult&&{result:e})),o&&jC.info("".concat(t.name," onSuccess")),e;};return i?aS(n,t.name+"Success",i,()=>a=!0):n();},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!1,error:e})),o&&jC.info("".concat(t.name," onFailure"),e.toString());};return i?aS(n,t.name+"Error",i,()=>a=!0):n();}};}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:RC("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:mC?"global":"oversea",areas:RC("AREAS")&&RC("AREAS").join(",")},t.extend),{stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=QC(QC({},n),{},{eventType:YC.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:gC,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:RC("PROCESS_ID"),appType:RC("APP_TYPE"),success:!0,version:EC,stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientType:20,clientRole:l,serviceId:RC("PROCESS_ID"),extensionID:RC("PLUGIN_INFO").join(",")||""});this.send({type:qC.SESSION,data:h},!0);}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:qC.JOIN_CHOOSE_SERVER,data:s},!0);}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:qC.REQ_USER_ACCOUNT,data:s},!0);}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:s,avoidJoinStartTime:o,isProxy:a,addr:c}=t,d=r-(s&&o?o:i.startTime),l=QC(QC({},n),{},{eventType:YC.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:s,signalChannel:t.signalChannel}),u=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)this.send({type:qC.JOIN_GATEWAY,data:l},!0);else {let e;if(c){if(a){const t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:a?1:0};}else {const t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(/:|p=/g)[1]:"",isProxy:a?1:0};}}else e={isSuccess:u,gatewayIp:"",port:"",isProxy:a?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:YC.REJOIN_GATEWAY});this.send({type:qC.RE_JOIN_GATEWAY,data:t},!0);}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=QC(QC({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:qC.JOIN_CHANNEL_TIMEOUT,data:r},!0);}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:qC.PUBLISH,data:s},!0);}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,s=Date.now(),o=QC(QC({},r),{},{eventType:YC.SUBSCRIBE,lts:s,eventElapse:t.eventElapse,elapse:s-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?o.peerSuid=t.peerid:o.peer=t.peerid,this.send({type:qC.SUBSCRIBE,data:o},!0);}wsCompressorInit(e){var t;const i=[...ph(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC({},s),{},{eventType:YC.WS_COMPRESSOR_INIT,lts:o,eventElapse:e.eventElapse,elapse:o-r.startTime,status:e.status?1:2});this.send({type:qC.WS_COMPRESSOR_INIT,data:a},!0);}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o,firstDecodeFrame:Math.max(o-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0);}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o});this.send({type:i,data:a},!0);}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:YC.PC_STATS,lts:r});this.send({type:qC.PC_STATS,data:s},!0);}updateRemoteRTPCapabilities(e,t){if(e){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:YC.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:qC.UPDATE_REMOTE_RTPCAPABILITIES,data:s},!0);}}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{eventType:t,lts:o});this.send({type:i,data:a},!0);}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:qC.STREAM_SWITCH,data:s},!0);}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_APPCENTER,data:s},!0);}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_WORKER_MANAGER,data:s},!0);}setProxyServer(e){this.proxyServer=e,e?jC.debug("reportProxyServerurl: ".concat(e)):jC.debug("disable reportProxyServerurl: ".concat(e));}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:qC.PEER_PUBLISH_STATUS,data:s},!0);}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return [e];e[t]="";const r=$T(JSON.stringify(e));let s=0;const o=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(o[o.length]=GT(GT({},e),{},{[t]:n.substring(s,c)}),s=c,a=n.charCodeAt(c)<=127?1:3);return s!==n.length-1&&(o[o.length]=GT(GT({},e),{},{[t]:n.substring(s)})),o;}(QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300);s.forEach(e=>this.send({type:qC.WORKER_EVENT,data:e},!0));}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.AP_WORKER_EVENT,data:s},!0);}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:qC.JOIN_WEB_PROXY_AP,data:s},!0);}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.WEBSOCKET_QUIT,data:s},!0);}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>RC("CUSTOM_REPORT_LIMIT"))throw new Kg(Hg.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0;},5e3));const i=Date.now(),n=t.map(t=>({type:qC.USER_ANALYTICS,data:QC(QC({sid:e},t),{},{lts:i})}));try{RC("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n);}catch(e){throw jC.error("send custom report message failed",e.toString()),new Kg(Hg.CUSTOM_REPORT_SEND_FAILED,e.message);}}sendApiInvoke(e){const t=RC("NOT_REPORT_EVENT");if(e.tag&&bn(t)&&bn(t).call(t,e.tag))return !1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:s}=i.info;let o;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Kg){const{code:t,message:i}=e.error;o=t||i||e.error.toString();}else o=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?o:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:qC.API_INVOKE,data:a},!1),!0;}appendSessionId(){ZC.__CLIENT_LIST__.forEach(e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;i<t;i++){const t=this.apiInvokeUploadPendingItems.shift();t&&(t.sid=e._sessionId,this.sendApiInvoke(Object.assign({},t)));}}});}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>RC("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1);}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1);}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t);}e.push(...n);for(const e of [...i]){var r;if(-1!==this.ltsList.indexOf(e.data.lts))e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts);else this.ltsList.push(e.data.lts),ep(r=this.ltsList).call(r,(e,t)=>e-t);}t||(this.lastSendNormalEventTime=Date.now());return RC("ENABLE_EVENT_REPORT")?(i.length&&(RC("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{RC("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>RC("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-RC("NORMAL_EVENT_QUEUE_CAPACITY")),jC.warning("report: drop normal events"))));})(i)),e):e;}async postDataToStatsCollector2(e){wT.networkState===gT.OFFLINE&&(await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]));const t=e=>{let t=new Uint8Array();return e.forEach(e=>{const i=sT(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(qC).forEach(i=>{let[n,r]=i;r===e.type&&(t=EventNameToID[n]);}),t;})(e),s=new DataView(n);s.setUint16(0,i.byteLength,!0),s.setUint8(2,255&r),s.setUint8(3,r>>>8&255),s.setUint8(4,r>>>16&255),t=oT(t,new Uint8Array(n)),t=oT(t,i);}),t;},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(RC("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(RC("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await uC(n,{timeout:1e4,data:t(e),headers:QC(QC({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0);}catch(e){if(1===r)throw e;continue;}return;}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(e=>JSON.stringify(e)),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0;})(e[0])};wT.networkState===gT.OFFLINE&&(await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]));const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("EVENT_REPORT_DOMAIN"),"&p=").concat(RC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(RC("EVENT_REPORT_DOMAIN"),":").concat(RC("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(RC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(RC("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(RC("STATS_COLLECTOR_PORT")).concat(n)));try{t?await hC(r,{timeout:1e4,data:i}):await uC(r,{timeout:1e4,data:i});}catch(t){if(1===e)throw t;continue;}return;}}createBaseInfo(e,t){const i=Object.assign({},KC);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i;}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:pT.TRACER}).onSuccess();}}function $C(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const s=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];let a=n;if(e.argsMap)try{a=e.argsMap(this,...n);}catch(e){jC.warning(e),a=[];}try{JSON.stringify(a);}catch(e){jC.warning("arguments for method ".concat(s,".").concat(String(i)," not serializable for apiInvoke.")),a=[];}const c=(e.report||eI).reportApiInvoke(this._sessionId||null,{name:"".concat(s,".").concat(String(i)),options:a,tag:pT.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,n);return t instanceof cg?t.then(t=>(c.onSuccess(e.reportResult&&t),t)).catch(e=>{throw c.onError(e),e;}):(c.onSuccess(e.reportResult&&t),t);}catch(e){throw c.onError(e),e;}};}return n;};}sh(ZC,"__CLIENT_LIST__",[]);const eI=new ZC();kC.on("REPORT_LOG_UPLOAD",e=>{e.networkState=wT.networkState,eI.reportApiInvoke(null,{name:"logUploadError",options:e,tag:pT.TRACER});});const tI=["CHINA","GLOBAL"],iI=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const s=r.join(""),o={};return o[e]=n,o[t]=s,Object.assign(o,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1});}();window.DEFAULT_TURN_CONFIG=iI,mC||(TC.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],TC.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],TC.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],TC.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],TC.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],TC.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],TC.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",TC.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",TC.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",TC.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",TC.AREAS=["NORTH_AMERICA","OVERSEA"]);const nI=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],rI=[];function sI(e,t){return !!t&&rI.some(i=>i.uid===e&&i.channelName===t);}ZC.__CLIENT_LIST__=rI;var oI,aI,cI,dI,lI,uI,hI,pI,_I,EI,mI,fI,gI,TI,SI,RI,CI,II=zi("Array").values,vI=ln,yI=Ze,AI=l,bI=II,wI=Array.prototype,OI={DOMTokenList:!0,NodeList:!0},NI=i(function(e){var t=e.values;return e===wI||AI(wI,e)&&t===wI.values||yI(OI,vI(e))?bI:t;});function DI(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o;}function PI(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t);}!function(e){e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY";}(oI||(oI={})),function(e){e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver";}(aI||(aI={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR";}(cI||(cI={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR";}(dI||(dI={})),function(e){e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND";}(lI||(lI={})),function(e){e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV";}(uI||(uI={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY";}(hI||(hI={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed";}(pI||(pI={})),function(e){e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream";}(_I||(_I={})),function(e){e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag";}(EI||(EI={})),function(e){e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats";}(mI||(mI={})),function(e){e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list";}(fI||(fI={})),function(e){e.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",e.NEED_ANSWER="NEED_ANSWER",e.NEED_RENEGOTIATE="NEED_RENEGOTIATE",e.P2P_LOST="P2P_LOST",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NEED_UNPUB="NEED_UNPUB",e.NEED_UNSUB="NEED_UNSUB",e.NEED_UPLOAD="NEED_UPLOAD",e.NEED_CONTROL="NEED_CONTROL",e.START_RECONNECT="START_RECONNECT",e.END_RECONNECT="END_RECONNECT",e.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT";}(gI||(gI={})),function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY";}(TI||(TI={})),function(e){e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire";}(SI||(SI={}));class LI extends Kg{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),sh(this,"name","AgoraRTCException");}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,jC);}throw(){super.throw(jC);}}function kI(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw jC.error("Invalid Channel Name ".concat(e)),new LI(Hg.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,");}function MI(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||$g(e,1,255)))throw new LI(Hg.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&jC.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.");}!function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming";}(RI||(RI={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",e[e.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",e[e.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN";}(CI||(CI={}));const UI={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},xI={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function VI(e,t){Xg(e.url,"".concat(t,".url"),1,1e3,!1),Zg(e.x)||zg(e.x,"".concat(t,".x"),0,1e4),Zg(e.y)||zg(e.y,"".concat(t,".y"),0,1e4),Zg(e.width)||zg(e.width,"".concat(t,".width"),0,1e4),Zg(e.height)||zg(e.height,"".concat(t,".height"),0,1e4),Zg(e.zOrder)||zg(e.zOrder,"".concat(t,".zOrder"),0,255),Zg(e.alpha)||zg(e.alpha,"".concat(t,".alpha"),0,1,!1);}const FI={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},BI={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var jI,GI,WI,HI,KI,YI,qI,zI,JI,XI,QI,ZI,$I,ev;function tv(e){if(!e.channelName)throw new LI(Hg.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new LI(Hg.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Xg(e.token,"info.token",1,2047),MI(e.uid),kI(e.channelName),!0;}!function(e){e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.INJECT_STREAM_STATUS="@live_uap-inject-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address";}(jI||(jI={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager";}(GI||(GI={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN";}(WI||(WI={})),function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort";}(HI||(HI={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile";}(KI||(KI={})),function(e){e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE";}(YI||(YI={})),function(e){e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE";}(qI||(qI={})),function(e){e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED";}(zI||(zI={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low";}(JI||(JI={})),function(e){e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_FAILBACK="datachannel_failback",e.RESET_SIGNAL="reset-signal";}(XI||(XI={})),function(e){e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON";}(QI||(QI={})),function(e){e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7";}(ZI||(ZI={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel";}($I||($I={})),function(e){e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS";}(ev||(ev={}));const iv=[ev.AFRICA,ev.ASIA,ev.CHINA,ev.EUROPE,ev.GLOBAL,ev.INDIA,ev.JAPAN,ev.NORTH_AMERICA,ev.OCEANIA,ev.OVERSEA,ev.SOUTH_AMERICA];var nv;!function(e){e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL";}(nv||(nv={}));const rv={CHINA:{},ASIA:{CODE:nv.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:nv.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:nv.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:nv.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:nv.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:nv.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:nv.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:nv.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:nv.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:nv.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:nv.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:nv.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:nv.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};var sv,ov,av,cv,dv,lv,uv,hv,pv,_v,Ev,mv,fv,gv,Tv,Sv,Rv,Cv,Iv,vv,yv,Av,bv,wv;mC&&(rv.CHINA={CODE:nv.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]}),function(e){e.UPDATE_BITRATE_LIMIT="update_bitrate_limit";}(sv||(sv={}));class Ov extends dT{constructor(e,t){super(),sh(this,"onICEConnectionStateChange",void 0),sh(this,"onConnectionStateChange",void 0),sh(this,"onDTLSTransportStateChange",void 0),sh(this,"onDTLSTransportError",void 0),sh(this,"onICETransportStateChange",void 0),sh(this,"onFirstAudioReceived",void 0),sh(this,"onFirstVideoReceived",void 0),sh(this,"onFirstAudioDecoded",void 0),sh(this,"onFirstVideoDecoded",void 0),sh(this,"onFirstVideoDecodedTimeout",void 0),sh(this,"onSelectedLocalCandidateChanged",void 0),sh(this,"onSelectedRemoteCandidateChanged",void 0);}}class Nv extends Ov{constructor(e,t){super(e,t);}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive";}(ov||(ov={})),function(e){e.VIDEO="video",e.AUDIO="audio";}(av||(av={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.RELAY=2]="RELAY";}(cv||(cv={})),function(e){e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.TCP_RESTART=1]="TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED";}(dv||(dv={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack";}(lv||(lv={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected";}(uv||(uv={})),function(e){e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE";}(hv||(hv={})),function(e){e.MUTE_LOCAL_VIDEO="mute_local_video",e.MUTE_LOCAL_AUDIO="mute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.MUTE_REMOTE_VIDEO="mute_remote_video",e.MUTE_REMOTE_AUDIO="mute_remote_audio",e.UNMUTE_REMOTE_VIDEO="unmute_remote_video",e.UNMUTE_REMOTE_AUDIO="unmute_remote_audio";}(pv||(pv={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED";}(_v||(_v={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED";}(Ev||(Ev={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url";}(mv||(mv={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK";}(fv||(fv={})),function(e){e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback";}(gv||(gv={})),function(e){e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation";}(Tv||(Tv={})),function(e){e[e.APP_TYPE_INVALID_VALUE=-1]="APP_TYPE_INVALID_VALUE",e[e.APP_TYPE_NATIVE=0]="APP_TYPE_NATIVE",e[e.APP_TYPE_NATIVE_COCOS=1]="APP_TYPE_NATIVE_COCOS",e[e.APP_TYPE_NATIVE_UNITY=2]="APP_TYPE_NATIVE_UNITY",e[e.APP_TYPE_NATIVE_ELECTRON=3]="APP_TYPE_NATIVE_ELECTRON",e[e.APP_TYPE_NATIVE_FLUTTER=4]="APP_TYPE_NATIVE_FLUTTER",e[e.APP_TYPE_NATIVE_UNREAL=5]="APP_TYPE_NATIVE_UNREAL",e[e.APP_TYPE_NATIVE_XAMARIN=6]="APP_TYPE_NATIVE_XAMARIN",e[e.APP_TYPE_NATIVE_API_CLOUD=7]="APP_TYPE_NATIVE_API_CLOUD",e[e.APP_TYPE_NATIVE_REACT_NATIVE=8]="APP_TYPE_NATIVE_REACT_NATIVE",e[e.APP_TYPE_NATIVE_PYTHON=9]="APP_TYPE_NATIVE_PYTHON",e[e.APP_TYPE_NATIVE_COCOS_CREATOR=10]="APP_TYPE_NATIVE_COCOS_CREATOR",e[e.APP_TYPE_NATIVE_RUST=11]="APP_TYPE_NATIVE_RUST",e[e.APP_TYPE_NATIVE_C_SHARP=12]="APP_TYPE_NATIVE_C_SHARP",e[e.APP_TYPE_NATIVE_CEF=13]="APP_TYPE_NATIVE_CEF",e[e.APP_TYPE_NATIVE_UNI_APP=14]="APP_TYPE_NATIVE_UNI_APP",e[e.APP_TYPE_WEBRTC=1e3]="APP_TYPE_WEBRTC",e[e.APP_TYPE_WEBRTC_REACT=1001]="APP_TYPE_WEBRTC_REACT",e[e.APP_TYPE_WEBRTC_VUE=1002]="APP_TYPE_WEBRTC_VUE",e[e.APP_TYPE_WEBRTC_ANGULAR=1003]="APP_TYPE_WEBRTC_ANGULAR";}(Sv||(Sv={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED";}(Rv||(Rv={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url";}(Cv||(Cv={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED";}(Iv||(Iv={})),function(e){e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check";}(vv||(vv={})),function(e){e.ABORT="abort";}(yv||(yv={})),function(e){e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video";}(Av||(Av={})),function(e){e[e.SUCCESS=1]="SUCCESS",e[e.FAILED=0]="FAILED";}(bv||(bv={})),function(e){e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed";}(wv||(wv={}));const Dv={[cI.ACCESS_POINT]:{[uI.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[uI.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[uI.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[uI.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[uI.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[uI.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[cI.UNILBS]:{[lI.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[lI.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[lI.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[lI.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[lI.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[lI.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[lI.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[lI.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[lI.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[lI.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[lI.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[lI.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[cI.STRING_UID_ALLOCATOR]:{[dI.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[dI.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[dI.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function Pv(e){const t=Dv[Math.floor(e/1e4)];if(!t)return {desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===cI.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return {desc:e.toString(),retry:!1};if("2"===t.toString()[0])return {desc:e.toString(),retry:!0};}return {desc:"unkonw error",retry:!1};}return i;}const Lv={[hI.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[hI.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[hI.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[hI.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[hI.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[hI.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[hI.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[hI.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[hI.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[hI.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[hI.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[hI.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[hI.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[hI.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[hI.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[hI.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[hI.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[hI.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[hI.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[hI.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[hI.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[hI.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[hI.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[hI.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[hI.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[hI.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[hI.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[hI.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[hI.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[hI.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[hI.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[hI.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[hI.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[hI.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[hI.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[hI.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[hI.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[hI.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[hI.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[hI.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[hI.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[hI.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[hI.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[hI.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[hI.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[hI.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[hI.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[hI.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[hI.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[hI.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[hI.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[hI.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[hI.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[hI.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[hI.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[hI.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[hI.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[hI.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[hI.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[hI.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[hI.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[hI.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function kv(e){const t=Lv[e];return t||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"};}function Mv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Uv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Mv(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Mv(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function xv(e){return e.every(e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING);}function Vv(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=RC("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150);}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r);}const Fv=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Bv=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,jv=/wss:\/\/(.+):([0-9]+)\/?/,Gv=/wss:\/\/(.[^\/]+)\/?/;let Wv=0;class Hv{constructor(e,t){sh(this,"id",0),sh(this,"store",void 0),sh(this,"recordIndex",void 0),sh(this,"websockets",[]),sh(this,"try443PortDuration",2e3),sh(this,"forceCloseWSDuration",5e3),sh(this,"try443PortTimeout",null),sh(this,"forceCloseTimeout",null),sh(this,"isTry443PortFailed",!1),sh(this,"isNormalPortFailed",!1),sh(this,"useDoubleDomain",!1),sh(this,"useProxy",!1),sh(this,"startTime",Date.now()),this.id=++Wv,this.try443PortDuration=RC("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t;}closeAllWebsockets(){this.websockets.forEach(e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close();}),this.websockets.length=0;}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout);}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];jC.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n);}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=RC("GATEWAY_DOMAINS"),r=Date.now(),s=[],o=n.find(t=>{var i;return bn(i=e.host).call(i,t);});o||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach(i=>{a.push(Vv(Uv(Uv({},e),{},{host:e.host.replace(o,i)}),t));});else {const i=Uv({},e);if(t&&o){const e=n.find(e=>e!==o);e&&(i.host=i.host.replace(o,e));}a.push(Vv(i,t));}try{a.forEach(e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",s.push(t),this.logger("ws is connecting:",t.url);});}catch(n){if(this.logger("ws create failed"),s.forEach(e=>e.close()),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new LI(Hg.WS_ERR,"init websocket failed! Error: ".concat(n.toString()));}const c=lg();this.store&&this.store.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},this.recordIndex),s.forEach(e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach(t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)));}),this.websockets.length=0,c.resolve(e);},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState)),t?this.isTry443PortFailed=xv(s):this.isNormalPortFailed=xv(s),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:QI.A_ROUND_WS_FAILED}));},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data));}),this.websockets.push(...s);return i||(()=>{const i=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.websockets.forEach(e=>e.readyState!==WebSocket.OPEN&&e.close());};if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{if(this.logger("2s timeout, isWebsocket created: ",c.isResolved),c.isResolved)return i();Sg().os===_g.MAC_OS&&wg()&&i(),this.createWebSocket(e,!0,!0).then(e=>c.resolve(e)).catch(e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed");}),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);},this.try443PortDuration);})(),c.promise;}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return [,t,i,n]=e.match(Fv)||[],t||([,i,n]=e.match(Bv)||[]),i&&n||([,i,n]=e.match(jv)||[]),i&&n||([,i]=e.match(Gv)||[]),i||jC.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"};}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(jC.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally(()=>this.clearTimeout());}}function Kv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}class Yv extends dT{get url(){return this.websocket&&this.websocket.url||null;}get reconnectMode(){return this._reconnectMode;}set reconnectMode(e){var t;bn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e;}get state(){return this._state;}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(SI.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(SI.CONNECTED):"closed"===this._state?this.emit(SI.CLOSED):"failed"===this._state&&this.emit(SI.FAILED));}resetReconnectCount(e){jC.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0;}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),sh(this,"connectionID",0),sh(this,"currentURLIndex",0),sh(this,"urls",[]),sh(this,"_reconnectMode","tryNext"),sh(this,"reconnectReason",void 0),sh(this,"_initMutex",new pS("websocket")),sh(this,"name",void 0),sh(this,"_state","closed"),sh(this,"reconnectInterrupter",void 0),sh(this,"websocket",void 0),sh(this,"retryConfig",void 0),sh(this,"reconnectCount",0),sh(this,"forceCloseTimeout",5e3),sh(this,"onlineReconnectListener",void 0),sh(this,"useCompress",void 0),sh(this,"tryDoubleDomain",!1),sh(this,"use443PortOnly",!1),sh(this,"wsInflateLength",0),sh(this,"wsDeflateLength",0),sh(this,"closeEstablishingWs",()=>{}),sh(this,"store",void 0),sh(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Kv(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Kv(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=r;const{timeout:o,timeoutFactor:a}=t,c=Math.max(300,Math.floor(3*o/5)),d=Math.max(1.2,Math.floor(8*a)/10);gT.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),wT.on(TT.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gT.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=a));});}getConnection(){return this.websocket||void 0;}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=lg(),t=this.urls[this.currentURLIndex];this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(SI.CLOSED,()=>{e.reject(new Kg(Hg.WS_DISCONNECT));}),this.once(SI.CONNECTED,e.resolve),await e.promise;}catch(e){}finally{i();}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout(()=>e.close(),500):e.close(),this.websocket=void 0;}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs();}reconnect(e,t){if(!this.websocket)return void jC.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),jC.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t});}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Kg(Hg.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e);}catch(e){throw new Kg(Hg.WS_ERR,"send websocket message error"+e.toString());}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength;}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t};}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0;}async createWebSocketConnection(e){var t;const i=lg();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),jC.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve();},r=async e=>{var t;if(jC.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new Kg(Hg.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else {"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=AT(this,SI.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void jC.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new Kg(Hg.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve();}},s=e=>{this.emit(SI.ON_MESSAGE,e);},o=e=>{jC.warn("[".concat(this.connectionID,"] ws open error ").concat(e));};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),RC("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=RC("GATEWAY_WSS_ADDRESS")),jC.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=s,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a;}catch(e){const t="closed"===this.state,n=e instanceof Kg,s=n&&e.code===Hg.WS_ABORT,o=n&&e.code===Hg.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());jC.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},a),t||o?(i.reject(t?new Kg(Hg.WS_DISCONNECT,"websocket is closed: ".concat(c)):new Kg(Hg.WS_ERR,"init websocket failed: ".concat(c))),o&&jC.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e);}return i.promise;}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return !1;if(0===this.urls.length)return !1;if("closed"===this.state)return !1;jC.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||wT.isOnline||!wT.onlineWaiter||(this.onlineReconnectListener=wT.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0;}));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=mS(this.reconnectCount,this.retryConfig);jC.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await cg.race([iS(t),this.onlineReconnectListener||new cg(()=>{})]);}if("closed"===this._state||!i)return !1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(SI.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e);};try{if("retry"===e)this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);jC.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);}else "recover"===e&&(jC.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(SI.RECONNECT_WAITTING_FINISH,e),this.urls=await vT(this,SI.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e));}catch(i){var r;jC.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&bn(n).call(n,"dynamic key expired")?(this.emit(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t);}return !0;}}class qv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0);}async chooseBestWebsocketConnection(e,t){const i=lg(),n=function(e,t){return new Hv(e,t);}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{jC.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new Kg(Hg.WS_ABORT,"choose best websocket aborted"));};const r=RC("GATEWAY_DOMAINS");return jC.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally(()=>{this.closeEstablishingWs=void 0;});}}class zv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0);}async chooseBestWebsocketConnection(e,t){return new cg((i,n)=>{let r=!1;const s=[];this.closeEstablishingWs=()=>{jC.debug("[choose-best-ws] close establishing websockets"),s.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close();}),n(new Kg(Hg.WS_ABORT,"choose best websocket aborted"));};const o=RC("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=o.find(t=>-1!==c?bn(e).call(e,t,c):bn(e).call(e,t));jC.debug("[choose-best-ws] currentDomain: ",d,", domains: ",o);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{o.forEach(t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",s.push(n),jC.debug("[choose-best-ws] ws is connecting:",n.url);});}catch(e){for(jC.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(e=>e.close());s.length;)s.pop();l=!0;}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},t),s.forEach(e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;jC.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter(t=>t!==e).forEach(e=>{jC.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close();}),r=!0,i(e);},e.onclose=e=>{if(a=e,r)return;s.find(e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))||(jC.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a));},e.onmessage=t=>{jC.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data));};}),iS(this.forceCloseTimeout).then(()=>{s.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close();});});}if(l){var h;let r;jC.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),s.push(r),r.binaryType="arraybuffer";}catch(e){const t=new Kg(Hg.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return jC.error("[".concat(this.name,"]").concat(t)),void n(t);}r.onopen=()=>{i(r);},r.onclose=e=>{n(e);},r.onmessage=e=>{jC.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data));},iS(this.forceCloseTimeout).then(()=>{r&&r.readyState!==WebSocket.OPEN&&r.close();});}}).then(e=>(this.closeEstablishingWs=void 0,e)).catch(e=>{throw this.closeEstablishingWs=void 0,e;});}}class Jv extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket&&this.websocket.url||null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"wsInflateDataTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close();}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fT.OFFLINE);});}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t();},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.PUBLISH_DATASTREAM&&e!==EI.SUBSCRIBE&&e!==EI.SUBSCRIBE_DATASTREAM&&e!==EI.UNSUBSCRIBE&&e!==EI.UNSUBSCRIBE_DATASTREAM&&e!==EI.UNPUBLISH&&e!==EI.UNPUBLISH_DATASTREAM&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,()=>{i(new LI(Hg.DISCONNECT_P2P));}),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,()=>{i(new LI(Hg.DISCONNECT_P2P));});});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),this.websocket.sendMessage(s,!0),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((t,i)=>{this.once(_I.WS_CONNECTED,()=>t(this.joinResponse)),this.once(_I.WS_CLOSED,()=>i(this.initError||new LI(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData();},2e4);});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents());}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,QI.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return !!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id});}),!0);}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e});}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(SI.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(SI.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(SI.WILL_RECONNECT,(e,t,i)=>{const n=bT(this,_I.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(jC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=QI.P2P_DISCONNECTED),r&&(jC.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(_I.REPORT_JOIN_GATEWAY,t||QI.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),i(e);}),this.websocket.on(SI.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{jC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",fT.SERVER_ERROR);}):this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code||QI.UNKNOWN_REASON,this.url||""),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fT.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);});}}var Xv="\t\n\v\f\r    \u2028\u2029\ufeff",Qv=J,Zv=pn,$v=Xv,ey=d("".replace),ty=RegExp("^["+$v+"]+"),iy=RegExp("(^|[^"+$v+"])["+$v+"]+$"),ny=function(e){return function(t){var i=Zv(Qv(t));return 1&e&&(i=ey(i,ty,"")),2&e&&(i=ey(i,iy,"$1")),i;};},ry={start:ny(1),end:ny(2),trim:ny(3)},sy=zd.PROPER,oy=n,ay=Xv,cy=ry.trim;wi({target:"String",proto:!0,forced:function(e){return oy(function(){return !!ay[e]()||"…"!=="…"[e]()||sy&&ay[e].name!==e;});}("trim")},{trim:function(){return cy(this);}});var dy,ly,uy=zi("String").trim,hy=l,py=uy,_y=String.prototype,Ey=i(function(e){var t=e.trim;return "string"==typeof e||e===_y||hy(_y,e)&&t===_y.trim?py:t;});function my(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function fy(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?my(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):my(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function gy(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(RC("TURN_DOMAIN")):(jC.info("Unidentified as ip: ".concat(e,", use as host")),e);}function Ty(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(RC("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map(e=>{let{ip:t,port:i}=e;return {address:"".concat(t,":").concat(i)};});const i=RC("GATEWAY_DOMAINS");let n=i[1]&&bn(t).call(t,i[1])?1:0;return e.map(e=>{let{domain_prefix:t,port:r,ip:s}=e;if(t)return {address:"".concat(t,".").concat(i[n++%i.length],":").concat(r)};const o=/^[\.\:\d]+$/.test(s),a=o?"".concat(s.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(r):"".concat(s,":").concat(r);return o||jC.info("Unidentified as ip: ".concat(s,", use as host")),{ip:s,port:r,address:a};});}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t<e.length;t++){var r;const n=Ey(r=e[t]).call(r);i[t]&&n&&(i[t].ip6=n);}}return {gatewayAddrs:i,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]};}function Sy(e){return "number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0;}function Ry(e){const t=e._encoderConfig;if(!t)return {};const i={resolution:t.width&&t.height?"".concat(Sy(t.width),"x").concat(Sy(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return "number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i;}function Cy(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0;}function Iy(e,t){let i,n,r;switch(t){case dy.CHOOSE_SERVER:n=4096,r="choose server";break;case dy.CLOUD_PROXY:n=1048576,r="proxy";break;case dy.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case dy.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new LI(Hg.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1});}if(e.response_body.forEach(t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map(e=>fy(fy({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:fy(fy({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert});}),!i)throw new LI(Hg.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i;}async function vy(e,t){return await cg.all(e.addresses.map(async e=>({address:gy(e.ip),tcpport:e.port,udpport:e.port,username:t&&RC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():iI.username,password:t&&RC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await cT(t.toString()):iI.password})));}function yy(e,t){const i=t._videoHeight||t.getMediaStreamTrack(!0).getSettings().height;return i?Math.max(i/Sy(e.height),1):(jC.warning("can't get ori-track's height, default scale down 4 times for low stream"),4);}function Ay(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:s,protocol:o}=e;return "local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:o}:{candidateType:t,relayProtocol:i,address:r,port:s,protocol:o};}function by(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}!function(e){e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK";}(dy||(dy={}));class wy extends dT{get url(){return this._url?this._url:null;}get reconnectMode(){return this._reconnectMode;}set reconnectMode(e){var t;bn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e;}get state(){return this._state;}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(gv.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(gv.CONNECTED):"closed"===this._state?this.emit(gv.CLOSED):"failed"===this._state&&this.emit(gv.FAILED));}constructor(e,t,i,n){super(),sh(this,"connectionID",0),sh(this,"currentURLIndex",0),sh(this,"reconnectReason",void 0),sh(this,"_reconnectMode","tryNext"),sh(this,"_name",void 0),sh(this,"_state","closed"),sh(this,"_retryConfig",void 0),sh(this,"_reconnectCount",0),sh(this,"_forceCloseTimeout",5e3),sh(this,"_onlineReconnectListener",void 0),sh(this,"_closeEstablishingTransmitter",()=>{}),sh(this,"_store",void 0),sh(this,"_joinChannelServiceRecordIndex",void 0),sh(this,"_useCompress",void 0),sh(this,"_inflateLength",0),sh(this,"_deflateLength",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?by(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):by(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({},t),this._useCompress=i;}resetReconnectCount(e){jC.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0;}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout(()=>e.close(),500):e.close(),this._transmitter=void 0;}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter();}reconnect(e,t){if(!this._transmitter)return void jC.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),jC.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t});}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t};}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength;}clearInflateData(){this._inflateLength=0,this._deflateLength=0;}}!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack";}(ly||(ly={}));class Oy{constructor(e,t,i){sh(this,"version",1),sh(this,"initialRTO",void 0),sh(this,"maxBatchAckCount",void 0),sh(this,"maxRTO",void 0),sh(this,"initialRTT",void 0),sh(this,"ID",void 0),sh(this,"rtt",void 0),sh(this,"packetNumber",1),sh(this,"rtoRatioMap",new Map()),sh(this,"timeoutMap",new Map()),sh(this,"unorderedPacketQueue",[]),sh(this,"batchAckPacketQueue",[]),sh(this,"lastOrderedPacketNumber",0),sh(this,"batchAckTimer",void 0),sh(this,"sendImpl",void 0),sh(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=nS(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:RC("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:RC("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:RC("TRANSMITTER_MAX_RTO");}packetize(e,t){return {type:ly.Default,version:this.version,packetNumber:t,payload:e};}serialize(e){switch(e.type){case ly.Default:{let t;if("string"==typeof e.payload){t=new TextEncoder().encode(e.payload);}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),tT(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i;}case ly.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),tT(i,8,BigInt(e.ackSendTs)),t;}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case ly.Default:{const r=t.getUint32(3),s=eT(t,7),o=e.slice(15),a=new TextDecoder().decode(o);return {version:i,type:n,packetNumber:r,sendTs:Number(s),payload:a};}case ly.Ack:{const e=t.getUint32(3),r=t.getUint8(7),s=eT(t,8);return {version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(s)};}default:throw jC.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n));}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout(()=>{this.resendMessage(t);},i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t);}onData(e){const t=this.deserialize(e);t.type===ly.Default?this.ack(t):t.type===ly.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t));}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(e=>{let[t,i]=e;window.clearTimeout(i);}),this.timeoutMap=new Map(),this.rtoRatioMap=new Map(),this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer);}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout(()=>{this.resendMessage(e);},t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e);}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i;}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8;}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout(()=>{this.batchAck();},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break;}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1;}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t);}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t);}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:ly.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[];}sendPacket(e){e.type===ly.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t);}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t);}}}class Ny extends wy{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),sh(this,"_initMutex",void 0),sh(this,"_reconnectInterrupter",void 0),sh(this,"_url",void 0),sh(this,"_transmitter",void 0),sh(this,"_addresses",void 0),sh(this,"_reliableTransmission",void 0),this._initMutex=new pS("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);gT.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s),wT.on(TT.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gT.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n));});}getConnection(){if(this._reliableTransmission)return this._reliableTransmission;}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex(e=>e.fingerprint||RC("FINGERPRINT"));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(gv.CLOSED,()=>i(new LI(Hg.WS_DISCONNECT))),this.once(gv.CONNECTED,()=>t());};return this._initMutex.lock().then(e=>new cg((e,t)=>{i(e,t);}).then(()=>{e();}).catch(()=>{e();}));}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new LI(Hg.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e);}catch(e){throw new LI(Hg.WS_ERR,"send datachannel signal message error"+e.toString());}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null);}sendMessageWithJSON(e){const t=JSON.stringify(e);return {compressed:t,compressedLength:t.length,origin:e};}sendMessageWithUint8Array(e){return {compressed:e,compressedLength:e.byteLength,origin:e};}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new cg((t,i)=>{var n;const r=()=>{jC.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t();},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),jC.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const n=AT(this,gv.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void jC.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new LI(Hg.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t();}else i(new LI(Hg.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close();},o=e=>{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data);};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),jC.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();vT(this,gv.TO_CONNECT_DATACHANNEL,e).then(e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;jC.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new Oy(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e));},e=>{"string"==typeof e&&this.emit(gv.ON_MESSAGE,e);}),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d();},r&&r(),n.onclose=s,n.onmessage=o,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a;}).catch(e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof LI&&e.code===Hg.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof LI&&e.code===Hg.WS_ERR){const t=new LI(Hg.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return jC.error("[".concat(this._name,"]").concat(t)),void i(t);}s&&s(e);}else i(new LI(Hg.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())));});});}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return !1;if(!this._addresses)return !1;if("closed"===this.state)return !1;this._onlineReconnectListener||wT.networkState!==gT.OFFLINE||(this._onlineReconnectListener=wT.onlineWaiter&&wT.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0;}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1;},t){const t=mS(this._reconnectCount,this._retryConfig);jC.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await cg.race([iS(t),this._onlineReconnectListener||new cg(()=>{})]);}if("closed"===this.state||!i)return !1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(gv.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e);};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e);}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||RC("FINGERPRINT")){this.currentURLIndex=e;break;}this.currentURLIndex+=1;}if(this.currentURLIndex>=this._addresses.length)return jC.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);jC.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e);}else "recover"===e&&(jC.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(gv.RECONNECT_WAITTING_FINISH,e),this.emit(gv.FAILBACK));return !0;}catch(i){var r,s;return jC.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&bn(s=i.data.desc).call(s,"dynamic key expired")?(this.emit(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t);}}}class Dy extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket?this.websocket.url:null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"inflateDataTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"onWebsocketMessage",e=>{if(e instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")&&(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Ny("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fv.OFFLINE);});}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t();},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.SUBSCRIBE&&e!==EI.UNSUBSCRIBE&&e!==EI.UNPUBLISH&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,()=>{i(new LI(Hg.DISCONNECT_P2P));}),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,()=>{i(new LI(Hg.DISCONNECT_P2P));});});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),e===EI.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(s,!0,!1),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("dc request timeout, type: ".concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fv.MULTI_IP)):this.reconnect(u.action,fv.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((i,n)=>{this.once(_I.WS_CONNECTED,()=>i(this.joinResponse)),this.once(_I.WS_CLOSED,()=>n(this.initError||new LI(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(gv.FAILBACK,()=>{void 0===this.openConnectionTime&&n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT));}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData();},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(jC.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT)));},RC("DC_JOIN_WITH_FAILBACK"));});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new Ny("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents());}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.DATACHANNEL_CONNECTING),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return !!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id});}),!0);}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fv.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fv.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e});}handleWebsocketEvents(){this.websocket.on(gv.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(gv.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(gv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(gv.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(gv.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(gv.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(gv.WILL_RECONNECT,(e,t)=>{if(bT(this,_I.IS_P2P_DISCONNECTED)&&"retry"===e)return jC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(jC.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),t(e);}),this.websocket.on(gv.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{jC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",fv.SERVER_ERROR);}):this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fv.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fv.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(gv.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);}),this.websocket.on(gv.TO_CONNECT_DATACHANNEL,async(e,t,i)=>vT(this,_I.DATACHANNEL_PRECONNECT,e).then(t).catch(i)),this.websocket.on(gv.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(_I.DATACHANNEL_FAILBACK);});}}class Py extends dT{constructor(e,t){super(),sh(this,"signal",void 0),sh(this,"token",void 0),sh(this,"tokenTimeout",void 0),sh(this,"tokenInterval",void 0),sh(this,"_sequence",0),sh(this,"userMap",new Map()),sh(this,"encoder",new TextEncoder()),this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===pI.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*RC("P2P_TOKEN_INTERVAL"));};i();}async send(e,t,i,n,r){var s,o,a;if(0===this.userMap.size)return;const c=Array.from(NI(s=this.userMap).call(s))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(o=n)&&void 0!==o?o:nS(6,""),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:n,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(c)};RC("SHOW_P2P_LOG")&&jC.debug("send message",d,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(d)).forEach(e=>{this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(e))});});const l=new cg((t,r)=>{const s=window.setTimeout(()=>{this.off("res-@".concat(n,"_ack"),o),this.off("res-@".concat(n),c),this.off(yv.ABORT,a),jC.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?r(new Kg(Hg.INVALID_REMOTE_USER)):r(new Kg(Hg.TIMEOUT));},RC("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),o=()=>{s&&window.clearTimeout(s),this.off(yv.ABORT,a),i&&t();},a=()=>{s&&window.clearTimeout(s),this.off("res-@".concat(n,"_ack"),o),this.off("res-@".concat(n),c),r(new Kg(Hg.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)));};this.once(yv.ABORT,a),this.once("res-@".concat(n,"_ack"),o);const c=(i,c)=>{l=!0,s&&window.clearTimeout(s),this.off("res-@".concat(n,"_ack"),o),this.off(yv.ABORT,a),"success"===i?t(c):r(new Kg(Hg.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)));};let l=!1;i||(this.once("res-@".concat(n),c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{l||jC.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(d));}));});try{return await l;}catch(s){if(s.code===Hg.TIMEOUT)return await this.send(e,t,i,n,r);throw s;}}onMessage(e){var t;const{_uid:i}=e;let n,r=this.userMap.get(i);if(r)n=r.splitMessageMap;else {if(this.userMap.size>0||!("_type"in e)||e._type!==vv.CHECK)return;const{token:t}=e;n=new Map(),r={uid:i,isStart:!0,token:t,splitMessageMap:n,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map()},this.userMap.set(i,r),this.signal.emit(fI.ON_USER_ONLINE,{uid:i}),this.handleUserOnline();}if("id"in e&&"total"in e){var s;const{id:t,total:r}=e,o=null!==(s=n.get(t))&&void 0!==s?s:[];if(o.push(e),n.has(t)||n.set(t,o),o.length!==r)return;{const r=ep(o).call(o,(e,t)=>e.index-t.index).map(e=>e.payload).join("");n.delete(t),(e=JSON.parse(r))._uid=i;}}const{_type:o,token:a}=e;if(bn(t=[vv.ACK,vv.CHECK]).call(t,o))return o===vv.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):jC.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e);}check(){const e={_id:nS(6,""),token:this.token,_type:vv.CHECK};RC("SHOW_P2P_LOG")&&jC.debug("send message",e),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(e)))});}ack(e){const t={_id:e,_type:vv.ACK,token:this.token};RC("SHOW_P2P_LOG")&&jC.debug("send message",t),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(t)))});}response(e,t,i){this.send(vv.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e);}handleReceivedMessage(e){const t=()=>{this.userMap.forEach(e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++;}});};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this.userMap.get(i),{receivedMessagesMap:s,isStart:o,nextExpectedSequenceNumber:a}=r;if(n<a)return this.ack(e._id),void jC.debug("[external-signal] receive old message, seq: ".concat(n,", ").concat(e._message));s.set(n,e),o&&n===a&&(this.receiveMessage(e),s.delete(a),r.nextExpectedSequenceNumber++,t());}receiveMessage(e){const{_id:t,_type:i,_message:n,_uid:r}=e;if(RC("SHOW_P2P_LOG")&&jC.debug("receive message",e),t){let s;switch(e._type!==vv.ACK&&(n&&(s=JSON.parse(n)),this.ack(e._id)),e._type){case vv.CANDIDATE:case vv.CONTROL:this.signal.emit(i,s,r);break;case vv.PUBLISH:case vv.UNPUBLISH:case vv.RESTART_ICE:case vv.CALL:s.uid=r,vT(this.signal,i,s).then(t=>{this.response(e._id,t);}).catch(()=>{this.response(e._id,void 0,!0);});break;case vv.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case vv.RESPONSE:{const{success:e,message:i}=s;this.emit("res-@".concat(t),e?"success":"failed",i);break;}}}}splitMessage(e){if(e.length<Py.MAX_MESSAGE_SIZE)return [e];const t=[],{remoteToken:i}=JSON.parse(e),n=nS(6,"");let r=0,s=800;const o=Math.ceil(e.length/s);for(;e.length>0;){r++;const a={id:n,index:r,total:o,payload:e.slice(0,s),token:"".concat(this.token,"_").concat(i)};JSON.stringify(a).length>Py.MAX_MESSAGE_SIZE?s-=50:(t.push(a),e=e.slice(s));}return t.map(e=>JSON.stringify(e));}handleCheckToken(e,t){return e.token!==t?(jC.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout(()=>{jC.debug("token timeout, ".concat(t)),this.reset(e.uid);},RC("MAX_P2P_TIMEOUT")),!0);}async handleUserOnline(){const e=await vT(this.signal,vv.CALL,void 0),t=await this.send(vv.CALL,e);this.signal.emit(_I.P2P_CONNECTION,t,!0);}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(yv.ABORT),this.signal.emit(fI.ON_USER_OFFLINE,{uid:i.uid,reason:wv.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(jC.debug("change local token from ".concat(t," to ").concat(t)),this.token=nS(6,"")));}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(yv.ABORT);}}sh(Py,"MAX_SIZE",1),sh(Py,"MAX_MESSAGE_SIZE",1024);class Ly extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket&&this.websocket.url||null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"p2pToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"_external_signal",void 0),sh(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case fI.ON_DATA_STREAM:return void this.handleDataStream(t._message);case fI.MUTE_AUDIO:case fI.MUTE_VIDEO:case fI.ON_P2P_LOST:case fI.ON_USER_ONLINE:return;case fI.ON_USER_OFFLINE:const{uid:e}=t._message;return jC.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e);}if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close();}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fT.OFFLINE);}),this.p2pToken=nS(6,""),this._external_signal=new Py(this,this.p2pToken);}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((e,t)=>{if(this.connectionState===pI.CONNECTED)return e();const i=()=>{this.off(_I.WS_CLOSED,n),e();},n=()=>{this.off(_I.WS_CONNECTED,i),t(new Kg(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,i),this.once(_I.WS_CLOSED,n);});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),this.websocket.sendMessage(s,!0),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new Kg(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new Kg(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new Kg(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i);}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((t,i)=>{this.once(_I.WS_CONNECTED,()=>t(this.joinResponse)),this.once(_I.WS_CLOSED,()=>i(this.initError||new Kg(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i);});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents()),this.p2pToken=nS(6,""),this._external_signal.clear(),this._external_signal=new Py(this,this.p2pToken);}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleDataStream(e){try{var t;const i=XT(e.payload),n=new TextDecoder().decode(i),r=JSON.parse(n);"total"in r&&"id"in r||bn(t=Object.values(vv)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(fI.ON_DATA_STREAM,e);}catch(t){this.emit(fI.ON_DATA_STREAM,e);}}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(SI.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(SI.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(SI.WILL_RECONNECT,(e,t,i)=>{"retry"!==e?(jC.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION)):jC.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e);}),this.websocket.on(SI.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Kg&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fT.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);});}}function ky(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function My(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ky(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ky(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}const Uy=new Map();class xy extends dT{get state(){return this._state;}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(XI.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(XI.CONNECTION_STATE_CHANGE,e,t);}get joinGatewayStartTime(){return this._joinGatewayStartTime;}set joinGatewayStartTime(e){jC.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e;}constructor(e,t){super(),sh(this,"store",void 0),sh(this,"joinInfo",void 0),sh(this,"key",void 0),sh(this,"ntpOffset",0),sh(this,"signal",void 0),sh(this,"role",void 0),sh(this,"inChannelInfo",{joinAt:null,duration:0}),sh(this,"spec",void 0),sh(this,"_state","DISCONNECTED"),sh(this,"_statsCollector",void 0),sh(this,"_disconnectedReason",void 0),sh(this,"isSignalRecover",!1),sh(this,"hasChangeBGPAddress",!1),sh(this,"trafficStatsInterval",void 0),sh(this,"networkQualityInterval",void 0),sh(this,"_joinGatewayStartTime",0),sh(this,"_signalTimeout",!1),sh(this,"_clientRoleOptions",void 0),sh(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?new Ly(My(My({},t),{},{retryConfig:t.websocketRetryConfig}),e):this.store.useDataChannel?new Dy(My(My({},t),{},{retryConfig:t.websocketRetryConfig}),e):new Jv(My(My({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents();}async join(e,t,i){if(this.signal instanceof Dy){let t=!1;"disabled"!==e.cloudProxyServer?(jC.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length>255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(jC.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.apResponse.addresses.some(e=>e.fingerprint)||RC("FINGERPRINT")||(jC.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal();}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=Uy.get(e.cname);if(r||(r=new Map(),Uy.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new LI(Hg.UID_CONFLICT);throw eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,t;}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const o=e.proxyServer;try{let t;if(jC.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof Dy?"datachannel":"websocket"," join uid ").concat(s)),this.signal instanceof Dy)t=await this.signal.init(e.apResponse.addresses,i);else {const n=e.gatewayAddrs.map(t=>{let{address:i}=t;const[n,r]=i.split(":"),s={host:n,port:r};return e.proxyServer&&(s.proxy=e.proxyServer),s;});t=await this.signal.init(n,i);}s=t.uid,jC.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof Dy?"datachannel":"websocket"," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime));}catch(t){if(t&&t.code===Hg.INIT_WEBSOCKET_TIMEOUT)throw jC.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===Hg.INIT_DATACHANNEL_TIMEOUT)throw jC.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw jC.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!o,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t;}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),jC.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{jC.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString());});},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_dnq)}):this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0});},2e3),this.store.joinGatewayEnd(),s;}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==ET.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==pI.CONNECTED||(await function(e,t){return t===1/0?e:cg.race([e,tS(t)]);}(this.signal.request(EI.LEAVE,void 0,!0),3e3));}catch(e){jC.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e);}this.signal.close(t),t!==ET.FALLBACK&&(this.state="DISCONNECTED"),this.reset();}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:RC("PUB_EXTEND"),twcc:!!RC("PUBLISH_TWCC"),rtx:!!RC("USE_PUB_RTX")};try{return (await this.signal.request(EI.PUBLISH,n,!0))._message;}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n;}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(EI.PUBLISH_DATASTREAM,r,!0);}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n;}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(EI.UNPUBLISH,{stream_id:t,ortc:e},!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] unpublish warning: "),e);}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cg.all(e.map(e=>this.signal.request(EI.UNPUBLISH_DATASTREAM,{channel_id:e},!0)));}catch(e){jC.warning("unpublish datachannels warning: ",e);}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC("SUBSCRIBE_TWCC"),rtx:!!RC("USE_SUB_RTX")||void 0,extend:RC("SUB_EXTEND"),svc:Array.isArray(RC("SVC"))&&0!==RC("SVC").length?RC("SVC"):void 0};try{return await this.signal.request(EI.PRE_SUBSCRIBE,n,!0);}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n;}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC("SUBSCRIBE_TWCC"),rtx:!!RC("USE_SUB_RTX"),extend:RC("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(RC("SVC"))&&0!==RC("SVC").length?RC("SVC"):void 0};try{return (await this.signal.request(EI.SUBSCRIBE,n,!0))._message;}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n;}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void(await this.signal.request(EI.SUBSCRIBE_DATASTREAM,n,!0));}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n;}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!RC("USE_SUB_RTX")};try{return await this.signal.request(EI.SUBSCRIBE_STREAMS,i,!0);}catch(i){if(t&&i.data&&i.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i;}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return "number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0;}(e);if(t)return this.signal.request(EI.SET_VIDEO_PROFILE,t);jC.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"));}async unsubscribe(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e);}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cg.all(e.map(e=>this.signal.request(EI.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0)));}catch(e){jC.warning("unsubscribeDataChannel warning: ",e);}}async massUnsubscribe(e){try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,e,!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e);}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return {gatewayEstablishParams:await this.signal.request(EI.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()};}getGatewayInfo(){return this.signal.request(EI.GATEWAY_INFO);}async renewToken(e){await this.signal.request(EI.RENEW_TOKEN,e),this.key=e.token;}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(EI.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e;}async setRemoteVideoStreamType(e,t){await this.signal.request(EI.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t});}async setDefaultRemoteVideoStreamType(e){await this.signal.request(EI.DEFAULT_VIDEO_STREAM,{stream_type:e});}async setStreamFallbackOption(e,t){await this.signal.request(EI.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t});}async pickSVCLayer(e,t){await this.signal.request(EI.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer});}async setRTM2Flag(e){await this.signal.request(EI.SET_RTM2_FLAG,{rtm2_flag:e});}async sendExtensionMessage(e,t,i){if(this.signal instanceof Ly)return this.signal.sendExtensionMessage(e,t,i);}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),My({},this.inChannelInfo);}async getGatewayVersion(){return (await this.signal.request(EI.GATEWAY_INFO)).version;}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=Uy.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid);}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0);}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:iI.username,password:iI.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null;}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(My(My({},iI),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}));}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(EI.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach(e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(t=>t.peer_uid===e.peer_uid);t&&t.B_st!==e.B_st&&KT(()=>{this.emit(XI.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st);});}),this._statsCollector.updateTrafficStats(e);}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new LI(Hg.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=RC("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i);}catch(e){i=void 0;}i&&i.length>128&&(i=void 0);const n=My({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:EC,browser:navigator.userAgent,process_id:RC("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:RC("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:RC("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:RC("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof RC("SUBSCRIBE_AUDIO_FILTER_TOPN")?RC("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof RC("ENABLE_PUBLISH_AUDIO_FILTER")?RC("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof RC("ENABLE_USER_LICENSE_CHECK")?RC("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:!0===RC("USE_PUB_RTX")||!0===RC("USE_SUB_RTX")||void 0,disableFEC:RC("DISABLE_FEC"),enableNTPReport:!!RC("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!RC("ENABLE_INSTANT_VIDEO")||void 0,enableDataStream2:"boolean"==typeof RC("ENABLE_DATASTREAM_2")?RC("ENABLE_DATASTREAM_2"):void 0,rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!RC("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:"boolean"==typeof RC("USE_XR")?RC("USE_XR"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,RC("ENCRYPT_AES")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n;}getRejoinMessage(){if(!this.joinInfo)throw new LI(Hg.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return {session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)};}handleSignalEvents(){this.signal.on(_I.WS_RECONNECT_WAITTING_FINISH,e=>{var t;bn(t=["tryNext","recover"]).call(t,e)&&this.joinInfo&&eI.adjustSessionStartTime(this.joinInfo.sid);}),this.signal.on(_I.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now();}),this.signal.on(_I.WS_RECONNECTING,e=>{this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||fT.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",eI.sessionInit(this.joinInfo.sid,{lts:new Date().getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now());}),this.signal.on(_I.WS_CLOSED,e=>{let t;switch(e){case ET.LEAVE:t=fT.LEAVE;break;case ET.UID_BANNED:case ET.IP_BANNED:case ET.CHANNEL_BANNED:case ET.SERVER_ERROR:t=fT.SERVER_ERROR;break;case ET.FALLBACK:t=fT.FALLBACK;break;case ET.LICENSE_MISSING:case ET.LICENSE_EXPIRED:case ET.LICENSE_MINUTES_EXCEEDED:case ET.LICENSE_PERIOD_INVALID:case ET.LICENSE_MULTIPLE_SDK_SERVICE:case ET.LICENSE_ILLEGAL:case ET.TOKEN_EXPIRE:t=e;break;default:t=fT.NETWORK_ERROR;}jC.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+fT.NETWORK_ERROR)),this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===ET.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==ET.FALLBACK&&(this.state="DISCONNECTED"),this.reset();}),this.signal.on(_I.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(jC.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void jC.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));SC("EVENT_REPORT_DOMAIN",e[1]),SC("EVENT_REPORT_BACKUP_DOMAIN",e[1]),SC("LOG_UPLOAD_SERVER","".concat(e[1],":6444"));}}),this.signal.on(fI.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e);}),this.signal.on(_I.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new LI(Hg.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,vT(this,XI.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i);}),this.signal.on(_I.REQUEST_JOIN_INFO,async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await vT(this,XI.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}));}),this.signal.on(_I.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage());}),this.signal.on(_I.REPORT_JOIN_GATEWAY,(e,t)=>{this.joinInfo&&(eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1);}),this.signal.on(_I.IS_P2P_DISCONNECTED,e=>{e(bT(this,XI.IS_P2P_DISCONNECTED));}),this.signal.on(_I.DISCONNECT_P2P,()=>{this.emit(XI.DISCONNECT_P2P);}),this.signal.on(_I.NEED_RENEW_SESSION,()=>{this.emit(XI.NEED_RENEW_SESSION);}),this.signal.on(_I.REQUEST_SUCCESS,()=>{this._signalTimeout=!1;}),this.signal.on(_I.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0;}),this.signal.on(_I.JOIN_RESPONSE,e=>{const t=this.getCurrentGatewayAddress();this.emit(XI.JOIN_RESPONSE,e,t);}),this.signal.on(_I.DATACHANNEL_PRECONNECT,async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return vT(this,XI.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i);}),this.signal.on(_I.DATACHANNEL_CONNECTING,async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await vT(this,XI.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}));}),this.signal.on(_I.DATACHANNEL_FAILBACK,()=>{jC.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(XI.DATACHANNEL_FAILBACK);});}async tryUnsubBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e;}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{stream_id:t.id},!0);}catch(e){throw jC.warning("unsubscribe datachannel warning",e),e;}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH,{stream_id:e,ortc:t},!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e;}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0);}catch(e){throw jC.warning("unpublish datastream warning: ",e),e;}}async tryMassUnsubBeforeResub(e){const t={users:e.map(e=>({stream_id:e.stream_id,stream_type:e.stream_type}))};try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,t,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e;}}async muteLocal(e,t){const i={action:e.find(e=>e.stream_type===JI.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e;}}async unmuteLocal(e,t){const i={action:e.find(e=>e.stream_type===JI.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e;}}async muteRemote(e,t){const i={action:e===av.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e;}}async unmuteRemote(e,t){const i={action:e===av.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e;}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e);}upload(e,t){this.signal.upload(e,t);}getSignalRTT(){return this.signal.rtt;}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(EI.RESTART_ICE,t,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e;}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,fT.P2P_FAILED);}getCurrentGatewayAddress(){var e;if(!RC("GATEWAY_WSS_ADDRESS"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0;}async setPublishAudioFilterEnabled(e){await this.signal.request(EI.SET_PARAMETER,{enablePublishAudioFilter:e});}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(ET.FALLBACK)),this.store.useDataChannel=!1,this.signal=new Jv(My(My({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(XI.RESET_SIGNAL,$I.websocket);}}let Vy=0,Fy=0;function By(e,t,i,n){return new cg((r,s)=>{t.timeout=t.timeout||RC("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),Vy+=$T(t.data)):i&&(t.data.size?Vy+=t.data.size:t.data instanceof FormData?Vy+=eS(t.data):Vy+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,sC.request(t).then(e=>{"string"==typeof e.data?Fy+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Fy+=e.data.byteLength:Fy+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data);}).catch(e=>{sC.isCancel(e)?s(new LI(Hg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new LI(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new LI(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new LI(Hg.NETWORK_ERROR,e.message));});});}/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function i(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0};};}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e;};var r,s=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var i=0;i<e.length;++i){var n=e[i];if(n&&n.Math==Math)return n;}throw Error("Cannot find global object");}(this);function o(e,t){if(t)e:{var i=s;e=e.split(".");for(var r=0;r<e.length-1;r++){var o=e[r];if(!(o in i))break e;i=i[o];}(t=t(r=i[e=e[e.length-1]]))!=r&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t});}}function a(e){return (e={next:e})[Symbol.iterator]=function(){return this;},e;}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:i(e)};}if(o("Symbol",function(e){function t(e,t){this.A=e,n(this,"description",{configurable:!0,writable:!0,value:t});}if(e)return e;t.prototype.toString=function(){return this.A;};var i="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n);};}),o("Symbol.iterator",function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<t.length;r++){var o=s[t[r]];"function"==typeof o&&"function"!=typeof o.prototype[e]&&n(o.prototype,e,{configurable:!0,writable:!0,value:function(){return a(i(this));}});}return e;}),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else {var d;e:{var l={};try{l.__proto__={a:!0},d=l.a;break e;}catch(e){}d=!1;}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e;}:null;}var u=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null;}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0;}function _(e,t){return e.h=3,{value:t};}function E(e){this.g=new h(),this.G=e;}function m(e,t,i,n){try{var r=t.call(e.g.j,i);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var s=r.value;}catch(t){return e.g.j=null,e.g.s(t),f(e);}return e.g.j=null,n.call(e.g,s),f(e);}function f(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1};}catch(t){e.g.v=void 0,e.g.s(t);}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return {value:t.return,done:!0};}return {value:void 0,done:!0};}function g(e){this.next=function(t){return e.o(t);},this.throw=function(t){return e.s(t);},this.return=function(t){return function(e,t){p(e.g);var i=e.g.j;return i?m(e,"return"in i?i.return:function(e){return {value:e,done:!0};},t,e.g.return):(e.g.return(t),f(e));}(e,t);},this[Symbol.iterator]=function(){return this;};}function T(e,t){return t=new g(new E(t)),u&&e.prototype&&u(t,e.prototype),t;}if(h.prototype.o=function(e){this.v=e;},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u;},h.prototype.return=function(e){this.l={return:e},this.h=this.u;},E.prototype.o=function(e){return p(this.g),this.g.j?m(this,this.g.j.next,e,this.g.o):(this.g.o(e),f(this));},E.prototype.s=function(e){return p(this.g),this.g.j?m(this,this.g.j.throw,e,this.g.o):(this.g.s(e),f(this));},o("Array.prototype.entries",function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var i=0,n=!1,r={next:function(){if(!n&&i<e.length){var r=i++;return {value:t(r,e[r]),done:!1};}return n=!0,{done:!0,value:void 0};}};return r[Symbol.iterator]=function(){return r;},r;}(this,function(e,t){return [e,t];});};}),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var S=function(e,t){for(var i=0;i<e.length;i++)t(e[i]);},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n");},C=function(e,t,i){return t instanceof Blob?(i=void 0!==i?String(i+""):"string"==typeof t.name?t.name:"blob",t.name===i&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],i)),[String(e),t]):[String(e),String(t)];},I=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.");},v="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,y=v.FormData,A=v.XMLHttpRequest&&v.XMLHttpRequest.prototype.send,b=v.Request&&v.fetch,w=v.navigator&&v.navigator.sendBeacon,O=v.Element&&v.Element.prototype,N=v.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in v&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"");}catch(e){v.File=function(e,t,i){return e=new Blob(e,i||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date())},toString:{value:function(){return "[object File]";}}}),N&&Object.defineProperty(e,N,{value:"File"}),e;};}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");},P=function(e){this.i=[];var t=this;e&&S(e.elements,function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var i=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];S(i,function(i){t.append(e.name,i);});}else "select-multiple"===e.type||"select-one"===e.type?S(e.options,function(i){!i.disabled&&i.selected&&t.append(e.name,i.value);}):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(i="textarea"===e.type?R(e.value):e.value,t.append(e.name,i));});};if((e=P.prototype).append=function(e,t,i){I(arguments,2),this.i.push(C(e,t,i));},e.delete=function(e){I(arguments,1);var t=[];e=String(e),S(this.i,function(i){i[0]!==e&&t.push(i);}),this.i=t;},e.entries=function e(){var t,i=this;return T(e,function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=_(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2;});},e.forEach=function(e,t){I(arguments,1);for(var i=c(this),n=i.next();!n.done;n=i.next()){var r=c(n.value);n=r.next().value,r=r.next().value,e.call(t,r,n,this);}},e.get=function(e){I(arguments,1);var t=this.i;e=String(e);for(var i=0;i<t.length;i++)if(t[i][0]===e)return t[i][1];return null;},e.getAll=function(e){I(arguments,1);var t=[];return e=String(e),S(this.i,function(i){i[0]===e&&t.push(i[1]);}),t;},e.has=function(e){I(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return !0;return !1;},e.keys=function e(){var t,i,n,r,s=this;return T(e,function(e){if(1==e.h&&(t=c(s),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,r=c(n),_(e,r.next().value));i=t.next(),e.h=2;});},e.set=function(e,t,i){I(arguments,2),e=String(e);var n=[],r=C(e,t,i),s=!0;S(this.i,function(t){t[0]===e?s&&(s=!n.push(r)):n.push(t);}),s&&n.push(r),this.i=n;},e.values=function e(){var t,i,n,r,s=this;return T(e,function(e){if(1==e.h&&(t=c(s),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,(r=c(n)).next(),_(e,r.next().value));i=t.next(),e.h=2;});},P.prototype._asNative=function(){for(var e=new y(),t=c(this),i=t.next();!i.done;i=t.next()){var n=c(i.value);i=n.next().value,n=n.next().value,e.append(i,n);}return e;},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach(function(e,n){return "string"==typeof e?t.push(i+D(R(n))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(i+D(R(n))+'"; filename="'+D(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n");}),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e});},P.prototype[Symbol.iterator]=function(){return this.entries();},P.prototype.toString=function(){return "[object FormData]";},O&&!O.matches&&(O.matches=O.matchesSelector||O.mozMatchesSelector||O.msMatchesSelector||O.oMatchesSelector||O.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return -1<t;}),N&&(P.prototype[N]="FormData"),A){var L=v.XMLHttpRequest.prototype.setRequestHeader;v.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0);},v.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),A.call(this,e)):A.call(this,e);};}b&&(v.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),b.call(this,e,t);}),w&&(v.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),w.call(this,e,t);}),v.FormData=P;}}();const jy=()=>{const e=RC("AREAS");0===e.length&&e.push(ev.GLOBAL);return BT(e).call(e,(e,t,i)=>{const n=Gy(t);return n?0===i?n:"".concat(e,",").concat(n):e;},"");},Gy=e=>e===ev.OVERSEA?"".concat(nv.ASIA,",").concat(nv.EUROPE,",").concat(nv.AFRICA,",").concat(nv.NORTH_AMERICA,",").concat(nv.SOUTH_AMERICA,",").concat(nv.OCEANIA):nv[e],Wy=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map(e=>{const i=rv[e],n=Object.keys(i);n&&n.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]));});}),t;},Hy={GLOBAL:{ASIA:[ev.CHINA,ev.JAPAN,ev.INDIA,ev.KOREA,ev.HKMC],EUROPE:[],NORTH_AMERICA:[ev.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Ky=Object.keys(Hy[ev.GLOBAL]),Yy=[ev.CHINA,ev.NORTH_AMERICA,ev.EUROPE,ev.ASIA,ev.JAPAN,ev.INDIA,ev.OCEANIA,ev.SOUTH_AMERICA,ev.AFRICA,ev.KOREA,ev.HKMC,ev.US],qy=function(e,t){let i=[];if(bn(e).call(e,ev.GLOBAL)){const s=[ev.GLOBAL,ev.OVERSEA],o=Object.keys(rv);if(t===ev.GLOBAL)throw new LI(Hg.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===ev.CHINA)i=[ev.OVERSEA];else if(r=t,bn(Ky).call(Ky,r)){const e=(n=t,Hy[ev.GLOBAL][n]||[]),r=[...s,t,...e];i=o.filter(e=>!bn(r).call(r,e));}else if(function(e){let t=!1;return Ky.forEach(i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=!0);}),t;}(t)){const e=function(e){let t;return Ky.forEach(i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=i);}),t;}(t),n=[...s,e,t];i=o.filter(e=>!bn(n).call(n,e));}else i=e;i=function(e){const t=[];return Yy.forEach(i=>{bn(e).call(e,i)&&t.push(i);}),t.concat(e.filter(e=>!bn(Yy).call(Yy,e)));}(i);}else i=e;var n,r;return i;};function zy(e){var t,i;if(!e&&bn(t=RC("AREAS")).call(t,ev.EXTENSIONS))return jC.debug("update area from ap : reset"),void Jy(tI,!0);if(!bn(i=RC("AREAS")).call(i,ev.GLOBAL)||!e)return;let n=rv.EXTENSIONS;n&&(n={CODE:Gy(ev.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},jC.debug("update area from ap success: ".concat(e,",config is "),n),SC("AREAS",[ev.EXTENSIONS],!0),Object.keys(n).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){SC(e,n[e][0]);}else SC(e,n[e]);}));}function Jy(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=eI.reportApiInvoke(null,{name:hT.SET_AREA,options:e,tag:pT.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!bn(iv).call(iv,e))throw new LI(Hg.INVALID_PARAMS,"invalid area code");}),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new LI(Hg.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?qy(r,i):r;}if(!t){if(CC.AREAS){const e=new LI(Hg.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void jC.warning("setArea is prohibited because of config-distribute");}if(bn(n).call(n,ev.GLOBAL)&&RC("AREAS")===ev.EXTENSIONS){const e=new LI(Hg.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void jC.warning("setArea is prohibited because of ap extensions");}}SC("AREAS",n,t);const r=Wy(n);Object.keys(r).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){SC(e,r[e][0]);}else SC(e,r[e]);}),jC.debug("set area success:",n.join(","));}catch(e){throw i.onError(e),e;}i.onSuccess();}function Xy(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Qy(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Xy(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Xy(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}let Zy=1;function $y(e,t,i,n,r){Zy+=1;const s={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:Zy,requestId:Zy,version:EC,cname:i.cname},o={service_name:t,json_body:JSON.stringify(s)};let a,c,d=e[0];return fS(async()=>{a=Date.now();const e=await By(d,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw jC.error(t.toString()),t;}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw jC.error(e.toString()),e;}if(!i.servers||0===i.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw jC.error(e.toString()),e;}const r=function(e,t){return {addressList:e.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(RC("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:e.workerToken,vid:e.vid};}(i,t);return RC("LIVE_STREAMING_ADDRESS")&&(r.addressList=RC("LIVE_STREAMING_ADDRESS")instanceof Array?RC("LIVE_STREAMING_ADDRESS"):[RC("LIVE_STREAMING_ADDRESS")]),Qy(Qy({},r),{},{responseTime:c});},(n,r)=>(eI.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1),(n,r)=>(eI.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==Hg.OPERATION_ABORTED&&n.code!==Hg.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0)),r);}let eA=1;function tA(e,t,i,n){let{url:r,areaCode:s}=e;const o=Date.now();let a;const[c,d]=oA(t,s,[dy.CHOOSE_SERVER]);let l=wT.networkState;return fS(async()=>{l&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),l=wT.networkState;const{data:e,headers:s}=await By(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a="1"===s.http3?1:-1,eI.reportResourceTiming(r,t.sid),nA(e,r,t,o,[dy.CHOOSE_SERVER],a);const d=Iy(e,dy.CHOOSE_SERVER);return rA(d),Ty(d,r);},e=>(e&&eI.joinChooseServer(t.sid,{lts:o,succ:!0,csAddr:r,opid:d,serverList:e.gatewayAddrs.map(e=>e.address),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),isHttp3:a}),!1),e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinChooseServer(t.sid,{lts:o,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:l}),isHttp3:a}),jC.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0)),n);}function iA(e,t,i,n){let r,{url:s,areaCode:o,serviceIds:a}=e;const c=Date.now(),[d,l]=oA(t,o,a);let u;return fS(async()=>{u&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),u=wT.networkState;const{data:e,headers:o}=await By(s,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===o.http3?1:-1,eI.reportResourceTiming(s,t.sid),nA(e,s,t,c,a,r);const l=Iy(e,dy.CHOOSE_SERVER),h=Iy(e,"proxy5"===t.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK);return rA(l),{gatewayInfo:Ty(l,s),proxyInfo:h,url:s};},e=>(e.gatewayInfo&&eI.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:s,serverList:e.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,opid:l,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&eI.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:s,turnServerAddrList:e.proxyInfo.addresses.map(e=>e.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1),e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:s,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:u})}),jC.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),n);}const nA=(e,t,i,n,r,s)=>{const o=[],a=o=>{4096===o.flag?eI.joinChooseServer(i.sid,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:o.error.message,csIp:o.error.data&&o.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:s}):1048576!==o.flag&&4194304!==o.flag&&4194310!==o.flag||eI.joinWebProxyAP(i.sid,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:o.error.code,eventType:i.cloudProxyServer,unilbsServerIds:r.toString()});};if(e.response_body.forEach(t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)jC.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else {const i={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};o.push(i),a(i);}if(0!==i){const n=Pv(i),r={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?jC.warning(r.error.toString()):o.push(r),a(r);}}),o.length)throw jC.warning("[".concat(i.clientId,"] multi unilbs ").concat(t," failed, ").concat(o.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry)).join(" | "))),new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,o.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!o.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(o.map(e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc;}).filter(e=>!!e))]});},rA=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});RC("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?zy(e.detail[23].toLowerCase()):zy());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){var s;const n=Ey(s=i[t]).call(s);e.addresses[t]&&i&&(e.addresses[t].fingerprint=n);}}if(RC("GATEWAY_ADDRESS")&&RC("GATEWAY_ADDRESS").length>0){jC.debug("assign gateway address to",RC("GATEWAY_ADDRESS"));const t=RC("GATEWAY_ADDRESS").map(t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find(e=>e.ip===t.ip&&e.port===t.port))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return {ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r};});e.addresses=t;}},sA=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=Pv(t.buffer.code);throw new LI(Hg.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry});}return t.buffer.ticket;}throw jC.debug("update ticket request received ap response without response body:",t),new LI(Hg.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1});},oA=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:Qy({6:e.stringUid,11:t,12:RC("USE_NEW_TOKEN")?"1":void 0,22:t},e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};r.request_bodies.forEach(t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}));});const s=new FormData();return s.append("request",JSON.stringify(r)),[s,n];},aA=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map(e=>({ip:e.ip,port:e.port}))}}]},r=new FormData();return r.append("request",JSON.stringify(n)),[r,i];};let cA=0;function dA(e){return cg.all(e.map(e=>e.then(e=>{throw e;},e=>e))).then(e=>{throw e;},e=>e);}const lA=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:s}=e,o=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=o*a,t=e+a;return i.slice(e,t).map(n);})();s&&s.push(...e);try{c=await dA(e);}catch(e){if(d+=a,o++,!(d>=i.length))return void(await l());r(e);}e.forEach(e=>e.cancel());};return await l(),c;};async function uA(e,t,i,n){const r=async function(e,t,i,n){let r=null;const s=[],o=async()=>{const r=RC("WEBCS_DOMAIN").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:jy()})),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),a=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0];},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),a;},a=async()=>{if(await iS(1e3),null!==r)return r;const o=RC("WEBCS_DOMAIN_BACKUP_LIST").map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:jy()})),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map(e=>e.url)}),c=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0];},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c;};try{return r=await dA([o(),a()]),s.length&&s.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),r;}catch(e){throw e[0];}}(e,t,i,n);return {gatewayInfo:await r};}async function hA(e,t,i,n,r){const s=e.cloudProxyServer;if("disabled"===s){if(!n)return;if(e.useLocalAccessPoint)return await uA(e,t,i,r);if(RC("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:s}=await EA(e,t,i,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return {gatewayInfo:n};const a=s.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:!1,security:!0}));if(r.useP2P){var o;const t=null!==(o=e.uid)&&void 0!==o?o:n.uid,i="glb:".concat(t.toString()),r=await cT(i),c=s.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:i,password:r,forceturn:!1,security:!0}));a.push(...c);}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:n};}return await uA(e,t,i,r);}const{proxyInfo:a,gatewayInfo:c}=await EA(e,t,i,r),d={gatewayInfo:c},l=a.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:iI.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:"proxy4"!==s,security:"proxy5"===s}));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i="glb:".concat(t.toString()),n=await cT(i),r=a.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport||iI.tcpport,udpport:"proxy4"===s?void 0:e.udpport||iI.udpport,username:i,password:n,forceturn:"proxy4"!==s,security:"proxy5"===s}));l.push(...r);}return e.turnServer={mode:"manual",servers:l},jC.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),d;}async function pA(e,t,i,n,r){const s=RC("ACCOUNT_REGISTER").slice(0,RC("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?s.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):s.map(e=>"https://".concat(e,"/api/v1"));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const s=await async function(e,t,i,n,r){const s=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await fS(()=>By(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw jC.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:Hg.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new LI(Hg.INVALID_UINT_UID_FROM_STRING_UID);return eI.reqUserAccount(o.sid,{lts:s,success:!0,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:null,extend:o}),!1;}const r=Pv(i.code);return r.retry&&(a=e[(n+1)%e.length]),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:r.desc,extend:o}),r.retry;},(t,i)=>t.code!==Hg.OPERATION_ABORTED&&(eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),a=e[(i+1)%e.length],!0),r);if(0!==c.code){const e=Pv(c.code);throw new LI(Hg.UNEXPECTED_RESPONSE,e.desc);}return c;}(o,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),s.uid;}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e;}}async function _A(e,t,i){const n=RC("CDS_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config")),r=n.map(n=>function(e,t,i,n){const r=Sg(),s={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:EC,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return fS(()=>By(e,{data:s,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==Hg.OPERATION_ABORTED,n);}(n,e,t,i));let s=null,o=null,a={};try{s=await dA(r);}catch(e){if(e.code===Hg.OPERATION_ABORTED)throw e;o=e;}r.forEach(e=>e.cancel());if(eI.reportApiInvoke(e.sid,{name:hT.REQUEST_CONFIG_DISTRIBUTE,options:{error:o,res:s}}).onSuccess(),s&&s.test_tags)try{a=function(e){if(!e.test_tags)return {};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach(e=>{var i;const r=Ey(i=e.slice(4)).call(i),s=JSON.parse(t[e])[1];n[r]=s;}),n;}(s);}catch(e){}return a;}async function EA(e,t,i,n){const r=RC("PROXY_SERVER_TYPE3"),s=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),"https://".concat(n,"/ap/?url=").concat(e);};let o=null;const a=[],c=async()=>{const r=RC("WEBCS_DOMAIN").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]};}),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),c=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0];},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),c;},d=async()=>{if(await iS(1e3),null!==o)return o;const r=RC("WEBCS_DOMAIN_BACKUP_LIST").map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]};}),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),d=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0];},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d;};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await dA([c(),d()]));}catch(e){throw e[0];}if(a.length&&a.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),!l||!u)throw new LI(Hg.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];bn(r).call(r,t)&&(e.proxyServer=t,jC.setProxyServer(t),eI.setProxyServer(t));}return o={gatewayInfo:l,proxyInfo:await vy(u,l.uid)},o;}async function mA(e,t,i,n){const r=RC("UAP_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"));return await $y(r,e,t,i,n);}async function fA(e,t,i){const n=RC("UAP_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap")),r=n.map(n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:EC,cname:t.cname,uid:t.uid.toString(),requestId:eA,seq:eA};eA+=1;const s={service_name:"tele_channel",json_body:JSON.stringify(r)};return fS(async()=>{const t=await By(e,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw jC.error(e.toString()),e;}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw jC.error(e.toString()),e;}if(!n.servers||0===n.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw jC.error(e.toString()),e;}return {vid:n.vid,workerToken:n.workerToken,addressList:(RC("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(RC("WORKER_DOMAIN"),":").concat(e.wss))};},void 0,e=>!!(e.code!==Hg.OPERATION_ABORTED&&e.code!==Hg.UNEXPECTED_RESPONSE||e.data&&e.data.retry),n);}(n,e,t,i));try{const e=await dA(r);return r.forEach(e=>e.cancel()),e;}catch(e){throw e[0];}}async function gA(e,t,i){let n=null;const r=[],s=async s=>{const o=RC(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"));return s&&(await iS(1e3),null!==n)?n:await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=aA(t,[dy.CHOOSE_SERVER]);let s=wT.networkState;return fS(async()=>{s&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),s=wT.networkState;const t=await By(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return sA(t,e);},()=>!1,e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.UPDATE_TICKET_FAILED?e.data.retry:(jC.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0)),n);}(n,e,t,i)),allFailedhandler:e=>{throw e[0];},promisesCollector:r});};try{return n=await dA([s(!1),s(!0)]),r.length&&r.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),n;}catch(e){throw e[0];}}function TA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function SA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?TA(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):TA(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class RA extends dT{get isSuccess(){return !!this.configs;}constructor(){super(),sh(this,"configs",void 0),sh(this,"joinInfo",void 0),sh(this,"cancelToken",void 0),sh(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),sh(this,"interval",void 0),sh(this,"mutex",new pS("config-distribute")),sh(this,"mutableParamsRead",!1);}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),RC("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute();},RC("CONFIG_DISTRIBUTE_INTERVAL")));}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0;}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())();}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;eI.reportApiInvoke(null,{options:void 0,name:hT.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:pT.TRACER}).onSuccess(JSON.stringify(CC));}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void jC.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await _A(this.joinInfo,this.cancelToken,this.retryConfig),jC.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e;}catch(e){const t=new LI(Hg.NETWORK_RESPONSE_ERROR,e);jC.warning("[config-distribute] ".concat(t.toString()));}finally{t();}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0;}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(sv.UPDATE_BITRATE_LIMIT,e):this.emit(sv.UPDATE_BITRATE_LIMIT,e));}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&SA({},this.configs.limit_bitrate.low_stream_uplink);}cacheGlobalParameterConfig(e){var t;const i=ep(t=Object.keys(e).filter(e=>/^webrtc_ng_global_parameter/.test(e))).call(t);for(let t=0;t<i.length;t++)for(let n=i.length-1;n>t;n--){const t=i[n];if("number"==typeof e[t].__priority){const r=e[t].__priority,s=i[n-1];if("number"==typeof e[s].__priority){if(!(r>e[s].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e;}}else {const e=t;i[n]=i[n-1],i[n-1]=e;}}}const n={};i.forEach(t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach(e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=SA({value:i[e]},r&&{expires:r}));});});try{!function(e){try{const t=Date.now();Object.keys(e).forEach(i=>{switch(i){case"ENABLE_EVENT_REPORT":case"UPLOAD_LOG":if(Object.prototype.hasOwnProperty.call(TC,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;CC[i]=n,TC[i]=n,jC.debug("Update global parameters from config distribute",i,n);}}});}catch(t){jC.error("Error update config immediately: ".concat(e),t.message);}}(n);const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),jC.debug("Caching global parameters ".concat(e));}catch(e){jC.error("Error caching global parameters:",e.message);}}}const CA={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1};function IA(){return CA;}var vA;function yA(e,t,i){return {sampleRate:e,stereo:t,bitrate:i};}function AA(e,t,i,n,r){return {width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r};}function bA(e,t,i,n,r){return {width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r};}function wA(e,t){return {numSpatialLayers:e,numTemporalLayers:t};}!function(e){e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change";}(vA||(vA={}));const OA={"90p":AA(160,90),"90p_1":AA(160,90),"120p":AA(160,120,15,30,65),"120p_1":AA(160,120,15,30,65),"120p_3":AA(120,120,15,30,50),"120p_4":AA(212,120),"180p":AA(320,180,15,30,140),"180p_1":AA(320,180,15,30,140),"180p_3":AA(180,180,15,30,100),"180p_4":AA(240,180,15,30,120),"240p":AA(320,240,15,40,200),"240p_1":AA(320,240,15,40,200),"240p_3":AA(240,240,15,40,140),"240p_4":AA(424,240,15,40,220),"360p":AA(640,360,15,80,400),"360p_1":AA(640,360,15,80,400),"360p_3":AA(360,360,15,80,260),"360p_4":AA(640,360,30,80,600),"360p_6":AA(360,360,30,80,400),"360p_7":AA(480,360,15,80,320),"360p_8":AA(480,360,30,80,490),"360p_9":AA(640,360,15,80,800),"360p_10":AA(640,360,24,80,800),"360p_11":AA(640,360,24,80,1e3),"480p":AA(640,480,15,100,500),"480p_1":AA(640,480,15,100,500),"480p_2":AA(640,480,30,100,1e3),"480p_3":AA(480,480,15,100,400),"480p_4":AA(640,480,30,100,750),"480p_6":AA(480,480,30,100,600),"480p_8":AA(848,480,15,100,610),"480p_9":AA(848,480,30,100,930),"480p_10":AA(640,480,10,100,400),"720p":AA(1280,720,15,120,1130),"720p_auto":AA(1280,720,30,900,3e3),"720p_1":AA(1280,720,15,120,1130),"720p_2":AA(1280,720,30,120,2e3),"720p_3":AA(1280,720,30,120,1710),"720p_5":AA(960,720,15,120,910),"720p_6":AA(960,720,30,120,1380),"1080p":AA(1920,1080,15,120,2080),"1080p_1":AA(1920,1080,15,120,2080),"1080p_2":AA(1920,1080,30,120,3e3),"1080p_3":AA(1920,1080,30,120,3150),"1080p_5":AA(1920,1080,60,120,4780),"1440p":AA(2560,1440,30,120,4850),"1440p_1":AA(2560,1440,30,120,4850),"1440p_2":AA(2560,1440,60,120,7350),"4k":AA(3840,2160,30,120,8910),"4k_1":AA(3840,2160,30,120,8910),"4k_3":AA(3840,2160,60,120,13500)},NA=[{scaleResolutionDownBy:2,width:1280,height:720,frameRate:30,bitrateMin:300,bitrateMax:900},{scaleResolutionDownBy:1.333333,width:1280,height:720,frameRate:30,bitrateMin:600,bitrateMax:2e3},{scaleResolutionDownBy:1,width:1280,height:720,frameRate:30,bitrateMin:900,bitrateMax:3e3}],DA={"480p":bA(640,480,5),"480p_1":bA(640,480,5),"480p_2":bA(640,480,30),"480p_3":bA(640,480,15),"720p":bA(1280,720,5),"720p_auto":AA(1280,720,30,900,3e3),"720p_1":bA(1280,720,5),"720p_2":bA(1280,720,30),"720p_3":bA(1280,720,15),"1080p":bA(1920,1080,5),"1080p_1":bA(1920,1080,5),"1080p_2":bA(1920,1080,30),"1080p_3":bA(1920,1080,15)},PA={"1SL1TL":wA(1,1),"3SL3TL":wA(3,3),"2SL3TL":wA(2,3)};function LA(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},OA[e]):e;}function kA(e){return "string"==typeof e?Object.assign({},DA[e]):e;}function MA(e){return "string"==typeof e?Object.assign({},PA[e]):e;}const UA={speech_low_quality:yA(16e3,!1),speech_standard:yA(32e3,!1,18),music_standard:yA(48e3,!1),standard_stereo:yA(48e3,!0,56),high_quality:yA(48e3,!1,128),high_quality_stereo:yA(48e3,!0,192)};function xA(e){return "string"==typeof e?Object.assign({},UA[e]):e;}const VA=[];function FA(e){return qg(e,"mediaSource",["screen","window","application"]),!0;}var BA,jA,GA,WA,HA,KA,YA,qA,zA,JA;!function(e){e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track";}(BA||(BA={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream";}(jA||(jA={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM";}(GA||(GA={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM";}(WA||(WA={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY";}(HA||(HA={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received";}(KA||(KA={})),function(e){e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed";}(YA||(YA={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed";}(qA||(qA={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source";}(zA||(zA={})),function(e){e.UPDATE_TRACK_SOURCE="update-track-source";}(JA||(JA={}));const XA={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},QA={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},ZA={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},$A={uplinkNetworkQuality:0,downlinkNetworkQuality:0},eb={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var tb,ib,nb,rb,sb,ob;!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node";}(tb||(tb={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints";}(ib||(ib={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND";}(nb||(nb={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged";}(rb||(rb={})),function(e){e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata";}(sb||(sb={})),function(e){e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen";}(ob||(ob={}));const ab={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};var cb;!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error";}(cb||(cb={}));class db extends dT{constructor(e,t){super(),sh(this,"_ID",void 0),sh(this,"_rtpTransceiver",void 0),sh(this,"_lowRtpTransceiver",void 0),sh(this,"_hints",[]),sh(this,"_isClosed",!1),sh(this,"_originMediaStreamTrack",void 0),sh(this,"_mediaStreamTrack",void 0),sh(this,"_external",{}),this._ID=t||nS(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){bn(VA).call(VA,e)||VA.push(e);}(this);}toString(){return this._ID;}getTrackId(){return this._ID;}getMediaStreamTrack(e){if(!e){const e=eI.reportApiInvoke(null,{name:hT.GET_MEDIA_STREAM_TRACK,options:[],tag:pT.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("");}return this._mediaStreamTrack;}getRTCRtpTransceiver(e){return e===GA.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver;}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings();}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=VA.indexOf(e);-1!==t&&VA.splice(t,1);}(this),this.emit(YA.CLOSED),this.removeAllListeners(KA.SEI_RECEIVED);}_updateRtpTransceiver(e,t){if(t===GA.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e;}else {if(this._rtpTransceiver===e)return;this._rtpTransceiver=e;}this.emit(KA.TRANSCEIVER_UPDATED,e,t);}}class lb extends db{get isExternalTrack(){return this._isExternalTrack;}get muted(){return this._muted;}get enabled(){return this._enabled;}get processorContext(){return this._processorContext;}constructor(e,t){super(e,t),sh(this,"_enabled",!0),sh(this,"_muted",!1),sh(this,"_isExternalTrack",!1),sh(this,"_isClosed",!1),sh(this,"_enabledMutex",void 0),sh(this,"processor",void 0),sh(this,"_handleTrackEnded",()=>{this.onTrackEnded();}),this._enabledMutex=new pS("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded);}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:"";}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,jC.debug("[".concat(this.getTrackId(),"] close")),this.emit(BA.NEED_CLOSE),super.close());}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}));}_getDefaultPlayerConfig(){return {};}onTrackEnded(){jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}stateCheck(e,t){if(jC.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Yg(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",jC);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",jC);}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[];}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():cg.resolve([]);}}function ub(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const hb=window.AudioContext||window.webkitAudioContext;let pb=null;const _b=new class extends dT{constructor(){super(...arguments),sh(this,"prevState",void 0),sh(this,"curState",void 0),sh(this,"currentTime",void 0),sh(this,"currentTimeStuckAt",void 0),sh(this,"interruptDetectorTrack",void 0),sh(this,"onLocalAudioTrackMute",()=>{jC.info("ios15-interruption-start"),this.emit(vA.IOS_15_16_INTERRUPTION_START);}),sh(this,"onLocalAudioTrackUnmute",async()=>{jC.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?jC.info("ios15-interruption-end-canceled"):(pb&&(await pb.suspend()),this.emit(vA.IOS_15_16_INTERRUPTION_END));});}get duringInterruption(){return "running"===this.prevState&&"interrupted"===this.curState;}bindInterruptDetectorTrack(e){jC.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute);}unbindInterruptDetectorTrack(e){jC.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0);}}();function Eb(){if(!hb)return void jC.error("your browser is not support web audio");jC.info("create audio context");const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ub(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ub(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({},RC("WEBAUDIO_INIT_OPTIONS"));jC.debug("audio context init option:",JSON.stringify(e)),pb=new hb(e),_b.curState=pb.state,pb.onstatechange=()=>{_b.prevState=_b.curState,_b.curState=pb?pb.state:void 0;const{prevState:e,curState:t}=_b,i="running"===t,n="interrupted"===t,r="running"===e,s="suspended"===e,o="interrupted"===e,a=Sg().osVersion;(Og()||Vg())&&r&&n&&(jC.info("ios".concat(a,"-interruption-start")),_b.emit(vA.IOS_INTERRUPTION_START)),(Og()||Vg())&&(s||o)&&i&&(jC.info("ios".concat(a,"-interruption-end")),_b.emit(vA.IOS_INTERRUPTION_END)),e!==t&&_b.emit(vA.STATE_CHANGE,t,e);},setInterval(()=>{var e;const t=null===(e=pb)||void 0===e?void 0:e.currentTime;if(_b.currentTime!==t)_b.currentTimeStuckAt&&(jC.debug("AudioContext current time resume at ".concat(t)),_b.currentTimeStuckAt=void 0),_b.currentTime=t;else {if(t!==_b.currentTimeStuckAt){eI.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:pT.TRACER}).onSuccess(),jC.warning("AudioContext current time stuck at ".concat(t));}_b.currentTimeStuckAt=t;}},5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,s=!1;function o(t){"running"===e.state?a(!1):Og()||Vg()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d));}function a(e){if(n!==e){n=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0});}}}function c(){o(!0);}function d(){o(!1);}function l(){o(!0);}function u(e){if(!s)if(i.paused){if(e){let e;h(!1),s=!0;try{e=i.play(),e?e.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p));}catch(e){p();}}else h(!0);}else h(!1);}function h(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0});}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),s=!1,u(!1);}function _(){u(!0);}if(Og()){const t=e.createMediaStreamDestination(),n=document.createElement("div");n.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,u(!0);}_b.on(vA.STATE_CHANGE,c),o(!1);}(pb);}function mb(){if(!pb){if(Eb(),!pb)throw new Kg(Hg.NOT_SUPPORTED,"can not create audio context");return pb;}return pb;}function fb(e){if(function(){if(null!==gb)return gb;const e=mb(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i);}catch(e){r=!0;}return t.disconnect(),gb=r,r;}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var s;return e._inputNodes||(e._inputNodes=[]),bn(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e;},e.disconnect=(n,r,s)=>{i.call(e),n?WT(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i);};}let gb=null;function Tb(e,t){let i=!1;const n=1/t;if(RC("DISABLE_WEBAUDIO")){const t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3);},1e3*n);}else {const t=mb();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const s=()=>{if(i)return void(r=null);const o=t.createOscillator();o.onended=s,o.connect(r),o.start(0),o.stop(t.currentTime+n),e(t.currentTime);};s();}return ()=>{i=!0;};}class Sb{constructor(){sh(this,"context",void 0),sh(this,"analyserNode",void 0),sh(this,"sourceNode",void 0),this.context=mb(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4;}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode);}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode);}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||Og()||Vg()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else {const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1;}const t=BT(e).call(e,(e,t)=>e+t*t,0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100;}getAnalyserNode(){return this.analyserNode;}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode);}catch(e){jC.warning("rebuild analyser node failed.");}}destroy(){this.updateSource(void 0);}}class Rb extends dT{get processSourceNode(){return this.sourceNode;}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode);}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect();}}get processedNode(){return this._processedNode;}constructor(){super(),sh(this,"outputNode",void 0),sh(this,"outputTrack",void 0),sh(this,"isPlayed",!1),sh(this,"context",void 0),sh(this,"audioBufferNode",void 0),sh(this,"destNode",void 0),sh(this,"audioOutputLevel",0),sh(this,"volumeLevelAnalyser",void 0),sh(this,"_processedNode",void 0),sh(this,"playNode",void 0),sh(this,"isDestroyed",!1),sh(this,"onNoAudioInput",void 0),sh(this,"isNoAudioInput",!1),sh(this,"_noAudioInputCount",0),this.context=mb(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),fb(this.outputNode),this.volumeLevelAnalyser=new Sb();}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(zA.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0;}return e.inputBuffer;}(e));});}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0);}createOutputTrack(){if(!IA().webAudioMediaStreamDest)throw new Kg(Hg.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack;}play(e){"running"!==this.context.state&&KT(()=>{_b.emit("autoplay-failed");}),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode);}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode);}catch(e){}this.isPlayed=!1;}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel();}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Og()||Vg()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await iS(200),(await this.checkHasAudioInput(e?e+1:1))&&n);}getAudioVolume(){return this.outputNode.gain.value;}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime);}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0;}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect();}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode);}}class Cb extends Rb{get isFreeze(){return !1;}constructor(e,t,i){var n;if(super(),sh(this,"sourceNode",void 0),sh(this,"track",void 0),sh(this,"clonedTrack",void 0),sh(this,"audioElement",void 0),sh(this,"isCurrentTrackCloned",!1),sh(this,"isRemoteTrack",!1),sh(this,"originVolumeLevelAnalyser",void 0),sh(this,"rebuildWebAudio",async()=>{if(jC.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&(await this.checkHasAudioInput()),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void jC.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>jC.info("resume success")),jC.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),fb(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput();}),"audio"!==e.kind)throw new Kg(Hg.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),fb(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,jC.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));fb(t),this.originVolumeLevelAnalyser=new Sb(),this.originVolumeLevelAnalyser.updateSource(t);}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const s=Sg();t&&s.os===_g.IOS&&Number(null===(n=s.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(_b.on(vA.STATE_CHANGE,()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio();}),this.checkHasAudioInput().then(e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0);}));}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.audioElement.srcObject=t;}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),_b.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy();}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]));}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),jC.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));fb(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i);}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel();}}async function Ib(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r);}async function vb(e,t){const i=await yb(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new cg((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const s=document.createElement("div");s.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e);};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked;},u.appendChild(e),u.appendChild(t);}c.appendChild(u),c.appendChild(d),s.appendChild(o),s.appendChild(a),s.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(s),document.body.appendChild(h),e.map(e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}));}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e;}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,function(e){return "&#"+e.charCodeAt(0)+";";})+"</span>",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l});},a.appendChild(t);}});});}(i,t);return await Ib(n,e,r);}async function yb(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=uT();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new Kg(Hg.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t});}catch(e){n=null;}n&&n.then||(n=new cg((e,n)=>{i.desktopCapturer.getSources({types:t},(t,i)=>{t?n(t):e(i);});}));try{return await n;}catch(e){throw new Kg(Hg.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString());}}function Ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const bb=new pS("safari");let wb=!1,Ob=!1;async function Nb(e,t){let i=0,n=null;for(;i<2;)try{n=await Db(e,t,i>0);break;}catch(e){if(e instanceof Kg)throw jC.error("[".concat(t,"] ").concat(e.toString())),e;const n=Pb(e.name||e.code||e,e.message);if(n.code===Hg.MEDIA_OPTION_INVALID){jC.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await iS(500);continue;}throw jC.error("[".concat(t,"] ").concat(n.toString())),n;}if(!n)throw new Kg(Hg.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n;}async function Db(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Kg(Hg.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=IA(),r=new MediaStream();if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return jC.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(uT()){if(e.screen.sourceId){Lb(r,await Ib(e.screen.sourceId,e.screen,e.screenAudio));}else {Lb(r,await vb(e.screen,e.screenAudio));}}else if(Ag()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new Kg(Hg.NOT_SUPPORTED,"This browser does not support screen sharing");jC.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(o=e.screen.extensionId,a=t,new cg((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},i=>{if(!i||!i.streamId)return jC.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new Kg(Hg.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId);});}catch(e){jC.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(o,")"),e.toString()),t(new Kg(Hg.CHROME_PLUGIN_NOT_INSTALL));}}));e.screen.mandatory.chromeMediaSourceId=i;Lb(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}));}else if(n.getDisplayMedia){var s;e.screen.mediaSource&&FA(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(s=e.screen.displaySurface)&&void 0!==s?s:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};!n&&delete c.selfBrowserSurface,!o&&delete c.surfaceSwitching,!a&&delete c.systemAudio,jC.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));const d=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ab(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ab(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({video:i,audio:!!e.screenAudio},c));Lb(r,d);}else {if(!wg())throw jC.error("[".concat(t,"] This browser does not support screenSharing")),new Kg(Hg.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&FA(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};jC.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i)));Lb(r,await navigator.mediaDevices.getUserMedia(i));}}var o,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=RC("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=dS(c,d);}catch(e){}jC.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),Sg();let l,u=null;(bg()||Og()||Ig())&&(u=await bb.lock());try{l=await navigator.mediaDevices.getUserMedia(c);}catch(e){throw u&&u(),e;}return c.audio&&(wb=!0),c.video&&(Ob=!0),Lb(r,l),u&&u(),r;}function Pb(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new Kg(Hg.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new Kg(Hg.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new Kg(Hg.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new Kg(Hg.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new Kg(Hg.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new Kg(Hg.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return jC.error("getUserMedia unexpected error",e),new Kg(Hg.UNEXPECTED_ERROR,"".concat(e,": ").concat(t));}}function Lb(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],s=t.getAudioTracks()[0];s&&(n&&e.removeTrack(n),e.addTrack(s)),r&&(i&&e.removeTrack(i),e.addTrack(r));}const kb=new class extends dT{get state(){return this._state;}set state(e){e!==this._state&&(this.emit(rb.STATE_CHANGE,e),this._state=e);}constructor(){super(),sh(this,"_state",nb.IDLE),sh(this,"isAccessMicrophonePermission",!1),sh(this,"isAccessCameraPermission",!1),sh(this,"lastAccessMicrophonePermission",!1),sh(this,"lastAccessCameraPermission",!1),sh(this,"checkdeviceMatched",!1),sh(this,"deviceInfoMap",new Map()),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(RC("ENUMERATE_DEVICES_INTERVAL")||(Gg()||Rg()===_g.HARMONY_OS)&&jg())&&this.updateDevicesInfo();},RC("ENUMERATE_DEVICES_INTERVAL_TIME"));}).catch(e=>jC.error(e.toString()));}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new Kg(Hg.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();}const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let s=!this.isAccessMicrophonePermission&&e,o=!this.isAccessCameraPermission&&t;r.audio&&(s=!1),r.video&&(o=!1);let a=null,c=null,d=null;if(!i&&(s||o)){if(bb.isLocked){jC.debug("[device manager] wait GUM lock");(await bb.lock())(),jC.debug("[device manager] GUM unlock");}if(wb&&(s=!1,this.isAccessMicrophonePermission=!0),Ob&&(o=!1,this.isAccessCameraPermission=!0),jC.debug("[device manager] check media device permissions",e,t,s,o),s&&o){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0;}else if(s){try{a=await navigator.mediaDevices.getUserMedia({audio:e});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessMicrophonePermission=!0;}else if(o){try{c=await navigator.mediaDevices.getUserMedia({video:t});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessCameraPermission=!0;}jC.debug("[device manager] mic permission",e,"cam permission",t);}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null,e;}catch(e){a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null;return new Kg(Hg.ENUMERATE_DEVICES_FAILED,e.toString()).throw();}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!0,!1,e)).filter(e=>"audioinput"===e.kind);}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!1,!0,e)).filter(e=>"videoinput"===e.kind);}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!0,!1,e)).filter(e=>"audiooutput"===e.kind);}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach(i=>{i.device.label===e&&(t=i.device.deviceId);}),t;}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find(t=>t.deviceId===e);if(!t)throw new Kg(Hg.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t;}async init(){this.state=nb.INITING;try{await this.updateDevicesInfo(),this.state=nb.INITEND;}catch(e){if(jC.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=nb.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)){new Kg(Hg.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw();}throw e;}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find(e=>"audioinput"===e.kind&&"default"===e.deviceId),i=e.find(e=>"audiooutput"===e.kind&&"default"===e.deviceId);t&&i?i.groupId===t.groupId?jC.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):jC.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):jC.debug("[device-check] default input or output not found");}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach(e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n);}n&&(n.updateAt=t);}),this.deviceInfoMap.forEach((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e));}),this.state!==nb.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach(e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(rb.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.PLAYOUT_DEVICE_CHANGED,e);}}),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0);}checkMediaDeviceInfoIsOk(e){const t=e.filter(e=>"audioinput"===e.kind),i=e.filter(e=>"videoinput"===e.kind),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break;}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break;}return n;}}();let Mb=!1;const Ub=new class extends dT{constructor(){super(...arguments),sh(this,"onAutoplayFailed",void 0),sh(this,"onAudioAutoplayFailed",void 0);}}();function xb(){if(Sg(),!Mb){const e=t=>{t.preventDefault(),Mb=!1,Wg()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0));};Mb=!0,Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),jC.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Ub.onAutoplayFailed?Ub.onAutoplayFailed():Ub.onAudioAutoplayFailed?jC.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):jC.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Ub.emit("autoplay-failed");}}function Vb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Fb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Vb(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Vb(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function Bb(e,t,i,n){if(!e)return;const r=eI.getBaseInfoBySessionId(e);if(!r)return;const s=r.info,o=Date.now(),a=Fb(Fb({},s),{},{vid:void 0===s.vid?0:Number(s.vid),lts:o,elapse:o-r.startTime,cbRegistered:Ub.onAutoplayFailed||Ub.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});eI.send({type:qC.AUTOPLAY_FAILED,data:a},!0);}const jb=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],Gb=new class{constructor(){sh(this,"onAutoplayFailed",void 0),sh(this,"elementMap",new Map()),sh(this,"elementStateMap",new Map()),sh(this,"elementsNeedToResume",[]),sh(this,"sinkIdMap",new Map()),sh(this,"autoResumeAfterInterruption",e=>{Array.from(this.elementMap.entries()).forEach(t=>{let[i,n]=t;const r=this.elementStateMap.get(i),s=n.srcObject.getAudioTracks()[0],o=s&&s.readyState;if(jC.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(o," ").concat(e)),"live"===o){if(e)return n.pause(),void n.play();if("running"===_b.curState)return Mg()?(n.pause(),void n.play()):void(r&&"paused"===r&&n.play());}});}),sh(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(jC.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play());});}),this.autoResumeAudioElement(),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),_b.on(vA.STATE_CHANGE,()=>{Og()&&"suspended"===_b.prevState&&"running"===_b.curState&&this.autoResumeAfterInterruption();});}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t);}catch(e){throw new Kg(Hg.PERMISSION_DENIED,"can not set sink id: "+e.toString());}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,sb.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{r.setSinkId(s).catch(e=>{jC.warning("[".concat(t,"] set sink id failed"),e.toString());});}catch(e){jC.warning("[".concat(t,"] set sink id failed"),e.toString());}const o=r.play();o&&o.then&&o.catch(e=>{n&&Bb(n,"audio",e.message,t),jC.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(jC.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),KT(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),xb();}));});}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]));}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e);}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100);}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e);}bindAudioElementEvents(e,t){jb.forEach(i=>{t.addEventListener(i,i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(jC.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&jC.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message));}this.elementStateMap.set(e,r);});});}getPlayerState(e){return this.elementStateMap.get(e)||"uninit";}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach(e=>{e.play().then(e=>{jC.debug("Auto resume audio element success");}).catch(e=>{jC.warning("Auto resume audio element failed!",e);});}),this.elementsNeedToResume=[];};new cg(e=>{document.body?e():window.addEventListener("load",()=>e());}).then(()=>{Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0));});}}();function Wb(){return function(e,t,i){const n=i.value;return "function"==typeof n&&(i.value=function(){this._isClosed&&new Kg(Hg.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",jC);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof cg?new cg((e,t)=>{r.then(e).catch(t);}):r;}),i;};}function Hb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Kb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Hb(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Hb(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class Yb extends dT{constructor(e){super(),sh(this,"name","VideoProcessorDestination"),sh(this,"ID","0"),sh(this,"_source",void 0),sh(this,"videoContext",void 0),sh(this,"inputTrack",void 0),this.videoContext=e;}get kind(){return "video";}get enabled(){return !0;}pipe(){throw new Kg(Hg.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor");}unpipe(){throw new Kg(Hg.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor");}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(tb.ON_TRACK,e.track));}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(tb.ON_TRACK,void 0);}}class qb extends dT{set chained(e){this._chained=e;}get chained(){return this._chained;}constructor(e,t){super(),sh(this,"constraintsMap",new Map()),sh(this,"statsRegistry",[]),sh(this,"usageRegistry",[]),sh(this,"trackId",void 0),sh(this,"direction",void 0),sh(this,"_chained",!1),this.trackId=e,this.direction=t;}async getConstraints(){return await vT(this,ib.REQUEST_CONSTRAINTS);}async requestApplyConstraints(e,t){var i;return jC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(i=this.constraintsMap).call(i)));}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return jC.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(t=this.constraintsMap).call(t)));}registerStats(e,t,i){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i});}unregisterStats(e,t){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1);}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s});}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message));}return e;}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t});}unregisterUsage(e){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1);}async gatherUsage(){const e=[];if(!this.chained)return [];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}));}catch(e){jC.error("gather extension usage error",e);}return e;}getDirection(){return this.direction;}}class zb extends dT{constructor(e){super(),sh(this,"name","AudioProcessorDestination"),sh(this,"ID","0"),sh(this,"inputTrack",void 0),sh(this,"inputNode",void 0),sh(this,"audioProcessorContext",void 0),sh(this,"_source",void 0),this.audioProcessorContext=e;}get kind(){return "audio";}get enabled(){return !0;}pipe(){throw new Kg(Hg.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor");}unpipe(){throw new Kg(Hg.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor");}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(tb.ON_TRACK,void 0),this.emit(tb.ON_NODE,void 0);}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(tb.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(tb.ON_NODE,this.inputNode));}}class Jb extends dT{set chained(e){this._chained=e;}get chained(){return this._chained;}constructor(e,t,i){super(),sh(this,"constraintsMap",new Map()),sh(this,"statsRegistry",[]),sh(this,"audioContext",void 0),sh(this,"trackId",void 0),sh(this,"direction",void 0),sh(this,"usageRegistry",[]),sh(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i;}async getConstraints(){return vT(this,ib.REQUEST_CONSTRAINTS);}getAudioContext(){return this.audioContext;}async requestApplyConstraints(e,t){var i;return jC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(i=this.constraintsMap).call(i)));}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(t=this.constraintsMap).call(t)));}registerStats(e,t,i){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i});}unregisterStats(e,t){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1);}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s});}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message));}return e;}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t});}unregisterUsage(e){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1);}async gatherUsage(){const e=[];if(!this.chained)return [];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}));}catch(e){jC.error("gather extension usage error",e);}return e;}getDirection(){return this.direction;}}class Xb extends dT{get isPlayed(){return !0;}get isFreeze(){return !1;}constructor(){super(),sh(this,"context",void 0),sh(this,"processSourceNode",void 0),sh(this,"outputTrack",void 0),sh(this,"processedNode",void 0),sh(this,"clonedTrack",void 0),sh(this,"outputNode",void 0),this.outputNode=new Qb();}setVolume(){}createOutputTrack(){throw new Kg(Hg.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled");}getOriginVolumeLevel(){return 0;}getAccurateVolumeLevel(){return 0;}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class Qb{disconnect(){}connect(){}}function Zb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function $b(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Zb(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Zb(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class ew extends lb{get _source(){return this.initWebAudio();}set _source(e){this._trackSource=e;}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext;}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination;}get isPlaying(){return this._useAudioElement?Gb.isPlaying(this.getTrackId()):this._source.isPlayed;}get __className__(){return "LocalAudioTrack";}constructor(e,t,i,n){super(e,i),sh(this,"trackMediaType","audio"),sh(this,"_encoderConfig",void 0),sh(this,"_trackSource",void 0),sh(this,"_enabled",!0),sh(this,"_volume",100),sh(this,"_useAudioElement",!0),sh(this,"_bypassWebAudio",!1),sh(this,"processor",void 0),sh(this,"_processorContext",void 0),sh(this,"_processorDestination",void 0),sh(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new Xb(),RC("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),RC("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);bg()&&!pb?setTimeout(()=>this.initWebAudio()):this.initWebAudio();}setVolume(e){zg(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Gb.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void jC.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,yT(this,BA.NEED_REPLACE_TRACK,this).then(()=>{jC.debug("[".concat(this.getTrackId(),"] replace web audio track success"));}).catch(e=>{jC.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e);}));}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel();}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new Kg(Hg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Gb.setSinkID(this.getTrackId(),e);}async setEnabled(e,t,i){return this._setEnabled(e,t,i);}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await yT(this,BA.NEED_ENABLE_TRACK,this),jC.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"));}catch(e){throw i||(this._enabled=!1),jC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e;}}else {this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw i||(this._enabled=!0),jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this));}getStats(){JT(()=>{jC.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead");},"localAudioTrackGetStatsWarning");const e=AT(this,BA.GET_STATS);return e||$b({},XA);}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,t=>e(t));}play(){jC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(jC.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play();}stop(){jC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop();}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy();}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack);}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e));}renewMediaStreamTrack(e){return cg.resolve(void 0);}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e;}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset();}bindProcessorDestinationEvents(e){e.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this));}),e.on(tb.ON_NODE,e=>{this._source.processedNode=e;});}unbindProcessorDestinationEvents(e){e.removeAllListeners(tb.ON_TRACK),e.removeAllListeners(tb.ON_NODE);}bindProcessorContextEvents(e){e.on(ib.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings());});}unbindProcessorContextEvents(e){e.removeAllListeners(ib.REQUEST_CONSTRAINTS);}initWebAudio(){return this._trackSource instanceof Xb&&(this._trackSource=new Cb(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource;}initProcessor(){const e=new Jb(this._source.context,this.getTrackId(),"local"),t=new zb(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(zA.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e});}),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Gb.stop(this.getTrackId()),this._source.play()),yT(this,BA.NEED_REPLACE_MIXING_TRACK,this).then(()=>{jC.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"));}).catch(e=>{jC.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e);})),{processorContext:e,processorDestination:t};}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],ew.prototype,"setVolume",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],ew.prototype,"setPlaybackDevice",null),DI([_S("LocalAudioTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object,Boolean]),PI("design:returntype",cg)],ew.prototype,"setEnabled",null),DI([_S("LocalAudioTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],ew.prototype,"setMuted",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Object)],ew.prototype,"getStats",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",void 0)],ew.prototype,"setAudioFrameCallback",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"stop",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"close",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],ew.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"unpipe",null);class tw extends ew{get __className__(){return "MicrophoneAudioTrack";}constructor(e,t,i,n){super(e,t.encoderConfig?xA(t.encoderConfig):{},n,RC("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),sh(this,"_config",void 0),sh(this,"_deviceName","default"),sh(this,"_constraints",void 0),sh(this,"_originalConstraints",void 0),sh(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Mg()||Ug())&&_b.bindInterruptDetectorTrack(this);}async setDevice(e){if(jC.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.audio=$b({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId());}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Nb({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e;}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"));}async setEnabled(e,t,i){if(t)return jC.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e;}return;}const r=$b({},this._constraints),s=kb.searchDeviceIdByName(this._deviceName);s&&!r.deviceId&&(r.deviceId=s);try{i||(this._enabled=!0);const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw i||(this._enabled=!1),jC.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled success"));}close(){super.close(),(Mg()||Ug())&&_b.unbindInterruptDetectorTrack(this);}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0));};_b.on(vA.IOS_INTERRUPTION_END,e);}else jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0);}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(ib.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t();}catch(e){i(e);}});}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],tw.prototype,"setDevice",null),DI([_S("MicrophoneAudioTrack","_enabledMutex"),$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean,Boolean]),PI("design:returntype",cg)],tw.prototype,"setEnabled",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],tw.prototype,"close",null);class iw extends ew{get __className__(){return "BufferSourceAudioTrack";}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),sh(this,"source",void 0),sh(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(zA.AUDIO_SOURCE_STATE_CHANGE,e=>{this.safeEmit(YA.SOURCE_STATE_CHANGE,e);});try{this._mediaStreamTrack=this._source.createOutputTrack();}catch(e){}}get currentState(){return this._bufferSource.currentState;}get duration(){return this._bufferSource.duration;}get playbackSpeed(){return this._bufferSource.playbackSpeed;}getCurrentTime(){return this._bufferSource.currentTime;}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer();}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer();}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e);}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer();}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer();}close(){this.source=null,this._bufferSource.destroy(),super.close();}setAudioBufferPlaybackSpeed(e){zg(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],iw.prototype,"startProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"pauseProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],iw.prototype,"seekAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"resumeProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"stopProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"close",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],iw.prototype,"setAudioBufferPlaybackSpeed",null);class nw extends ew{get __className__(){return "MixingAudioTrack";}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return !0;return !1;}constructor(){const e=mb().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,nS(8,"track-mix-")),sh(this,"trackList",void 0),sh(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack();}catch(e){}this.destNode=e,this.trackList=[];}hasAudioTrack(e){return -1!==this.trackList.indexOf(e);}addAudioTrack(e){-1===this.trackList.indexOf(e)?(jC.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):jC.debug("track ".concat(e.getTrackId()," is already added"));}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){jC.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode);}catch(e){}WT(this.trackList,e),this.updateEncoderConfig();}}updateEncoderConfig(){const e={};this.trackList.forEach(t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0));}),this._encoderConfig=e;}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach(t=>{t instanceof nw?t.emit(KA.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e);}));}}function rw(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=LA(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Bg()&&i.frameRate&&(t.frameRate=i.frameRate),Sg().name===Eg.EDGE&&"object"==typeof t.frameRate&&(t.frameRate.max=60),wg()&&(t.frameRate={ideal:30,max:30}),t;}function sw(e){const t={};if(Bg()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Ag()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=xA(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize;}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Gg()&&(t.sampleRate=void 0),t;}class ow extends Rb{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(zA.AUDIO_SOURCE_STATE_CHANGE,this._currentState));}get currentState(){return this._currentState;}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),sh(this,"audioBuffer",void 0),sh(this,"sourceNode",void 0),sh(this,"startPlayTime",0),sh(this,"startPlayOffset",0),sh(this,"pausePlayTime",0),sh(this,"options",void 0),sh(this,"currentLoopCount",0),sh(this,"currentPlaybackSpeed",100),sh(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0;}createWebAudioDiagram(){return this.context.createGain();}get duration(){return this.audioBuffer?this.audioBuffer.duration:0;}get playbackSpeed(){return this.currentPlaybackSpeed;}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0;}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):jC.warning("can not set audio source options");}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing";}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused");}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e));}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing");}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop();}catch(e){}this.reset();}}destroy(){this.audioBuffer=null,super.destroy();}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e;}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this));}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e;}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset();}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0;}}const aw=new Map();async function cw(e,t){let i=null;if("string"==typeof e){const t=aw.get(e);if(t)return jC.debug("use cached audio resource: ",e),t;try{i=(await fS(()=>sC.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data;}catch(e){throw new Kg(Hg.FETCH_AUDIO_FILE_FAILED,e.toString());}}else {const t=new cg((t,i)=>{const n=new FileReader();n.onload=e=>{e.target?t(e.target.result):i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR));},n.onerror=()=>{i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR));},n.readAsArrayBuffer(e);});i=await t;}const n=await function(e){const t=mb();return new cg((i,n)=>{t.decodeAudioData(e,e=>{i(e);},e=>{n(new Kg(Hg.DECODE_AUDIO_FILE_FAILED,e.toString()));});});}(i);return "string"==typeof e&&t&&aw.set(e,n),n;}const dw=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new cg((i,n)=>{t.toBlob(async e=>{if(t.remove(),e){const n=await lw(e);i({buffer:n,width:t.width,height:t.height});}else n(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED));},e,1);});},lw=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t);};function uw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function hw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?uw(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):uw(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class pw{get videoElementStatus(){return this._videoElementStatus;}set videoElementStatus(e){e!==this._videoElementStatus&&(jC.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e);}get videoState(){return this._videoState;}set videoState(e){var t;e!==this._videoState&&(jC.debug("[".concat(this.trackId,"] video-status change ").concat(this._videoState," => ").concat(e)),this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState));}constructor(e){sh(this,"trackId",void 0),sh(this,"config",void 0),sh(this,"onFirstVideoFrameDecoded",void 0),sh(this,"onVideoStateChanged",void 0),sh(this,"freezeTimeCounterList",[]),sh(this,"renderFreezeAccTime",0),sh(this,"isKeepLastFrame",!1),sh(this,"timeUpdatedCount",0),sh(this,"freezeTime",0),sh(this,"playbackTime",0),sh(this,"lastTimeUpdatedTime",0),sh(this,"autoplayFailed",!1),sh(this,"videoTrack",void 0),sh(this,"videoElement",void 0),sh(this,"cacheVideoElement",void 0),sh(this,"_videoState",ob.VideoStateStopped),sh(this,"videoElementCheckInterval",void 0),sh(this,"videoElementFreezeTimeout",void 0),sh(this,"_videoElementStatus",sb.NONE),sh(this,"isGettingVideoDimensions",!1),sh(this,"startGetVideoDimensions",()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return jC.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500);};!this.isGettingVideoDimensions&&e();}),sh(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===_b.curState&&(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()));}),sh(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=sb.PLAYING;break;case"loadeddata":if(this.videoState=ob.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove();}catch(e){}this.cacheVideoElement=void 0;}break;case"canplay":this.videoElementStatus=sb.CANPLAY;break;case"stalled":this.videoElementStatus=sb.STALLED;break;case"suspend":this.videoElementStatus=sb.SUSPEND;break;case"pause":this.videoElementStatus=sb.PAUSED,Og()||Vg()||bg()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=sb.WAITING;break;case"abort":this.videoElementStatus=sb.ABORT;break;case"ended":this.videoElementStatus=sb.ENDED;break;case"emptied":this.videoElementStatus=sb.EMPTIED;break;case"error":{this.videoElementStatus=sb.ERROR;const e=this.videoElement.error;e&&jC.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break;}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Dw.lastVisibleTime<Dw.lastHiddenTime||i<Dw.lastHiddenTime||i<Dw.lastVisibleTime)return;for(t>RC("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3);}break;}}}),sh(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()));}),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16);}getVideoElement(){return this.videoElement;}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0;}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement();}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement());}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch(t=>{e&&Bb(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(jC.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):jC.warning("[".concat(this.trackId,"] play warning: "),t);});const i=Sg();if(("Safari"===i.name&&15===Number(i.version)||Mg())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)");};t.then(e).catch(e);}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return jC.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i;}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new cg((n,r)=>{i.toBlob(async e=>{if(i.remove(),e){const t=await lw(e);n({buffer:t,width:i.width,height:i.height});}else r(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED));},e,t<0?.1:t>1?1:t);})):await dw(e);}destroy(){_b.off(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=ob.VideoStateStopped;}initVideoElement(){if(this.videoElementStatus=sb.INIT,!this.videoElementCheckInterval&&(_w.forEach(e=>{this.videoElement.addEventListener(e,this.handleVideoEvents);}),this.videoElementCheckInterval=window.setInterval(()=>{(function(e){return e!==document.body&&document.body.contains(e);})(this.videoElement)||(this.videoElementStatus=sb.DESTROYED);},1e3),RC("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,RC("VIDEO_FREEZE_DURATION")));},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===ob.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=ob.VideoStateFrozen:document.addEventListener("visibilitychange",n));},s=(e,t)=>{if(this.videoElementStatus===sb.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;this.videoState===ob.VideoStateStarting&&(this.videoState=ob.VideoStateDecoding),this.videoState===ob.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,RC("VIDEO_FREEZE_DURATION"))),e<RC("VIDEO_FREEZE_DURATION")&&this.videoState===ob.VideoStateFrozen&&(this.videoState=ob.VideoStateDecoding),e>RC("VIDEO_FREEZE_DURATION")&&Dw.lastVisibleTime>=Dw.lastHiddenTime&&i.timestamp>Dw.lastVisibleTime&&i.timestamp>Dw.lastHiddenTime&&(this.renderFreezeAccTime+=e);}i=hw(hw({},t),{},{timestamp:e});}var n,o;RC("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(n=(o=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(o,s));};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,s);}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Gg()&&(this.videoElement.poster="noposter");const i=Sg();if("Safari"===i.name&&15===Number(i.version)||Mg()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load());}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load();const n=this.videoElement.play();void 0!==n&&n.catch(e=>{jC.debug("[".concat(this.trackId,"] playback interrupted"),e.toString());});}resetVideoElement(){_w.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents);}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=sb.NONE;}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{jC.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."));}).catch(e=>{jC.error(e);}),this.autoplayFailed=!1,Wg()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0));};Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),xb();}}const _w=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Ew extends pw{constructor(e){super(e),sh(this,"container",void 0),sh(this,"slot",void 0),this.slot=e.element,this.updateConfig(e);}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements();}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements());}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e);}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2);}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await dw(e);}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container);}catch(e){}this.container=void 0;}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",RC("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container);}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0";}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement);}catch(e){}this.videoElement=document.createElement("video");}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"));}getContainerElement(){return this.container;}}function mw(e){return new cg((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const s=Og()?"canplay":"playing";r.addEventListener(s,()=>{const e=r.videoWidth,i=r.videoHeight;!e&&wg()||(n=!0,r.srcObject=null,r.remove(),t([e,i]));}),r.srcObject=new MediaStream([e]),r.play().catch(sS),setTimeout(()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]));},4e3);});}const fw=async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return Uint8Array.from(t);}(function(e){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n;}function n(e,t){const i=(65535&e)+(65535&t);return (e>>16)+(t>>16)+(i>>16)<<16|65535&i;}function r(e,t,i,r,s,o){return n(function(e,t){return e<<t|e>>>32-t;}(n(n(t,e),n(r,o)),s),i);}function s(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a);}function o(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a);}function a(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a);}function c(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a);}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t<e.length;t++)n[t>>2]|=e.charCodeAt(t)<<t%4*8;return n[t>>2]|=128<<t%4*8,n[16*i-2]=8*e.length,n;}(e);let l,u,h,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)u=E,h=m,p=f,_=g,E=s(E,m,f,g,d[l+0],7,-680876936),g=s(g,E,m,f,d[l+1],12,-389564586),f=s(f,g,E,m,d[l+2],17,606105819),m=s(m,f,g,E,d[l+3],22,-1044525330),E=s(E,m,f,g,d[l+4],7,-176418897),g=s(g,E,m,f,d[l+5],12,1200080426),f=s(f,g,E,m,d[l+6],17,-1473231341),m=s(m,f,g,E,d[l+7],22,-45705983),E=s(E,m,f,g,d[l+8],7,1770035416),g=s(g,E,m,f,d[l+9],12,-1958414417),f=s(f,g,E,m,d[l+10],17,-42063),m=s(m,f,g,E,d[l+11],22,-1990404162),E=s(E,m,f,g,d[l+12],7,1804603682),g=s(g,E,m,f,d[l+13],12,-40341101),f=s(f,g,E,m,d[l+14],17,-1502002290),m=s(m,f,g,E,d[l+15],22,1236535329),E=o(E,m,f,g,d[l+1],5,-165796510),g=o(g,E,m,f,d[l+6],9,-1069501632),f=o(f,g,E,m,d[l+11],14,643717713),m=o(m,f,g,E,d[l+0],20,-373897302),E=o(E,m,f,g,d[l+5],5,-701558691),g=o(g,E,m,f,d[l+10],9,38016083),f=o(f,g,E,m,d[l+15],14,-660478335),m=o(m,f,g,E,d[l+4],20,-405537848),E=o(E,m,f,g,d[l+9],5,568446438),g=o(g,E,m,f,d[l+14],9,-1019803690),f=o(f,g,E,m,d[l+3],14,-187363961),m=o(m,f,g,E,d[l+8],20,1163531501),E=o(E,m,f,g,d[l+13],5,-1444681467),g=o(g,E,m,f,d[l+2],9,-51403784),f=o(f,g,E,m,d[l+7],14,1735328473),m=o(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=n(E,u),m=n(m,h),f=n(f,p),g=n(g,_);return i(E)+i(m)+i(f)+i(g);}(""+t+i)).slice(0,16),r=n.slice(0,12),s=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},s,e));},gw=async(e,t,i)=>await fw(e.buffer,t,i);function Tw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Sw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Tw(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Tw(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class Rw extends lb{get isPlaying(){return !(!this._player||this._player.videoElementStatus!==sb.PLAYING);}get processorContext(){return this._processorContext;}set processorContext(e){this._processorContext=e;}get __className__(){return "LocalVideoTrack";}constructor(e,t,i,n,r,s){if(super(e,r),sh(this,"trackMediaType","video"),sh(this,"_player",void 0),sh(this,"isUseScaleResolutionDownBy",!1),sh(this,"_videoVisibleTimer",null),sh(this,"_statsTimer",null),sh(this,"_previousVideoVisibleStatus",void 0),sh(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),sh(this,"_encoderConfig",void 0),sh(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),sh(this,"_optimizationMode",void 0),sh(this,"_videoHeight",void 0),sh(this,"_videoWidth",void 0),sh(this,"_forceBitrateLimit",void 0),sh(this,"_enabled",!0),sh(this,"processorDestination",void 0),sh(this,"_processorContext",void 0),bg()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i;}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=s||[],-1===this._hints.indexOf(jA.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=Sg();return !(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t);}(Eg.CHROME,115)&&-1!==Rg().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&IA().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),s=void 0,n.removeEventListener("ended",a);};let c=window.setInterval(()=>{if(s&&r&&Date.now()-o>(null!=t?t:1e3))try{"live"===n.readyState?s.enqueue(r.clone()):a();}catch(e){a();}},null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(s=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close();}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n;}}(e);t&&(jC.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t);}t&&-1!==this._hints.indexOf(jA.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new qb(this.getTrackId(),"local"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents();}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body);}jC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Sw(Sw(Sw({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(YA.VIDEO_ELEMENT_VISIBLE_STATUS,e);}catch(e){}},RC("CHECK_VIDEO_VISIBLE_INTERVAL"));}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._statsTimer&&(this.isUseScaleResolutionDownBy=!1,window.clearInterval(this._statsTimer),this._statsTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug("[".concat(this.getTrackId(),"] stop video playback")));}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}return t||(this._enabled=!1),void jC.info("[".concat(this.getTrackId(),"] setEnabled to false success"));}this._originMediaStreamTrack.enabled=!0;try{await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0);}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this));}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if("720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=rw({encoderConfig:e});(bg()||Og()||Vg())&&(t.deviceId=void 0),jC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution();}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t;}}this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}getStats(){JT(()=>{jC.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead");},"localVideoTrackGetStatsWarning");const e=AT(this,BA.GET_STATS);return e||Sw({},QA);}async setBeautyEffect(e){jC.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect");}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2);}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await dw(e);}async setBitrateLimit(e){if(jC.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate);try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void jC.error(Hg.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await yT(this,BA.SET_OPTIMIZATION_MODE,this);}catch(e){throw this._optimizationMode=t,jC.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"));}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return jC.error(Hg.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,jC.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"));}updateMediaStreamTrackResolution(){mw(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t;}).catch(sS);}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack);}_getDefaultPlayerConfig(){return {fit:"contain"};}async setSenderConfiguration(e){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");jC.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:s,min:o}=function(e,t,i,n,r){const s=RC("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===s)return {min:n,max:r};if(void 0===r){var o;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===s?4*a:2*a,n=null!==(o=n)&&void 0!==o?o:a;}else {var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10);}return {min:n,max:r};}(e,t,i,r,n);this._encoderConfig.bitrateMin=o,this._encoderConfig.bitrateMax=s,jC.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(s,", brMin: ").concat(o,"]"));}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason));}return t;}return;}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message);}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e;}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset();}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe();}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,"track-video-cloned-"),r=new Rw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,qT(this._scalabilityMode),this._optimizationMode,n,qT(this._hints));return e&&i&&r.setEncoderConfiguration(i),jC.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r;}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Kg(Hg.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Kg(Hg.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution();}startMonitorStats(){if(!bg()&&!Og())return;this._statsTimer&&window.clearInterval(this._statsTimer);let e=2,t=NA[e];let i=-1;let n=Date.now();const r=e=>{e>2||e<0||(n=Date.now(),t=NA[e],this.setSenderConfiguration(t));};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval(()=>{const s=this.getStats(),o=AT(this,BA.GET_RTC_STATS);if(s.sendPackets>0&&o){-1===i&&(i=Date.now());const a=Date.now();if(a-i<1e3||a-n<RC("PROFILE_SWITCH_INTERVAL"))return;const c=s.sendFrameRate,d=.6*t.frameRate,l=.9*t.frameRate;"number"==typeof c&&c>0&&c<d?e>0&&(e--,r(e),jC.debug("[".concat(this.getTrackId(),"] step down for fps ").concat(c,", switchProfile to ").concat(e))):o.OutgoingAvailableBandwidth<t.bitrateMin?e>0&&(e--,r(e),jC.debug("[".concat(this.getTrackId(),"] step down for OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", bitrateMin ").concat(t.bitrateMin,", switchProfile to ").concat(e))):"number"==typeof c&&c>l&&e<NA.length-1&&o.OutgoingAvailableBandwidth>1.2*NA[e+1].bitrateMin&&(e++,r(e),jC.debug("[".concat(this.getTrackId(),"] step up for fps ").concat(c,", OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", switchProfile to ").concat(e)));}},RC("CHECK_LOCAL_STATS_INTERVAL"));}sendSeiData(e){if(JT(()=>{eI.reportApiInvoke(null,{name:hT.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:pT.TRACER}).onSuccess("");},this._mediaStreamTrack.id||this.getTrackId()),!RC("ENABLE_VIDEO_SEI")||!RC("ENABLE_ENCODED_TRANSFORM"))return void jC.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new Kg(Hg.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void jC.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===n?this.safeEmit("sei-to-send",e):jC.warning("SEI is not supported by ".concat(n));}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this));});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK);}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(ib.REQUEST_CONSTRAINTS);}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",void 0)],Rw.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"stop",null),DI([_S("LocalVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean]),PI("design:returntype",cg)],Rw.prototype,"setEnabled",null),DI([_S("LocalVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],Rw.prototype,"setMuted",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],Rw.prototype,"setEncoderConfiguration",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Object)],Rw.prototype,"getStats",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object]),PI("design:returntype",cg)],Rw.prototype,"setBeautyEffect",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",ImageData)],Rw.prototype,"getCurrentFrameData",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[String,Number]),PI("design:returntype",cg)],Rw.prototype,"getCurrentFrameImage",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Rw.prototype,"setBitrateLimit",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],Rw.prototype,"setOptimizationMode",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],Rw.prototype,"setScalabiltyMode",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"updateMediaStreamTrackResolution",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Rw.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"unpipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"close",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),PI("design:type",Function),PI("design:paramtypes",[MediaStreamTrack,Boolean]),PI("design:returntype",cg)],Rw.prototype,"replaceTrack",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"startMonitorStats",null);class Cw extends Rw{get __className__(){return "CameraVideoTrack";}constructor(e,t,i,n,r,s){super(e,LA(t.encoderConfig),n,r,s),sh(this,"_config",void 0),sh(this,"_originalConstraints",void 0),sh(this,"_constraints",void 0),sh(this,"_enabled",!0),sh(this,"_deviceName","default"),sh(this,"tryResumeVideoForIOS15_16WeChat",async()=>{(Mg()||Ug())&&!function(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2;}()&&Fg()&&this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack());}),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=LA(this._config.encoderConfig),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.on(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents();}async setDevice(e){return "string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0;}async _setDeviceById(e){if(jC.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.video=Sw({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId());}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e;}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setDevice success"));}async _setDeviceByFacingModel(e){jC.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Sw(Sw({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Nb(t,this.getTrackId());}catch(t){throw jC.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t;}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution();}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Sw({},t.video),jC.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"));}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else {const e=await Nb({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1);}await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e;}this.updateMediaStreamTrackResolution(),jC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0);}else {this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled to false success"));}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");"720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=YT(this._config);i.encoderConfig=e;const n=rw(i);(bg()||Og()||Vg())&&(n.deviceId=void 0),jC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution();}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t;}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}_getDefaultPlayerConfig(){return {mirror:!0,fit:"cover"};}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0));};_b.on(vA.IOS_INTERRUPTION_END,e);}else jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Nb({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution();}}close(){super.close(),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.off(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat);}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,"track-cam-cloned-"),r=new Cw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,qT(Sw(Sw({},this._config),{},{encoderConfig:i})),qT(this._constraints),qT(this._scalabilityMode),this._optimizationMode,n);return e&&i&&r.setEncoderConfiguration(i),jC.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r;}bindProcessorContextEvents(){this.processorContext.on(ib.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t();}catch(e){i(e);}}),this.processorContext.on(ib.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings());});}}function Iw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function vw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Iw(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Iw(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function yw(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=vw(vw({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?jC.debug("[".concat(e,"] set content hint to"),i.optimizationMode):jC.debug("[".concat(e,"] set content hint failed")))):jC.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")));}function Aw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function bw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Aw(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Aw(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Cw.prototype,"setDevice",null),DI([_S("CameraVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean]),PI("design:returntype",cg)],Cw.prototype,"setEnabled",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],Cw.prototype,"setEncoderConfiguration",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Cw.prototype,"close",null);class ww extends db{getUserId(){return this._userId;}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(nS(5,""))),sh(this,"_userId",void 0),sh(this,"_uintId",void 0),sh(this,"_isDestroyed",!1),sh(this,"store",void 0),sh(this,"processor",void 0),this._userId=t,this._uintId=i,this.store=n;}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext});}_destroy(){this._isDestroyed=!0,jC.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close();}getProcessorStats(){return this.processorContext.gatherStats();}getProcessorUsage(){return this.processorContext.gatherUsage();}}class Ow extends ww{get isPlaying(){return !(!this._player||this._player.videoElementStatus!==sb.PLAYING);}get __className__(){return "RemoteVideoTrack";}constructor(e,t,i,n){super(e,t,i,n),sh(this,"_videoVisibleTimer",null),sh(this,"_previousVideoVisibleStatus",void 0),sh(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),sh(this,"trackMediaType","video"),sh(this,"_videoWidth",void 0),sh(this,"_videoHeight",void 0),sh(this,"_player",void 0),sh(this,"processorDestination",void 0),sh(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new qb(this.getTrackId(),"remote"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents();}getStats(){JT(()=>{jC.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead");},"remoteVideoTrackGetStatsWarning");return AT(this,BA.GET_STATS)||bw({},eb);}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body);}jC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=bw(bw({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(qA.FIRST_FRAME_DECODED);},this._player.onVideoStateChanged=e=>{this.safeEmit(qA.VIDEO_STATE_CHANGED,e);}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(qA.VIDEO_ELEMENT_VISIBLE_STATUS,e);}catch(e){}},RC("CHECK_VIDEO_VISIBLE_INTERVAL"));}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug("[".concat(this.getTrackId(),"] stop video playback")));}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2);}updateMediaStreamTrackResolution(){mw(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t;}).catch(sS);}_updatePlayerSource(){jC.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack);}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason));}return t;}return;}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message);}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e;}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset();}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource());});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK);}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents();}_onSei(e){this.emit(KA.SEI_RECEIVED,e);}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",void 0)],Ow.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Ow.prototype,"stop",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Ow.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Ow.prototype,"unpipe",null);class Nw extends ww{get isPlaying(){return this._useAudioElement?Gb.isPlaying(this.getTrackId()):this._source.isPlayed;}get __className__(){return "RemoteAudioTrack";}constructor(e,t,i,n){super(e,t,i,n),sh(this,"trackMediaType","audio"),sh(this,"_source",void 0),sh(this,"_useAudioElement",!0),sh(this,"_volume",100),sh(this,"processorContext",void 0),sh(this,"processorDestination",void 0),sh(this,"_played",!1),sh(this,"_bypassWebAudio",!1),RC("DISABLE_WEBAUDIO")?(this._source=new Xb(),this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Cb(e,!0),RC("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(zA.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(qA.FIRST_FRAME_DECODED);}),this.processorContext=new Jb(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new zb(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(zA.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext});});}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,t=>e(t));}setVolume(e){this._volume=e,this._useAudioElement?Gb.setVolume(this.getTrackId(),e):this._source.setVolume(e/100);}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new Kg(Hg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Gb.setSinkID(this.getTrackId(),e);}getVolumeLevel(){return this._source.getAccurateVolumeLevel();}getStats(){JT(()=>{jC.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead");},"remoteAudioTrackGetStatsWarning");return AT(this,BA.GET_STATS)||bw({},ZA);}play(){jC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(jC.debug("[".concat(this.getTrackId(),"] use audio element to play")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play();}stop(){jC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop();}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy();}_isFreeze(){return this._source.isFreeze;}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack);}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e;}unpipe(){var e;if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset();}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource());}),this.processorDestination.on(tb.ON_NODE,e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t);});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK),this.processorDestination.removeAllListeners(tb.ON_NODE);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],Nw.prototype,"setVolume",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],Nw.prototype,"setPlaybackDevice",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"stop",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Nw.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"unpipe",null);const Dw=new class extends dT{get visibility(){return document.visibilityState;}get lastHiddenTime(){return this._lastHiddenTime;}get lastVisibleTime(){return this._lastVisibleTime;}constructor(){super(),sh(this,"_lastHiddenTime",0),sh(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),jC.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState);});}}();/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */function Pw(e){let t=e.length;for(;--t>=0;)e[t]=0;}const Lw=256,kw=286,Mw=30,Uw=15,xw=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Vw=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Fw=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Bw=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jw=new Array(576);Pw(jw);const Gw=new Array(60);Pw(Gw);const Ww=new Array(512);Pw(Ww);const Hw=new Array(256);Pw(Hw);const Kw=new Array(29);Pw(Kw);const Yw=new Array(Mw);function qw(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length;}let zw,Jw,Xw;function Qw(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t;}Pw(Yw);const Zw=e=>e<256?Ww[e]:Ww[256+(e>>>7)],$w=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255;},eO=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,$w(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i);},tO=(e,t,i)=>{eO(e,i[2*t],i[2*t+1]);},iO=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1;}while(--t>0);return i>>>1;},nO=(e,t,i)=>{const n=new Array(16);let r,s,o=0;for(r=1;r<=Uw;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=iO(n[t]++,t));}},rO=e=>{let t;for(t=0;t<kw;t++)e.dyn_ltree[2*t]=0;for(t=0;t<Mw;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0;},sO=e=>{e.bi_valid>8?$w(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0;},oO=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i];},aO=(e,t,i)=>{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r<e.heap_len&&oO(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!oO(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n;},cO=(e,t,i)=>{let n,r,s,o,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?tO(e,r,t):(s=Hw[r],tO(e,s+Lw+1,t),o=xw[s],0!==o&&(r-=Kw[s],eO(e,r,o)),n--,s=Zw(n),tO(e,s,i),o=Vw[s],0!==o&&(n-=Yw[s],eO(e,n,o)));}while(a<e.sym_next);tO(e,256,t);},dO=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let o,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,o=0;o<s;o++)0!==i[2*o]?(e.heap[++e.heap_len]=d=o,e.depth[o]=0):i[2*o+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,i[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[2*c+1]);for(t.max_code=d,o=e.heap_len>>1;o>=1;o--)aO(e,i,o);c=s;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],aO(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=a,i[2*c]=i[2*o]+i[2*a],e.depth[c]=(e.depth[o]>=e.depth[a]?e.depth[o]:e.depth[a])+1,i[2*o+1]=i[2*a+1]=c,e.heap[1]=c++,aO(e,i,1);}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=Uw;h++)e.bl_count[h]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=i[2*i[2*l+1]+1]+1,h>c&&(h=c,E++),i[2*l+1]=h,l>n||(e.bl_count[h]++,p=0,l>=a&&(p=o[l-a]),_=i[2*l],e.opt_len+=_*(h+p),s&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2;}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>n||(i[2*u+1]!==h&&(e.opt_len+=(h-i[2*u+1])*i[2*u],i[2*u+1]=h),l--);}})(e,t),nO(i,d,e.bl_count);},lO=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=o,o=t[2*(n+1)+1],++a<c&&r===o||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4));},uO=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),n=0;n<=i;n++)if(r=o,o=t[2*(n+1)+1],!(++a<c&&r===o)){if(a<d)do{tO(e,r,e.bl_tree);}while(0!=--a);else 0!==r?(r!==s&&(tO(e,r,e.bl_tree),a--),tO(e,16,e.bl_tree),eO(e,a-3,2)):a<=10?(tO(e,17,e.bl_tree),eO(e,a-3,3)):(tO(e,18,e.bl_tree),eO(e,a-11,7));a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4);}};let hO=!1;const pO=(e,t,i,n)=>{eO(e,0+(n?1:0),3),sO(e),$w(e,i),$w(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i;};var _O=e=>{hO||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(Kw[n]=i,e=0;e<1<<xw[n];e++)Hw[i++]=n;for(Hw[i-1]=n,r=0,n=0;n<16;n++)for(Yw[n]=r,e=0;e<1<<Vw[n];e++)Ww[r++]=n;for(r>>=7;n<Mw;n++)for(Yw[n]=r<<7,e=0;e<1<<Vw[n]-7;e++)Ww[256+r++]=n;for(t=0;t<=Uw;t++)s[t]=0;for(e=0;e<=143;)jw[2*e+1]=8,e++,s[8]++;for(;e<=255;)jw[2*e+1]=9,e++,s[9]++;for(;e<=279;)jw[2*e+1]=7,e++,s[7]++;for(;e<=287;)jw[2*e+1]=8,e++,s[8]++;for(nO(jw,287,s),e=0;e<Mw;e++)Gw[2*e+1]=5,Gw[2*e]=iO(e,5);zw=new qw(jw,xw,257,kw,Uw),Jw=new qw(Gw,Vw,0,Mw,Uw),Xw=new qw(new Array(0),Fw,0,19,7);})(),hO=!0),e.l_desc=new Qw(e.dyn_ltree,zw),e.d_desc=new Qw(e.dyn_dtree,Jw),e.bl_desc=new Qw(e.bl_tree,Xw),e.bi_buf=0,e.bi_valid=0,rO(e);},EO=(e,t,i,n)=>{let r,s,o=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<Lw;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0;})(e)),dO(e,e.l_desc),dO(e,e.d_desc),o=(e=>{let t;for(lO(e,e.dyn_ltree,e.l_desc.max_code),lO(e,e.dyn_dtree,e.d_desc.max_code),dO(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Bw[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t;})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?pO(e,t,i,n):4===e.strategy||s===r?(eO(e,2+(n?1:0),3),cO(e,jw,Gw)):(eO(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(eO(e,t-257,5),eO(e,i-1,5),eO(e,n-4,4),r=0;r<n;r++)eO(e,e.bl_tree[2*Bw[r]+1],3);uO(e,e.dyn_ltree,t-1),uO(e,e.dyn_dtree,i-1);})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),cO(e,e.dyn_ltree,e.dyn_dtree)),rO(e),n&&sO(e);},mO=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Hw[i]+Lw+1)]++,e.dyn_dtree[2*Zw(t)]++),e.sym_next===e.sym_end),fO={_tr_init:_O,_tr_stored_block:pO,_tr_flush_block:EO,_tr_tally:mO,_tr_align:e=>{eO(e,2,3),tO(e,256,jw),(e=>{16===e.bi_valid?($w(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8);})(e);}};var gO=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0;}while(--o);r%=65521,s%=65521;}return r|s<<16|0;};const TO=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e;}return t;})());var SO=(e,t,i,n)=>{const r=TO,s=n+i;e^=-1;for(let i=n;i<s;i++)e=e>>>8^r[255&(e^t[i])];return -1^e;},RO={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},CO={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:IO,_tr_stored_block:vO,_tr_flush_block:yO,_tr_tally:AO,_tr_align:bO}=fO,{Z_NO_FLUSH:wO,Z_PARTIAL_FLUSH:OO,Z_FULL_FLUSH:NO,Z_FINISH:DO,Z_BLOCK:PO,Z_OK:LO,Z_STREAM_END:kO,Z_STREAM_ERROR:MO,Z_DATA_ERROR:UO,Z_BUF_ERROR:xO,Z_DEFAULT_COMPRESSION:VO,Z_FILTERED:FO,Z_HUFFMAN_ONLY:BO,Z_RLE:jO,Z_FIXED:GO,Z_DEFAULT_STRATEGY:WO,Z_UNKNOWN:HO,Z_DEFLATED:KO}=CO,YO=286,qO=30,zO=19,JO=2*YO+1,XO=15,QO=258,ZO=262,$O=42,eN=113,tN=666,iN=(e,t)=>(e.msg=RO[t],t),nN=e=>2*e-(e>4?9:0),rN=e=>{let t=e.length;for(;--t>=0;)e[t]=0;},sN=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0;}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0;}while(--t);};let oN=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const aN=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0));},cN=(e,t)=>{yO(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,aN(e.strm);},dN=(e,t)=>{e.pending_buf[e.pending++]=t;},lN=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t;},uN=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=gO(e.adler,t,r,i):2===e.state.wrap&&(e.adler=SO(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r);},hN=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,o=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-ZO?e.strstart-(e.w_size-ZO):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+QO;let p=d[s+o-1],_=d[s+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+o]===_&&d[i+o-1]===p&&d[i]===d[s]&&d[++i]===d[s+1]){s+=2,i++;do{}while(d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&s<h);if(n=QO-(h-s),s=h-QO,n>o){if(e.match_start=t,o=n,n>=a)break;p=d[s+o-1],_=d[s+o];}}}while((t=u[t&l])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead;},pN=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ZO)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),sN(e),n+=t),0===e.strm.avail_in)break;if(i=uN(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=oN(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=oN(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<ZO&&0!==e.strm.avail_in);},_N=(e,t)=>{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i<s&&(0===i&&t!==DO||t===wO||i!==n+e.strm.avail_in))break;o=t===DO&&i===n+e.strm.avail_in?1:0,vO(e,0,0,o),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,aN(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(uN(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i);}while(0===o);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),o?4:t!==wO&&t!==DO&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(uN(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===DO)&&t!==wO&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,o=t===DO&&0===e.strm.avail_in&&i===n?1:0,vO(e,e.block_start,i,o),e.block_start+=i,aN(e.strm)),o?3:1);},EN=(e,t)=>{let i,n;for(;;){if(e.lookahead<ZO){if(pN(e),e.lookahead<ZO&&t===wO)return 1;if(0===e.lookahead)break;}if(i=0,e.lookahead>=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-ZO&&(e.match_length=hN(e,i)),e.match_length>=3){if(n=AO(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;}while(0!=--e.match_length);e.strstart++;}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=oN(e,e.ins_h,e.window[e.strstart+1]);}else n=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;},mN=(e,t)=>{let i,n,r;for(;;){if(e.lookahead<ZO){if(pN(e),e.lookahead<ZO&&t===wO)return 1;if(0===e.lookahead)break;}if(i=0,e.lookahead>=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-ZO&&(e.match_length=hN(e,i),e.match_length<=5&&(e.strategy===FO||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=AO(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(cN(e,!1),0===e.strm.avail_out))return 1;}else if(e.match_available){if(n=AO(e,0,e.window[e.strstart-1]),n&&cN(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1;}else e.match_available=1,e.strstart++,e.lookahead--;}return e.match_available&&(n=AO(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;};function fN(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r;}const gN=[new fN(0,0,0,0,_N),new fN(4,4,8,4,EN),new fN(4,5,16,8,EN),new fN(4,6,32,32,EN),new fN(4,4,16,16,mN),new fN(8,16,32,32,mN),new fN(8,16,128,128,mN),new fN(8,32,128,256,mN),new fN(32,128,258,1024,mN),new fN(32,258,258,4096,mN)];function TN(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=KO,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*JO),this.dyn_dtree=new Uint16Array(2*(2*qO+1)),this.bl_tree=new Uint16Array(2*(2*zO+1)),rN(this.dyn_ltree),rN(this.dyn_dtree),rN(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(XO+1),this.heap=new Uint16Array(2*YO+1),rN(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*YO+1),rN(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}const SN=e=>{if(!e)return 1;const t=e.state;return !t||t.strm!==e||t.status!==$O&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==eN&&t.status!==tN?1:0;},RN=e=>{if(SN(e))return iN(e,MO);e.total_in=e.total_out=0,e.data_type=HO;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?$O:eN,e.adler=2===t.wrap?0:1,t.last_flush=-2,IO(t),LO;},CN=e=>{const t=RN(e);var i;return t===LO&&((i=e.state).window_size=2*i.w_size,rN(i.head),i.max_lazy_match=gN[i.level].max_lazy,i.good_match=gN[i.level].good_length,i.nice_match=gN[i.level].nice_length,i.max_chain_length=gN[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t;},IN=(e,t,i,n,r,s)=>{if(!e)return MO;let o=1;if(t===VO&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||i!==KO||n<8||n>15||t<0||t>9||s<0||s>GO||8===n&&1!==o)return iN(e,MO);8===n&&(n=9);const a=new TN();return e.state=a,a.strm=e,a.status=$O,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=s,a.method=i,CN(e);};var vN=(e,t)=>{if(SN(e)||t>PO||t<0)return e?iN(e,MO):MO;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===tN&&t!==DO)return iN(e,0===e.avail_out?xO:MO);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(aN(e),0===e.avail_out)return i.last_flush=-1,LO;}else if(0===e.avail_in&&nN(t)<=nN(n)&&t!==DO)return iN(e,xO);if(i.status===tN&&0!==e.avail_in)return iN(e,xO);if(i.status===$O&&0===i.wrap&&(i.status=eN),i.status===$O){let t=KO+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=BO||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,lN(i,t),0!==i.strstart&&(lN(i,e.adler>>>16),lN(i,65535&e.adler)),e.adler=1,i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;}if(57===i.status)if(e.adler=0,dN(i,31),dN(i,139),dN(i,8),i.gzhead)dN(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),dN(i,255&i.gzhead.time),dN(i,i.gzhead.time>>8&255),dN(i,i.gzhead.time>>16&255),dN(i,i.gzhead.time>>24&255),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(dN(i,255&i.gzhead.extra.length),dN(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=SO(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,3),i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,aN(e),0!==i.pending)return i.last_flush=-1,LO;t=0,n-=r;}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0;}i.status=73;}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0;}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,dN(i,t);}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0;}i.status=91;}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0;}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,dN(i,t);}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n));}i.status=103;}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(aN(e),0!==i.pending))return i.last_flush=-1,LO;dN(i,255&e.adler),dN(i,e.adler>>8&255),e.adler=0;}if(i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;}if(0!==e.avail_in||0!==i.lookahead||t!==wO&&i.status!==tN){let n=0===i.level?_N(i,t):i.strategy===BO?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(pN(e),0===e.lookahead)){if(t===wO)return 1;break;}if(e.match_length=0,i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;})(i,t):i.strategy===jO?((e,t)=>{let i,n,r,s;const o=e.window;for(;;){if(e.lookahead<=QO){if(pN(e),e.lookahead<=QO&&t===wO)return 1;if(0===e.lookahead)break;}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=o[r],n===o[++r]&&n===o[++r]&&n===o[++r])){s=e.strstart+QO;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&r<s);e.match_length=QO-(s-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=3?(i=AO(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;})(i,t):gN[i.level].func(i,t);if(3!==n&&4!==n||(i.status=tN),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),LO;if(2===n&&(t===OO?bO(i):t!==PO&&(vO(i,0,0,!1),t===NO&&(rN(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),aN(e),0===e.avail_out))return i.last_flush=-1,LO;}return t!==DO?LO:i.wrap<=0?kO:(2===i.wrap?(dN(i,255&e.adler),dN(i,e.adler>>8&255),dN(i,e.adler>>16&255),dN(i,e.adler>>24&255),dN(i,255&e.total_in),dN(i,e.total_in>>8&255),dN(i,e.total_in>>16&255),dN(i,e.total_in>>24&255)):(lN(i,e.adler>>>16),lN(i,65535&e.adler)),aN(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?LO:kO);},yN=(e,t)=>{let i=t.length;if(SN(e))return MO;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==$O||n.lookahead)return MO;if(1===r&&(e.adler=gO(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(rN(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size;}const s=e.avail_in,o=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,pN(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=oN(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++;}while(--t);n.strstart=e,n.lookahead=2,pN(n);}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=o,e.input=a,e.avail_in=s,n.wrap=r,LO;},AN={deflateInit:(e,t)=>IN(e,t,KO,15,8,WO),deflateInit2:IN,deflateReset:CN,deflateResetKeep:RN,deflateSetHeader:(e,t)=>SN(e)||2!==e.state.wrap?MO:(e.state.gzhead=t,LO),deflate:vN,deflateEnd:e=>{if(SN(e))return MO;const t=e.state.status;return e.state=null,t===eN?iN(e,UO):LO;},deflateSetDictionary:yN,deflateInfo:"pako deflate (from Nodeca project)"};const bN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var wN={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)bN(i,t)&&(e[t]=i[t]);}}return e;},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,r=e.length;t<r;t++){let r=e[t];i.set(r,n),n+=r.length;}return i;}};let ON=!0;try{String.fromCharCode.apply(null,new Uint8Array(1));}catch(e){ON=!1;}const NN=new Uint8Array(256);for(let e=0;e<256;e++)NN[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;NN[254]=NN[254]=1;var DN={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r<o;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(a),s=0,r=0;s<a;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t;},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n<i;){let t=e[n++];if(t<128){s[r++]=t;continue;}let o=NN[t];if(o>4)s[r++]=65533,n+=o-1;else {for(t&=2===o?31:3===o?15:7;o>1&&n<i;)t=t<<6|63&e[n++],o--;o>1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t);}}return ((e,t)=>{if(t<65534&&e.subarray&&ON)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i;})(s,r);},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+NN[e[i]]>t?i:t;}};var PN=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;};const LN=Object.prototype.toString,{Z_NO_FLUSH:kN,Z_SYNC_FLUSH:MN,Z_FULL_FLUSH:UN,Z_FINISH:xN,Z_OK:VN,Z_STREAM_END:FN,Z_DEFAULT_COMPRESSION:BN,Z_DEFAULT_STRATEGY:jN,Z_DEFLATED:GN}=CO;function WN(e){this.options=wN.assign({level:BN,method:GN,chunkSize:16384,windowBits:15,memLevel:8,strategy:jN},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new PN(),this.strm.avail_out=0;let i=AN.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==VN)throw new Error(RO[i]);if(t.header&&AN.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?DN.string2buf(t.dictionary):"[object ArrayBuffer]"===LN.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=AN.deflateSetDictionary(this.strm,e),i!==VN)throw new Error(RO[i]);this._dict_set=!0;}}function HN(e,t){const i=new WN(t);if(i.push(e,!0),i.err)throw i.msg||RO[i.err];return i.result;}WN.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return !1;for(s=t===~~t?t:!0===t?xN:kN,"string"==typeof e?i.input=DN.string2buf(e):"[object ArrayBuffer]"===LN.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===MN||s===UN)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else {if(r=AN.deflate(i,s),r===FN)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=AN.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===VN;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break;}else this.onData(i.output);}return !0;},WN.prototype.onData=function(e){this.chunks.push(e);},WN.prototype.onEnd=function(e){e===VN&&(this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};var KN={Deflate:WN,deflate:HN,deflateRaw:function(e,t){return (t=t||{}).raw=!0,HN(e,t);},gzip:function(e,t){return (t=t||{}).gzip=!0,HN(e,t);},constants:CO};const YN=16209;var qN=function(e,t){let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v,y;const A=e.state;i=e.next_in,v=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,u=A.window,h=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<<A.lenbits)-1,f=(1<<A.distbits)-1;e:do{p<15&&(h+=v[i++]<<p,p+=8,h+=v[i++]<<p,p+=8),g=_[h&m];t:for(;;){if(T=g>>>24,h>>>=T,p-=T,T=g>>>16&255,0===T)y[r++]=65535&g;else {if(!(16&T)){if(0==(64&T)){g=_[(65535&g)+(h&(1<<T)-1)];continue t;}if(32&T){A.mode=16191;break e;}e.msg="invalid literal/length code",A.mode=YN;break e;}S=65535&g,T&=15,T&&(p<T&&(h+=v[i++]<<p,p+=8),S+=h&(1<<T)-1,h>>>=T,p-=T),p<15&&(h+=v[i++]<<p,p+=8,h+=v[i++]<<p,p+=8),g=E[h&f];i:for(;;){if(T=g>>>24,h>>>=T,p-=T,T=g>>>16&255,!(16&T)){if(0==(64&T)){g=E[(65535&g)+(h&(1<<T)-1)];continue i;}e.msg="invalid distance code",A.mode=YN;break e;}if(R=65535&g,T&=15,p<T&&(h+=v[i++]<<p,p+=8,p<T&&(h+=v[i++]<<p,p+=8)),R+=h&(1<<T)-1,R>a){e.msg="invalid distance too far back",A.mode=YN;break e;}if(h>>>=T,p-=T,T=r-s,R>T){if(T=R-T,T>d&&A.sane){e.msg="invalid distance too far back",A.mode=YN;break e;}if(C=0,I=u,0===l){if(C+=c-T,T<S){S-=T;do{y[r++]=u[C++];}while(--T);C=r-R,I=y;}}else if(l<T){if(C+=c+l-T,T-=l,T<S){S-=T;do{y[r++]=u[C++];}while(--T);if(C=0,l<S){T=l,S-=T;do{y[r++]=u[C++];}while(--T);C=r-R,I=y;}}}else if(C+=l-T,T<S){S-=T;do{y[r++]=u[C++];}while(--T);C=r-R,I=y;}for(;S>2;)y[r++]=I[C++],y[r++]=I[C++],y[r++]=I[C++],S-=3;S&&(y[r++]=I[C++],S>1&&(y[r++]=I[C++]));}else {C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],S-=3;}while(S>2);S&&(y[r++]=y[C++],S>1&&(y[r++]=y[C++]));}break;}}break;}}while(i<n&&r<o);S=p>>3,i-=S,p-=S<<3,h&=(1<<p)-1,e.next_in=i,e.next_out=r,e.avail_in=i<n?n-i+5:5-(i-n),e.avail_out=r<o?o-r+257:257-(r-o),A.hold=h,A.bits=p;};const zN=15,JN=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),XN=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),QN=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ZN=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var $N=(e,t,i,n,r,s,o,a)=>{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,T=0,S=0,R=0,C=0,I=0,v=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=zN;E++)A[E]=0;for(m=0;m<n;m++)A[t[i+m]]++;for(T=c,g=zN;g>=1&&0===A[g];g--);if(T>g&&(T=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f<g&&0===A[f];f++);for(T<f&&(T=f),C=1,E=1;E<=zN;E++)if(C<<=1,C-=A[E],C<0)return -1;if(C>0&&(0===e||1!==g))return -1;for(b[1]=0,E=1;E<zN;E++)b[E+1]=b[E]+A[E];for(m=0;m<n;m++)0!==t[i+m]&&(o[b[t[i+m]]++]=m);if(0===e?(y=D=o,_=20):1===e?(y=JN,D=XN,_=257):(y=QN,D=ZN,_=0),v=0,m=0,E=f,p=s,S=T,R=0,u=-1,I=1<<T,h=I-1,1===e&&I>852||2===e&&I>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<S,f=l;do{l-=d,r[p+(v>>R)+l]=w<<24|O<<16|N|0;}while(0!==l);for(d=1<<E-1;v&d;)d>>=1;if(0!==d?(v&=d-1,v+=d):v=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]];}if(E>T&&(v&h)!==u){for(0===R&&(R=T),p+=f,S=E-R,C=1<<S;S+R<g&&(C-=A[S+R],!(C<=0));)S++,C<<=1;if(I+=1<<S,1===e&&I>852||2===e&&I>592)return 1;u=v&h,r[u]=T<<24|S<<16|p-s|0;}}return 0!==v&&(r[p+v]=E-R<<24|64<<16|0),a.bits=T,0;};const{Z_FINISH:eD,Z_BLOCK:tD,Z_TREES:iD,Z_OK:nD,Z_STREAM_END:rD,Z_NEED_DICT:sD,Z_STREAM_ERROR:oD,Z_DATA_ERROR:aD,Z_MEM_ERROR:cD,Z_BUF_ERROR:dD,Z_DEFLATED:lD}=CO,uD=16180,hD=16190,pD=16191,_D=16192,ED=16194,mD=16199,fD=16200,gD=16206,TD=16209,SD=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function RD(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}const CD=e=>{if(!e)return 1;const t=e.state;return !t||t.strm!==e||t.mode<uD||t.mode>16211?1:0;},ID=e=>{if(CD(e))return oD;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=uD,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,nD;},vD=e=>{if(CD(e))return oD;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,ID(e);},yD=(e,t)=>{let i;if(CD(e))return oD;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?oD:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,vD(e));},AD=(e,t)=>{if(!e)return oD;const i=new RD();e.state=i,i.strm=e,i.window=null,i.mode=uD;const n=yD(e,t);return n!==nD&&(e.state=null),n;};let bD,wD,OD=!0;const ND=e=>{if(OD){bD=new Int32Array(512),wD=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for($N(1,e.lens,0,288,bD,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;$N(2,e.lens,0,32,wD,0,e.work,{bits:5}),OD=!1;}e.lencode=bD,e.lenbits=9,e.distcode=wD,e.distbits=5;},DD=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0;};var PD=(e,t)=>{let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(CD(e)||!e.output||!e.input&&0!==e.avail_in)return oD;i=e.state,i.mode===pD&&(i.mode=_D),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,I=nD;e:for(;;)switch(i.mode){case uD:if(0===i.wrap){i.mode=_D;break;}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(2&i.wrap&&35615===d){0===i.wbits&&(i.wbits=15),i.check=0,y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0),d=0,l=0,i.mode=16181;break;}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=TD;break;}if((15&d)!==lD){e.msg="unknown compression method",i.mode=TD;break;}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg="invalid window size",i.mode=TD;break;}i.dmax=1<<i.wbits,i.flags=0,e.adler=i.check=1,i.mode=512&d?16189:pD,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(i.flags=d,(255&i.flags)!==lD){e.msg="unknown compression method",i.mode=TD;break;}if(57344&i.flags){e.msg="unknown header flags set",i.mode=TD;break;}i.head&&(i.head.text=d>>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.head&&(i.head.time=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=SO(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.head&&(i.head.xflags=255&d,i.head.os=d>>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.length=d,i.head&&(i.head.extra_len=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0;}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C));}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,C)break e;}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.comment+=String.fromCharCode(C));}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,C)break e;}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(4&i.wrap&&d!==(65535&i.check)){e.msg="header crc mismatch",i.mode=TD;break;}d=0,l=0;}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=pD;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}e.adler=i.check=SD(d),d=0,l=0,i.mode=hD;case hD:if(0===i.havedict)return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,sD;e.adler=i.check=1,i.mode=pD;case pD:if(t===tD||t===iD)break e;case _D:if(i.last){d>>>=7&l,l-=7&l,i.mode=gD;break;}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}switch(i.last=1&d,d>>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(ND(i),i.mode=mD,t===iD){d>>>=2,l-=2;break e;}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=TD;}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",i.mode=TD;break;}if(i.length=65535&d,d=0,l=0,i.mode=ED,t===iD)break e;case ED:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break;}i.mode=pD;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(i.nlen=257+(31&d),d>>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=TD;break;}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.lens[w[i.have++]]=7&d,d>>>=3,l-=3;}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},I=$N(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid code lengths set",i.mode=TD;break;}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;v=i.lencode[d&(1<<i.lenbits)-1],m=v>>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(g<16)d>>>=m,l-=m,i.lens[i.have++]=g;else {if(16===g){for(b=m+2;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(d>>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=TD;break;}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2;}else if(17===g){for(b=m+3;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}d>>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3;}else {for(b=m+7;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}d>>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7;}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=TD;break;}for(;p--;)i.lens[i.have++]=C;}}if(i.mode===TD)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=TD;break;}if(i.lenbits=9,A={bits:i.lenbits},I=$N(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid literal/lengths set",i.mode=TD;break;}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},I=$N(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,I){e.msg="invalid distances set",i.mode=TD;break;}if(i.mode=mD,t===iD)break e;case mD:i.mode=fD;case fD:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,qN(e,h),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===pD&&(i.back=-1);break;}for(i.back=0;v=i.lencode[d&(1<<i.lenbits)-1],m=v>>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(f&&0==(240&f)){for(T=m,S=f,R=g;v=i.lencode[R+((d&(1<<T+S)-1)>>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}d>>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break;}if(32&f){i.back=-1,i.mode=pD;break;}if(64&f){e.msg="invalid literal/length code",i.mode=TD;break;}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.length+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra;}i.was=i.length,i.mode=16202;case 16202:for(;v=i.distcode[d&(1<<i.distbits)-1],m=v>>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(0==(240&f)){for(T=m,S=f,R=g;v=i.distcode[R+((d&(1<<T+S)-1)>>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}d>>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=TD;break;}i.offset=g,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}i.offset+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra;}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=TD;break;}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=TD;break;}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window;}else E=r,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++];}while(--p);0===i.length&&(i.mode=fD);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=fD;break;case gD:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<<l,l+=8;}if(h-=c,e.total_out+=h,i.total+=h,4&i.wrap&&h&&(e.adler=i.check=i.flags?SO(i.check,r,h,o-h):gO(i.check,r,h,o-h)),h=c,4&i.wrap&&(i.flags?d:SD(d))!==i.check){e.msg="incorrect data check",i.mode=TD;break;}d=0,l=0;}i.mode=16207;case 16207:if(i.wrap&&i.flags){for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8;}if(4&i.wrap&&d!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=TD;break;}d=0,l=0;}i.mode=16208;case 16208:I=rD;break e;case TD:I=aD;break e;case 16210:return cD;default:return oD;}return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,(i.wsize||h!==e.avail_out&&i.mode<TD&&(i.mode<gD||t!==eD))&&DD(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,i.total+=h,4&i.wrap&&h&&(e.adler=i.check=i.flags?SO(i.check,r,h,e.next_out-h):gO(i.check,r,h,e.next_out-h)),e.data_type=i.bits+(i.last?64:0)+(i.mode===pD?128:0)+(i.mode===mD||i.mode===ED?256:0),(0===u&&0===h||t===eD)&&I===nD&&(I=dD),I;},LD={inflateReset:vD,inflateReset2:yD,inflateResetKeep:ID,inflateInit:e=>AD(e,15),inflateInit2:AD,inflate:PD,inflateEnd:e=>{if(CD(e))return oD;let t=e.state;return t.window&&(t.window=null),e.state=null,nD;},inflateGetHeader:(e,t)=>{if(CD(e))return oD;const i=e.state;return 0==(2&i.wrap)?oD:(i.head=t,t.done=!1,nD);},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return CD(e)?oD:(n=e.state,0!==n.wrap&&n.mode!==hD?oD:n.mode===hD&&(r=1,r=gO(r,t,i,0),r!==n.check)?aD:(s=DD(e,t,i,i),s?(n.mode=16210,cD):(n.havedict=1,nD)));},inflateInfo:"pako inflate (from Nodeca project)"};var kD=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1;};const MD=Object.prototype.toString,{Z_NO_FLUSH:UD,Z_FINISH:xD,Z_OK:VD,Z_STREAM_END:FD,Z_NEED_DICT:BD,Z_STREAM_ERROR:jD,Z_DATA_ERROR:GD,Z_MEM_ERROR:WD}=CO;function HD(e){this.options=wN.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new PN(),this.strm.avail_out=0;let i=LD.inflateInit2(this.strm,t.windowBits);if(i!==VD)throw new Error(RO[i]);if(this.header=new kD(),LD.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=DN.string2buf(t.dictionary):"[object ArrayBuffer]"===MD.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=LD.inflateSetDictionary(this.strm,t.dictionary),i!==VD)))throw new Error(RO[i]);}function KD(e,t){const i=new HD(t);if(i.push(e),i.err)throw i.msg||RO[i.err];return i.result;}HD.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return !1;for(o=t===~~t?t:!0===t?xD:UD,"[object ArrayBuffer]"===MD.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=LD.inflate(i,o),s===BD&&r&&(s=LD.inflateSetDictionary(i,r),s===VD?s=LD.inflate(i,o):s===GD&&(s=BD));i.avail_in>0&&s===FD&&i.state.wrap>0&&0!==e[i.next_in];)LD.inflateReset(i),s=LD.inflate(i,o);switch(s){case jD:case GD:case BD:case WD:return this.onEnd(s),this.ended=!0,!1;}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===FD))if("string"===this.options.to){let e=DN.utf8border(i.output,i.next_out),t=i.next_out-e,r=DN.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r);}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==VD||0!==a){if(s===FD)return s=LD.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break;}}return !0;},HD.prototype.onData=function(e){this.chunks.push(e);},HD.prototype.onEnd=function(e){e===VD&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};var YD={Inflate:HD,inflate:KD,inflateRaw:function(e,t){return (t=t||{}).raw=!0,KD(e,t);},ungzip:KD,constants:CO};const{Deflate:qD,deflate:zD,deflateRaw:JD,gzip:XD}=KN,{Inflate:QD,inflate:ZD,inflateRaw:$D,ungzip:eP}=YD;var tP,iP=zD,nP=ZD;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE";}(tP||(tP={}));class rP{constructor(){sh(this,"_sequence",0),sh(this,"_startTime",Date.now()),sh(this,"isUseOneByte",!0);}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime);}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence);}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength;}else t.commonPacketHeader.length=8+t.payload.byteLength;RC("SHOW_DATASTREAM2_LOG")&&jC.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength;}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i;}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let s,o;if(i+=4,RC("SHOW_DATASTREAM2_LOG")&&jC.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find(e=>0===e.id);if(e){t=1==(1&new DataView(e.data).getUint32(0,!0));}}s=t?this.decompress(s):s;}else s=e.slice(8);return s;}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach(e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength);}),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r;}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===tP.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,i=new ArrayBuffer(0);s?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i});}if(c!==r)throw Error("parse error");return {profile:n,length:r,datas:o};}decompress(e){return nP(new Uint8Array(e));}compress(e){return iP(new Uint8Array(e));}}class sP extends dT{constructor(e,t){super(),sh(this,"_version",1),sh(this,"_type",3),sh(this,"_config",void 0),sh(this,"_originDataChannel",void 0),sh(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),sh(this,"_dataStreamPacketHandler",void 0),sh(this,"_datachannelEventMap",new Map()),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new rP();}get id(){return this._config.id;}get ordered(){return this._config.ordered;}get maxRetransmits(){return RC("DATASTREAM_MAX_RETRANSMITS");}get metadata(){return this._config.metadata;}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting";}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null;}getChannelId(){return this.id;}getConfig(){return this._config;}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0);}async _waitTillOpen(){return new cg((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout(()=>{var e;t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)));},1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e();},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT);};}else t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"));});}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e);}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id);}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[cb.OPEN,cb.CLOSE,cb.ERROR].forEach(t=>{const i=()=>{this.emit(t);};this._datachannelEventMap.set(t,i),e.addEventListener(t,i);});}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach(t=>{let[i,n]=t;e.removeEventListener(i,n);}),this._datachannelEventMap.clear();}}class oP extends sP{constructor(e){super(e),sh(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(t).getUint8(3);if(i!==this.id)return void(RC("SHOW_DATASTREAM2_LOG")&&jC.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let n=e.data.slice(this._dataStreamPacketHeader.byteLength);n=this._dataStreamPacketHandler.deserialize(n),this.emit(cb.MESSAGE,n);};}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents();}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close());}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener);}}class aP extends sP{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer);}}}var cP=n,dP=ht("iterator"),lP=!cP(function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2"),n="";return e.pathname="c%20d",t.forEach(function(e,i){t.delete("b"),n+=i+e;}),i.delete("a",2),!e.toJSON||!i.has("a",1)||i.has("a",2)||!t.size&&true||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[dP]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host;}),uP=Uo,hP=wi,pP=h,_P=L,EP=d,mP=N,fP=lP,gP=Uo,TP=Vo,SP=function(e,t,i){for(var n in t)i&&i.unsafe&&e[n]?e[n]=t[n]:uP(e,n,t[n],i);return e;},RP=ca,CP=Sl,IP=va,vP=k_,yP=w,AP=Ze,bP=Xt,wP=ln,OP=ii,NP=te,DP=pn,PP=go,LP=B,kP=Bp,MP=Lp,UP=H_,xP=Rh,VP=ht("iterator"),FP="URLSearchParams",BP=FP+"Iterator",jP=IP.set,GP=IP.getterFor(FP),WP=IP.getterFor(BP),HP=Object.getOwnPropertyDescriptor,KP=function(e){if(!mP)return pP[e];var t=HP(pP,e);return t&&t.value;},YP=KP("fetch"),qP=KP("Request"),zP=KP("Headers"),JP=qP&&qP.prototype,XP=zP&&zP.prototype,QP=pP.RegExp,ZP=pP.TypeError,$P=pP.decodeURIComponent,eL=pP.encodeURIComponent,tL=EP("".charAt),iL=EP([].join),nL=EP([].push),rL=EP("".replace),sL=EP([].shift),oL=EP([].splice),aL=EP("".split),cL=EP("".slice),dL=/\+/g,lL=Array(4),uL=function(e){return lL[e-1]||(lL[e-1]=QP("((?:%[\\da-f]{2}){"+e+"})","gi"));},hL=function(e){try{return $P(e);}catch(t){return e;}},pL=function(e){var t=rL(e,dL," "),i=4;try{return $P(t);}catch(e){for(;i;)t=rL(t,uL(i--),hL);return t;}},_L=/[!'()~]|%20/g,EL={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},mL=function(e){return EL[e];},fL=function(e){return rL(eL(e),_L,mL);},gL=CP(function(e,t){jP(this,{type:BP,iterator:kP(GP(e).entries),kind:t});},"Iterator",function(){var e=WP(this),t=e.kind,i=e.iterator.next(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.value]),i;},!0),TL=function(e){this.entries=[],this.url=null,void 0!==e&&(NP(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===tL(e,0)?cL(e,1):e:DP(e)));};TL.prototype={type:FP,bindURL:function(e){this.url=e,this.update();},parseObject:function(e){var t,i,n,r,s,o,a,c=MP(e);if(c)for(i=(t=kP(e,c)).next;!(n=_P(i,t)).done;){if(s=(r=kP(OP(n.value))).next,(o=_P(s,r)).done||(a=_P(s,r)).done||!_P(s,r).done)throw ZP("Expected sequence with length 2");nL(this.entries,{key:DP(o.value),value:DP(a.value)});}else for(var d in e)AP(e,d)&&nL(this.entries,{key:d,value:DP(e[d])});},parseQuery:function(e){if(e)for(var t,i,n=aL(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=aL(t,"="),nL(this.entries,{key:pL(sL(i)),value:pL(iL(i,"="))}));},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],nL(i,fL(e.key)+"="+fL(e.value));return iL(i,"&");},update:function(){this.entries.length=0,this.parseQuery(this.url.query);},updateURL:function(){this.url&&this.url.update();}};var SL=function(){vP(this,RL);var e=jP(this,new TL(arguments.length>0?arguments[0]:void 0));mP||(this.size=e.entries.length);},RL=SL.prototype;if(SP(RL,{append:function(e,t){var i=GP(this);UP(arguments.length,2),nL(i.entries,{key:DP(e),value:DP(t)}),mP||this.length++,i.updateURL();},delete:function(e){for(var t=GP(this),i=UP(arguments.length,1),n=t.entries,r=DP(e),s=i<2?void 0:arguments[1],o=void 0===s?s:DP(s),a=0;a<n.length;){var c=n[a];if(c.key!==r||void 0!==o&&c.value!==o)a++;else if(oL(n,a,1),void 0!==o)break;}mP||(this.size=n.length),t.updateURL();},get:function(e){var t=GP(this).entries;UP(arguments.length,1);for(var i=DP(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null;},getAll:function(e){var t=GP(this).entries;UP(arguments.length,1);for(var i=DP(e),n=[],r=0;r<t.length;r++)t[r].key===i&&nL(n,t[r].value);return n;},has:function(e){for(var t=GP(this).entries,i=UP(arguments.length,1),n=DP(e),r=i<2?void 0:arguments[1],s=void 0===r?r:DP(r),o=0;o<t.length;){var a=t[o++];if(a.key===n&&(void 0===s||a.value===s))return !0;}return !1;},set:function(e,t){var i=GP(this);UP(arguments.length,1);for(var n,r=i.entries,s=!1,o=DP(e),a=DP(t),c=0;c<r.length;c++)(n=r[c]).key===o&&(s?oL(r,c--,1):(s=!0,n.value=a));s||nL(r,{key:o,value:a}),mP||(this.size=r.length),i.updateURL();},sort:function(){var e=GP(this);xP(e.entries,function(e,t){return e.key>t.key?1:-1;}),e.updateURL();},forEach:function(e){for(var t,i=GP(this).entries,n=bP(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this);},keys:function(){return new gL(this,"keys");},values:function(){return new gL(this,"values");},entries:function(){return new gL(this,"entries");}},{enumerable:!0}),gP(RL,VP,RL.entries,{name:"entries"}),gP(RL,"toString",function(){return GP(this).serialize();},{enumerable:!0}),mP&&TP(RL,"size",{get:function(){return GP(this).entries.length;},configurable:!0,enumerable:!0}),RP(SL,FP),hP({global:!0,constructor:!0,forced:!fP},{URLSearchParams:SL}),!fP&&yP(zP)){var CL=EP(XP.has),IL=EP(XP.set),vL=function(e){if(NP(e)){var t,i=e.body;if(wP(i)===FP)return t=e.headers?new zP(e.headers):new zP(),CL(t,"content-type")||IL(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),PP(e,{body:LP(0,DP(i)),headers:LP(0,t)});}return e;};if(yP(YP)&&hP({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return YP(e,arguments.length>1?vL(arguments[1]):{});}}),yP(qP)){var yL=function(e){return vP(this,JP),new qP(e,arguments.length>1?vL(arguments[1]):{});};JP.constructor=yL,yL.prototype=JP,hP({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:yL});}}var AL,bL={URLSearchParams:SL,getState:GP},wL=N,OL=d,NL=L,DL=n,PL=Ys,LL=ko,kL=k,ML=Je,UL=K,xL=Object.assign,VL=Object.defineProperty,FL=OL([].concat),BL=!xL||DL(function(){if(wL&&1!==xL({b:1},xL(VL({},"a",{enumerable:!0,get:function(){VL(this,"b",{value:3,enumerable:!1});}}),{b:2})).b)return !0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach(function(e){t[e]=e;}),7!=xL({},e)[i]||PL(xL({},t)).join("")!=n;})?function(e,t){for(var i=ML(e),n=arguments.length,r=1,s=LL.f,o=kL.f;n>r;)for(var a,c=UL(arguments[r++]),d=s?FL(PL(c),s(c)):PL(c),l=d.length,u=0;l>u;)a=d[u++],wL&&!NL(o,c,a)||(i[a]=c[a]);return i;}:xL,jL=ii,GL=Hp,WL=Xt,HL=L,KL=Je,YL=function(e,t,i,n){try{return n?t(jL(i)[0],i[1]):t(i);}catch(t){GL(e,"throw",t);}},qL=bp,zL=ls,JL=Bi,XL=Yr,QL=Bp,ZL=Lp,$L=Array,ek=d,tk=2147483647,ik=/[^\0-\u007E]/,nk=/[.\u3002\uFF0E\uFF61]/g,rk="Overflow: input needs wider integers to process",sk=RangeError,ok=ek(nk.exec),ak=Math.floor,ck=String.fromCharCode,dk=ek("".charCodeAt),lk=ek([].join),uk=ek([].push),hk=ek("".replace),pk=ek("".split),_k=ek("".toLowerCase),Ek=function(e){return e+22+75*(e<26);},mk=function(e,t,i){var n=0;for(e=i?ak(e/700):e>>1,e+=ak(e/t);e>455;)e=ak(e/35),n+=36;return ak(n+36*e/(e+38));},fk=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=dk(e,i++);if(r>=55296&&r<=56319&&i<n){var s=dk(e,i++);56320==(64512&s)?uk(t,((1023&r)<<10)+(1023&s)+65536):(uk(t,r),i--);}else uk(t,r);}return t;}(e);var i,n,r=e.length,s=128,o=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&uk(t,ck(n));var c=t.length,d=c;for(c&&uk(t,"-");d<r;){var l=tk;for(i=0;i<e.length;i++)(n=e[i])>=s&&n<l&&(l=n);var u=d+1;if(l-s>ak((tk-o)/u))throw sk(rk);for(o+=(l-s)*u,s=l,i=0;i<e.length;i++){if((n=e[i])<s&&++o>tk)throw sk(rk);if(n==s){for(var h=o,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;uk(t,ck(Ek(_+E%m))),h=ak(E/m),p+=36;}uk(t,ck(Ek(h))),a=mk(o,u,d==c),o=0,d++;}}o++,s++;}return lk(t,"");},gk=wi,Tk=N,Sk=lP,Rk=h,Ck=Xt,Ik=d,vk=Uo,yk=Vo,Ak=k_,bk=Ze,wk=BL,Ok=function(e){var t=KL(e),i=zL(this),n=arguments.length,r=n>1?arguments[1]:void 0,s=void 0!==r;s&&(r=WL(r,n>2?arguments[2]:void 0));var o,a,c,d,l,u,h=ZL(t),p=0;if(!h||this===$L&&qL(h))for(o=JL(t),a=i?new this(o):$L(o);o>p;p++)u=s?r(t[p],p):t[p],XL(a,p,u);else for(l=(d=QL(t,h)).next,a=i?new this():[];!(c=HL(l,d)).done;p++)u=s?YL(d,r,[c.value,p],!0):c.value,XL(a,p,u);return a.length=p,a;},Nk=wo,Dk=Yu.codeAt,Pk=function(e){var t,i,n=[],r=pk(hk(_k(e),nk,"."),".");for(t=0;t<r.length;t++)i=r[t],uk(n,ok(ik,i)?"xn--"+fk(i):i);return lk(n,".");},Lk=pn,kk=ca,Mk=H_,Uk=bL,xk=va,Vk=xk.set,Fk=xk.getterFor("URL"),Bk=Uk.URLSearchParams,jk=Uk.getState,Gk=Rk.URL,Wk=Rk.TypeError,Hk=Rk.parseInt,Kk=Math.floor,Yk=Math.pow,qk=Ik("".charAt),zk=Ik(/./.exec),Jk=Ik([].join),Xk=Ik(1..toString),Qk=Ik([].pop),Zk=Ik([].push),$k=Ik("".replace),eM=Ik([].shift),tM=Ik("".split),iM=Ik("".slice),nM=Ik("".toLowerCase),rM=Ik([].unshift),sM="Invalid scheme",oM="Invalid host",aM="Invalid port",cM=/[a-z]/i,dM=/[\d+-.a-z]/i,lM=/\d/,uM=/^0x/i,hM=/^[0-7]+$/,pM=/^\d+$/,_M=/^[\da-f]+$/i,EM=/[\0\t\n\r #%/:<>?@[\\\]^|]/,mM=/[\0\t\n\r #/:<>?@[\\\]^|]/,fM=/^[\u0000-\u0020]+/,gM=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,TM=/[\t\n\r]/g,SM=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)rM(t,e%256),e=Kk(e/256);return Jk(t,".");}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,s=0;s<8;s++)0!==e[s]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=s),++r);return r>i&&(t=n,i=r),t;}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=Xk(e[i],16),i<7&&(t+=":")));return "["+t+"]";}return e;},RM={},CM=wk({},RM,{" ":1,'"':1,"<":1,">":1,"`":1}),IM=wk({},CM,{"#":1,"?":1,"{":1,"}":1}),vM=wk({},IM,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),yM=function(e,t){var i=Dk(e,0);return i>32&&i<127&&!bk(t,e)?e:encodeURIComponent(e);},AM={ftp:21,file:null,http:80,https:443,ws:80,wss:443},bM=function(e,t){var i;return 2==e.length&&zk(cM,qk(e,0))&&(":"==(i=qk(e,1))||!t&&"|"==i);},wM=function(e){var t;return e.length>1&&bM(iM(e,0,2))&&(2==e.length||"/"===(t=qk(e,2))||"\\"===t||"?"===t||"#"===t);},OM=function(e){return "."===e||"%2e"===nM(e);},NM={},DM={},PM={},LM={},kM={},MM={},UM={},xM={},VM={},FM={},BM={},jM={},GM={},WM={},HM={},KM={},YM={},qM={},zM={},JM={},XM={},QM=function(e,t,i){var n,r,s,o=Lk(e);if(t){if(r=this.parse(o))throw Wk(r);this.searchParams=null;}else {if(void 0!==i&&(n=new QM(i,!0)),r=this.parse(o,null,n))throw Wk(r);(s=jk(new Bk())).bindURL(this),this.searchParams=s;}};QM.prototype={type:"URL",parse:function(e,t,i){var n,r,s,o,a,c=this,d=t||NM,l=0,u="",h=!1,p=!1,_=!1;for(e=Lk(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=$k(e,fM,""),e=$k(e,gM,"$1")),e=$k(e,TM,""),n=Ok(e);l<=n.length;){switch(r=n[l],d){case NM:if(!r||!zk(cM,r)){if(t)return sM;d=PM;continue;}u+=nM(r),d=DM;break;case DM:if(r&&(zk(dM,r)||"+"==r||"-"==r||"."==r))u+=nM(r);else {if(":"!=r){if(t)return sM;u="",d=PM,l=0;continue;}if(t&&(c.isSpecial()!=bk(AM,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&AM[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=WM:c.isSpecial()&&i&&i.scheme==c.scheme?d=LM:c.isSpecial()?d=xM:"/"==n[l+1]?(d=kM,l++):(c.cannotBeABaseURL=!0,Zk(c.path,""),d=zM);}break;case PM:if(!i||i.cannotBeABaseURL&&"#"!=r)return sM;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=Nk(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=XM;break;}d="file"==i.scheme?WM:MM;continue;case LM:if("/"!=r||"/"!=n[l+1]){d=MM;continue;}d=VM,l++;break;case kM:if("/"==r){d=FM;break;}d=qM;continue;case MM:if(c.scheme=i.scheme,r==AL)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=UM;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.path.length--,d=qM;continue;}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}break;case UM:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=qM;continue;}d=FM;}else d=VM;break;case xM:if(d=VM,"/"!=r||"/"!=qk(u,l+1))continue;l++;break;case VM:if("/"!=r&&"\\"!=r){d=FM;continue;}break;case FM:if("@"==r){h&&(u="%40"+u),h=!0,s=Ok(u);for(var E=0;E<s.length;E++){var m=s[E];if(":"!=m||_){var f=yM(m,vM);_?c.password+=f:c.username+=f;}else _=!0;}u="";}else if(r==AL||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return "Invalid authority";l-=Ok(u).length+1,u="",d=BM;}else u+=r;break;case BM:case jM:if(t&&"file"==c.scheme){d=KM;continue;}if(":"!=r||p){if(r==AL||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return oM;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(u))return o;if(u="",d=YM,t)return;continue;}"["==r?p=!0:"]"==r&&(p=!1),u+=r;}else {if(""==u)return oM;if(o=c.parseHost(u))return o;if(u="",d=GM,t==jM)return;}break;case GM:if(!zk(lM,r)){if(r==AL||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var g=Hk(u,10);if(g>65535)return aM;c.port=c.isSpecial()&&g===AM[c.scheme]?null:g,u="";}if(t)return;d=YM;continue;}return aM;}u+=r;break;case WM:if(c.scheme="file","/"==r||"\\"==r)d=HM;else {if(!i||"file"!=i.scheme){d=qM;continue;}if(r==AL)c.host=i.host,c.path=Nk(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){wM(Jk(Nk(n,l),""))||(c.host=i.host,c.path=Nk(i.path),c.shortenPath()),d=qM;continue;}c.host=i.host,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}}break;case HM:if("/"==r||"\\"==r){d=KM;break;}i&&"file"==i.scheme&&!wM(Jk(Nk(n,l),""))&&(bM(i.path[0],!0)?Zk(c.path,i.path[0]):c.host=i.host),d=qM;continue;case KM:if(r==AL||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&bM(u))d=qM;else if(""==u){if(c.host="",t)return;d=YM;}else {if(o=c.parseHost(u))return o;if("localhost"==c.host&&(c.host=""),t)return;u="",d=YM;}continue;}u+=r;break;case YM:if(c.isSpecial()){if(d=qM,"/"!=r&&"\\"!=r)continue;}else if(t||"?"!=r){if(t||"#"!=r){if(r!=AL&&(d=qM,"/"!=r))continue;}else c.fragment="",d=XM;}else c.query="",d=JM;break;case qM:if(r==AL||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=nM(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,"")):OM(u)?"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,""):("file"==c.scheme&&!c.path.length&&bM(u)&&(c.host&&(c.host=""),u=qk(u,0)+":"),Zk(c.path,u)),u="","file"==c.scheme&&(r==AL||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)eM(c.path);"?"==r?(c.query="",d=JM):"#"==r&&(c.fragment="",d=XM);}else u+=yM(r,IM);break;case zM:"?"==r?(c.query="",d=JM):"#"==r?(c.fragment="",d=XM):r!=AL&&(c.path[0]+=yM(r,RM));break;case JM:t||"#"!=r?r!=AL&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":yM(r,RM)):(c.fragment="",d=XM);break;case XM:r!=AL&&(c.fragment+=yM(r,CM));}l++;}},parseHost:function(e){var t,i,n;if("["==qk(e,0)){if("]"!=qk(e,e.length-1))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return qk(e,u);};if(":"==h()){if(":"!=qk(e,1))return;u+=2,l=++d;}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&zk(_M,h());)t=16*t+Hk(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++;}if(!zk(lM,h()))return;for(;zk(lM,h());){if(s=Hk(h(),10),null===r)r=s;else {if(0==r)return;r=10*r+s;}if(r>255)return;u++;}c[d]=256*c[d]+r,2!=++n&&4!=n||d++;}if(4!=n)return;break;}if(":"==h()){if(u++,!h())return;}else if(h())return;c[d++]=t;}else {if(null!==l)return;u++,l=++d;}}if(null!==l)for(o=d-l,d=7;0!=d&&o>0;)a=c[d],c[d--]=c[l+o-1],c[l+--o]=a;else if(8!=d)return;return c;}(iM(e,1,-1)),!t)return oM;this.host=t;}else if(this.isSpecial()){if(e=Pk(e),zk(EM,e))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=tM(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(s=10,r.length>1&&"0"==qk(r,0)&&(s=zk(uM,r)?16:8,r=iM(r,8==s?1:2)),""===r)o=0;else {if(!zk(10==s?pM:8==s?hM:_M,r))return e;o=Hk(r,s);}Zk(i,o);}for(n=0;n<t;n++)if(o=i[n],n==t-1){if(o>=Yk(256,5-t))return null;}else if(o>255)return null;for(a=Qk(i),n=0;n<i.length;n++)a+=i[n]*Yk(256,3-n);return a;}(e),null===t)return oM;this.host=t;}else {if(zk(mM,e))return oM;for(t="",i=Ok(e),n=0;n<i.length;n++)t+=yM(i[n],RM);this.host=t;}},cannotHaveUsernamePasswordPort:function(){return !this.host||this.cannotBeABaseURL||"file"==this.scheme;},includesCredentials:function(){return ""!=this.username||""!=this.password;},isSpecial:function(){return bk(AM,this.scheme);},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&bM(e[0],!0)||e.length--;},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,s=e.port,o=e.path,a=e.query,c=e.fragment,d=t+":";return null!==r?(d+="//",e.includesCredentials()&&(d+=i+(n?":"+n:"")+"@"),d+=SM(r),null!==s&&(d+=":"+s)):"file"==t&&(d+="//"),d+=e.cannotBeABaseURL?o[0]:o.length?"/"+Jk(o,"/"):"",null!==a&&(d+="?"+a),null!==c&&(d+="#"+c),d;},setHref:function(e){var t=this.parse(e);if(t)throw Wk(t);this.searchParams.update();},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new ZM(e.path[0]).origin;}catch(e){return "null";}return "file"!=e&&this.isSpecial()?e+"://"+SM(this.host)+(null!==t?":"+t:""):"null";},getProtocol:function(){return this.scheme+":";},setProtocol:function(e){this.parse(Lk(e)+":",NM);},getUsername:function(){return this.username;},setUsername:function(e){var t=Ok(Lk(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=yM(t[i],vM);}},getPassword:function(){return this.password;},setPassword:function(e){var t=Ok(Lk(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=yM(t[i],vM);}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?SM(e):SM(e)+":"+t;},setHost:function(e){this.cannotBeABaseURL||this.parse(e,BM);},getHostname:function(){var e=this.host;return null===e?"":SM(e);},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,jM);},getPort:function(){var e=this.port;return null===e?"":Lk(e);},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=Lk(e))?this.port=null:this.parse(e,GM));},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Jk(e,"/"):"";},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,YM));},getSearch:function(){var e=this.query;return e?"?"+e:"";},setSearch:function(e){""==(e=Lk(e))?this.query=null:("?"==qk(e,0)&&(e=iM(e,1)),this.query="",this.parse(e,JM)),this.searchParams.update();},getSearchParams:function(){return this.searchParams.facade;},getHash:function(){var e=this.fragment;return e?"#"+e:"";},setHash:function(e){""!=(e=Lk(e))?("#"==qk(e,0)&&(e=iM(e,1)),this.fragment="",this.parse(e,XM)):this.fragment=null;},update:function(){this.query=this.searchParams.serialize()||null;}};var ZM=function(e){var t=Ak(this,$M),i=Mk(arguments.length,1)>1?arguments[1]:void 0,n=Vk(t,new QM(e,!1,i));Tk||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash());},$M=ZM.prototype,eU=function(e,t){return {get:function(){return Fk(this)[e]();},set:t&&function(e){return Fk(this)[t](e);},configurable:!0,enumerable:!0};};if(Tk&&(yk($M,"href",eU("serialize","setHref")),yk($M,"origin",eU("getOrigin")),yk($M,"protocol",eU("getProtocol","setProtocol")),yk($M,"username",eU("getUsername","setUsername")),yk($M,"password",eU("getPassword","setPassword")),yk($M,"host",eU("getHost","setHost")),yk($M,"hostname",eU("getHostname","setHostname")),yk($M,"port",eU("getPort","setPort")),yk($M,"pathname",eU("getPathname","setPathname")),yk($M,"search",eU("getSearch","setSearch")),yk($M,"searchParams",eU("getSearchParams")),yk($M,"hash",eU("getHash","setHash"))),vk($M,"toJSON",function(){return Fk(this).serialize();},{enumerable:!0}),vk($M,"toString",function(){return Fk(this).serialize();},{enumerable:!0}),Gk){var tU=Gk.createObjectURL,iU=Gk.revokeObjectURL;tU&&vk(ZM,"createObjectURL",Ck(tU,Gk)),iU&&vk(ZM,"revokeObjectURL",Ck(iU,Gk));}kk(ZM,"URL"),gk({global:!0,constructor:!0,forced:!Sk,sham:!Tk},{URL:ZM});var nU=wi,rU=n,sU=H_,oU=pn,aU=lP,cU=ae("URL");nU({target:"URL",stat:!0,forced:!(aU&&rU(function(){cU.canParse();}))},{canParse:function(e){var t=sU(arguments.length,1),i=oU(e),n=t<2||void 0===arguments[1]?void 0:oU(arguments[1]);try{return !!new cU(i,n);}catch(e){return !1;}}});var dU=i(ie.URL);function lU(){const e=new Blob([atob("ZnVuY3Rpb24gZShlKXtjb25zdCB0PW5ldyBEYXRhVmlldyhlLmRhdGEpO2lmKDA9PT10LmdldFVpbnQ4KDApJiYwPT09dC5nZXRVaW50OCgxKSYmMD09PXQuZ2V0VWludDgoMikmJjE9PT10LmdldFVpbnQ4KDMpJiY2PT09dC5nZXRVaW50OCg0KSl7bGV0IG49NixyPTAsbz0wO2Zvcig7MjU1PT09KG89dC5nZXRVaW50OChuKyspKTspcis9MjU1O3IrPW87Y29uc3QgYT1mdW5jdGlvbihlLHQsbil7bGV0IHI9bmV3IFVpbnQ4QXJyYXkoZSx0LG4pLG89W10sYT0wO2Zvcig7YTxuOylhKzM8biYmMD09PXJbYV0mJjA9PT1yW2ErMV0mJjM9PT1yW2ErMl0mJigwPT09clthKzNdfHwxPT09clthKzNdfHwyPT09clthKzNdfHwzPT09clthKzNdKT8oby5wdXNoKHJbYV0sclthKzFdLHJbYSszXSksYSs9NCk6KG8ucHVzaChyW2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShvKX0oZS5kYXRhLG4scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfXJldHVybiBudWxsfWZ1bmN0aW9uIHQoZSx0KXtjb25zdCBuPWZ1bmN0aW9uKGUpe2NvbnN0IHQ9ZS5sZW5ndGg7bGV0IG49W10scj0wO2Zvcig7cjx0OylyKzI8dCYmMD09PWVbcl0mJjA9PT1lW3IrMV0mJigwPT09ZVtyKzJdfHwxPT09ZVtyKzJdfHwyPT09ZVtyKzJdfHwzPT09ZVtyKzJdKT8obi5wdXNoKGVbcl0sZVtyKzFdLDMsZVtyKzJdKSxyKz0zKToobi5wdXNoKGVbcl0pLHIrKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KG4pfSh0KSxyPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihyLzI1NSksYT1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK3IrZS5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBpPTA7Zm9yKDtpPG87KXNbNitpXT0yNTUsaSsrO3JldHVybiBzWzYraV09YSxpKysscy5zZXQobiw2K2kpLHMuc2V0KG5ldyBVaW50OEFycmF5KGUpLDYraStyKSxzLmJ1ZmZlcn1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlNhZmFyaSIpPi0xJiYtMT09PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiQ2hyb21lIikmJihzZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXI7bGV0IG89W107ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPWU9PntlLmRhdGEuc2VpJiZvLnB1c2goZS5kYXRhLnNlaSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBhPXIucmVhZGFibGUuZ2V0UmVhZGVyKCkscz1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJyeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2EucmVhZCgpLnRoZW4oKHI9PntpZighci5kb25lKXtpZihyLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZShyLnZhbHVlKTt0JiZuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOnR9KX1zLndyaXRlKHIudmFsdWUpLG4ub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQobil9fSkpfShyKToidHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIGUobil7YS5yZWFkKCkudGhlbigocj0+e2lmKCFyLmRvbmUpe2lmKHIudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgZT1vLnNoaWZ0KCk7ZSYmKHIudmFsdWUuZGF0YT10KHIudmFsdWUuZGF0YSxlKSl9cy53cml0ZShyLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0ocil9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKSk7Cg==")],{type:"text/javascript"});return setTimeout(()=>dU.revokeObjectURL(e),0),new Worker(dU.createObjectURL(e));}const uU=new Map();const hU=new Map();async function pU(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(hU.has(e))return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.error("create audio-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n);}});n.readable.pipeThrough(r).pipeTo(n.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>n.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i));},t.worker=n;}function i(){e.track.removeEventListener("ended",i),function(e){const t=hU.get(e);if(t){hU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate();}catch(e){jC.warning(e&&e.message);}}}(e);}hU.set(e,t),e.track.addEventListener("ended",i);}function _U(e){const t=new DataView(e.data);if(0===t.getUint8(0)&&0===t.getUint8(1)&&0===t.getUint8(2)&&1===t.getUint8(3)&&6===t.getUint8(4)){let i=6,n=0,r=0;for(;255===(r=t.getUint8(i++));)n+=255;n+=r;const s=function(e,t,i){let n=new Uint8Array(e,t,i),r=[],s=0;for(;s<i;)s+3<i&&0===n[s]&&0===n[s+1]&&3===n[s+2]&&(0===n[s+3]||1===n[s+3]||2===n[s+3]||3===n[s+3])?(r.push(n[s],n[s+1],n[s+3]),s+=4):(r.push(n[s]),s++);return new Uint8Array(r);}(e.data,i,n);return new Uint8Array(s);}return null;}function EU(e,t){const i=function(e){const t=e.length;let i=[],n=0;for(;n<t;)n+2<t&&0===e[n]&&0===e[n+1]&&(0===e[n+2]||1===e[n+2]||2===e[n+2]||3===e[n+2])?(i.push(e[n],e[n+1],3,e[n+2]),n+=3):(i.push(e[n]),n++);return new Uint8Array(i);}(t),n=i.length,r=Math.floor(n/255),s=n%255,o=new Uint8Array(6+r+1+n+e.byteLength);o[0]=0,o[1]=0,o[2]=0,o[3]=1,o[4]=6,o[5]=101;let a=0;for(;a<r;)o[6+a]=255,a++;return o[6+a]=s,a++,o.set(i,6+a),o.set(new Uint8Array(e),6+a+n),o.buffer;}const mU=new Map();const fU=new Map();async function gU(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(!e.track)return;if(fU.has(e)){const i=fU.get(e);return void(i&&(i.onSei=t.onSei));}const i={track:e.track,onSei:t.onSei};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams();}catch(e){return void jC.error("create video-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const s=_U(t);s&&i.onSei&&i.onSei(s),r.enqueue(t);}});t.readable.pipeThrough(r).pipeTo(t.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const t=lU(),r=new MessageChannel();await new cg(e=>t.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(t,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>t.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei);},i.worker=t;}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n);}!function(e){const t=fU.get(e);if(t){fU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate();}catch(e){jC.warning(e&&e.message);}}}(e);}fU.set(e,i),e.track.addEventListener("ended",n);}!function(){const e=Sg();CA.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return !0;return !1;}(),CA.getStreamFromExtension=e.name===Eg.CHROME&&Number(e.version)>34,CA.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return !1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return !1;const e=new RTCPeerConnection();let t=!1;try{e.addTransceiver("audio"),t=!0;}catch(e){}return e.close(),t;}(),CA.supportMinBitrate=e.name===Eg.CHROME||e.name===Eg.EDGE,CA.supportSetRtpSenderParameters=function(){const e=Sg();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return !1;return !!jg()||!(!bg()&&!Ig())||e.name===Eg.FIREFOX&&Number(e.version)>=64;}(),e.name===Eg.SAFARI&&(Number(e.version)>=14?CA.supportDualStream=!0:CA.supportDualStream=!1),CA.webAudioMediaStreamDest=function(){const e=Sg();if(e.name===Eg.SAFARI&&Number(e.version)<12)return !1;return !0;}(),CA.supportReplaceTrack=function(){if(!window.RTCRtpSender)return !1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return !0;return !1;}(),CA.supportWebGL="undefined"!=typeof WebGLRenderingContext,CA.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,jg()||(CA.webAudioWithAEC=!0),CA.supportShareAudio=function(){const e=Sg();if((e.os===_g.WIN_10||e.os===_g.WIN_81||e.os===_g.WIN_7||e.os===_g.LINUX||e.os===_g.MAC_OS||e.os===_g.CHROMIUM_OS)&&e.name===Eg.CHROME&&Number(e.version)>=74)return !0;return !1;}(),CA.supportDataChannel=function(){if(Ng(76)||function(e){const t=Sg();return !(t.name!==Eg.FIREFOX||!t.osVersion)&&Number(t.version)>=e;}(68)||function(e){const t=Sg();return !(t.name!==Eg.SAFARI||!t.osVersion)&&Number(t.version)>=e;}(14))return !0;return !1;}(),CA.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return !wg()&&!!e&&e.prototype.setConfiguration instanceof Function;}(),CA.supportWebRTCEncodedTransform=function(){const e=Sg();return "Chrome"===e.name&&Number(e.version)>=86||"Safari"===e.name&&Number(e.version)>=15;}(),CA.supportWebRTCInsertableStream=function(){const e=Sg();return (e.name===Eg.CHROME||e.name===Eg.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window;}(),KT(()=>{CA.supportDualStreamEncoding=function(){const e=Sg();if(RC("DISABLE_WEBAUDIO"))return !0;return "Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&RC("CHROME_DUAL_STREAM_USE_ENCODING"));}(),jC.info("browser compatibility",JSON.stringify(CA),JSON.stringify(e));});}();class TU extends dT{constructor(){super(...arguments),sh(this,"resultStorage",new Map());}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t));}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i));}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t));}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t));}record(e,t,i){if(RC("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=bn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",SU[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",SU[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[];}}checkAudioOutputLevel(e){return !(e.receiveBitrate>0&&0===e.receiveLevel);}checkAudioInputLevel(e,t){return t instanceof nw&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel;}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Sy(t._encoderConfig.frameRate));const n=e.captureFrameRate;return !i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1);}checkFramerateSent(e){return !(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1);}checkSendVideoBitrate(e,t){return !!t.muted||0!==e.sendBitrate;}checkSendAudioBitrate(e,t){return t instanceof nw&&!t.isActive||!!t.muted||0!==e.sendBitrate;}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate;}}const SU={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const RU=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t));}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t));}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime);}return 0;}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime);}return 0;}}();function CU(e,t){this.v=e,this.k=t;}function IU(e){return new CU(e,0);}var vU=ag,yU=um;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=yU.f(this);return {promise:e.promise,resolve:e.resolve,reject:e.reject};}});var AU=um,bU=YE;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=AU.f(this),i=bU(e);return (i.error?t.reject:t.resolve)(i.value),t.promise;}});var wU=i(vU),OU=Fo.f("asyncIterator"),NU=i(OU);function DU(e){var t,i;function n(t,i){try{var s=e[t](i),o=s.value,a=o instanceof CU;wU.resolve(a?o.v:o).then(function(i){if(a){var c="return"===t?"return":"next";if(!o.k||i.done)return n(c,i);i=e[c](i).value;}r(s.done?"return":"normal",i);},function(e){n("throw",e);});}catch(e){r("throw",e);}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1});}(t=t.next)?n(t.key,t.arg):i=null;}this._invoke=function(e,r){return new wU(function(s,o){var a={key:e,arg:r,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,n(e,r));});},"function"!=typeof e.return&&(this.return=void 0);}function PU(e){return function(){return new DU(e.apply(this,arguments));};}DU.prototype["function"==typeof xu&&NU||"@@asyncIterator"]=function(){return this;},DU.prototype.next=function(e){return this._invoke("next",e);},DU.prototype.throw=function(e){return this._invoke("throw",e);},DU.prototype.return=function(e){return this._invoke("return",e);};var LU=i(ie.Object.getOwnPropertySymbols),kU=wi,MU=Ki.indexOf,UU=Ih,xU=v([].indexOf),VU=!!xU&&1/xU([1],1,-0)<0;kU({target:"Array",proto:!0,forced:VU||!UU("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return VU?xU(this,e,t)||0:MU(this,e,t);}});var FU=zi("Array").indexOf,BU=l,jU=FU,GU=Array.prototype,WU=i(function(e){var t=e.indexOf;return e===GU||BU(GU,e)&&t===GU.indexOf?jU:t;}),HU=Je,KU=Ys;wi({target:"Object",stat:!0,forced:n(function(){KU(1);})},{keys:function(e){return KU(HU(e));}});var YU=i(ie.Object.keys);function qU(e,t){if(null==e)return {};var i,n,r=function(e,t){if(null==e)return {};var i,n,r={},s=YU(e);for(n=0;n<s.length;n++)i=s[n],WU(t).call(t,i)>=0||(r[i]=e[i]);return r;}(e,t);if(LU){var s=LU(e);for(n=0;n<s.length;n++)i=s[n],WU(t).call(t,i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i]);}return r;}var zU={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),s=" ";let o;function a(e){return e>="0"&&e<="9";}function c(e){return e>="!"&&e<="~";}function d(e){return c(e)||e>="€"&&e<="ÿ";}function l(e){return "!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~";}function u(e){return e>="1"&&e<="9";}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z";}function p(e){return "d"===e||"h"===e||"m"===e||"s"===e;}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ";}function E(e){return h(e)||a(e)||"+"===e||"/"===e;}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e;}function f(e){return h(e)||a(e)||"+"===e||"/"===e;}function g(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function T(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?g(Object(i),!0).forEach(function(t){S(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):g(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function S(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e;}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m";}(o||(o={}));class R{consumeText(e,t){let i=t;for(;i<e.length;){const t=e[i];if("\0"===t||"\r"===t||t===n)break;i+=1;}if(i-t==0)throw new Error("Invalid text, at ".concat(e));return i;}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t,s);}consumeOneOrMore(e,t,i){let n=t;for(;i(e[n]);)n++;if(n-t==0)throw new Error("Invalid rule at ".concat(t,"."));return n;}consumeSpace(e,t){if(e[t]===s)return t+1;throw new Error("Invalid space at ".concat(t,"."));}consumeIP4Address(e,t){let i=t;for(let t=0;t<4;t++)if(i=this.consumeDecimalUChar(e,i),3!==t){if("."!==e[i])throw new Error("Invalid IP4 address.");i++;}return i;}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw new Error("Invalid decimal uchar.");const n=parseInt(e.slice(t,i));if(n>=0&&n<=255)return i;throw new Error("Invalid decimal uchar");}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return ":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i;}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i);}catch(e){}return i;}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i);}catch(e){}return i;}return i;}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i;}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break;}var n;return t+i;}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i;}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d);}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t);}catch(i){return this.consumeExtnAddr(e,t);}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return "/"===e[i]?this.consumeInteger(e,i+1):i;}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i);}return "/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i;}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t;}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t;}consumeToken(e,t){return this.consumeOneOrMore(e,t,l);}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i;}consumeAddress(e,t){return this.consumeTill(e,t,s);}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i;}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t;}consumePort(e,t){return this.consumeOneOrMore(e,t,a);}consume(e,t,i){for(let n=0;n<i.length;n++){if(t+n>=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n));}return t+i.length;}consumeTill(e,t,i){let n=t;for(;n<e.length&&("string"!=typeof i||e[n]!==i)&&("function"!=typeof i||!i(e[n]));)n++;return n;}}class C extends R{constructor(){super(),S(this,"records",[]),S(this,"currentLine",0);}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter(e=>!!e.trim()).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),s=this.parseInformation(),o=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return {version:i,origin:n,sessionName:r,information:s,uri:o,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_};}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e;}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===n)return "\r"===e[t-1]?r:n;throw new Error("Invalid newline character.");}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return {type:i,value:e.slice(2),line:t,cur:0};}parseSessionAttribute(){const e=new v();for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==o.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(t,e=>l(e)&&":"!==e),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++;}return e.digest();}parseMediaAttributes(e){const t=new y(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==o.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(e,e=>l(e)&&":"!==e),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++;}return t.digest();}parseKey(){const e=this.getCurrentRecord();if(e.type===o.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.");}}parseZone(){const e=this.getCurrentRecord();if(e.type===o.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n});}catch(e){break;}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t;}return [];}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++;}}return e;}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime));}catch(e){break;}if(0===t.length)throw new Error("Invalid typed time.");return t;}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i};}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==o.BANDWIDTH)break;{const i=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const n=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:n}),this.currentLine++;}}return e;}parseVersion(){const e=this.getCurrentRecord();if(e.type!==o.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t;}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==o.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const s=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:n,nettype:r,addrtype:s,unicastAddress:c};}parseSessionName(){const e=this.getCurrentRecord();if(e.type===o.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t;}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==o.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t;}parseUri(){const e=this.getCurrentRecord();if(e.type===o.URI)return this.currentLine++,e.value;}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.EMAIL)break;e.push(t.value),this.currentLine++;}return e;}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.PHONE)break;e.push(t.value),this.currentLine++;}return e;}parseConnection(){const e=this.getCurrentRecord();if(e.type===o.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:n};}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,i+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const n=[];for(n.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,n.push(this.extract(e,this.consumeToken));if(0===n.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:n,fmts:r};}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===o.TIME;){const t=this.parseTime(),i=this.parseRepeat(),n=this.parseZone();e.push({time:t,repeats:i,zones:n});}return e;}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===o.MEDIA;){const t=this.parseMedia(),i=this.parseInformation(),n=this.parseConnections(),r=this.parseBandWidth(),s=this.parseKey(),o=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:n,bandwidths:r,key:s,attributes:o});}return e;}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===o.CONNECTION;)e.push(this.parseConnection());return e;}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken));}catch(e){break;}if(0===t.length)throw new Error("Invalid fmts");return t;}extract(e,t,...i){const n=t.call(this,e.value,e.cur,...i),r=e.value.slice(e.cur,n);return e.cur=n,r;}extractOneOrMore(e,t){const i=this.consumeOneOrMore(e.value,e.cur,t),n=e.value.slice(e.cur,i);return e.cur=i,n;}consumeSpaceForRecord(e){if(e.value[e.cur]!==s)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1;}}class I extends R{constructor(...e){super(...e),S(this,"attributes",void 0),S(this,"digested",!1);}extractOneOrMore(e,t,i){const n=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,n),[s,o]=i||[];if("number"==typeof s&&r.length<s)throw new Error("error in length, should be more or equal than ".concat(s," characters."));if("number"==typeof o&&r.length>o)throw new Error("error in length, should be less or equal than ".concat(o," characters."));return e._cur=n,r;}consumeAttributeSpace(e){if(e.attValue[e._cur]!==s)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1;}extract(e,t,...i){if(!e.attValue)throw new Error("Nothing to extract from attValue.");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r;}atEnd(e){if(!e.attValue)throw new Error();return e._cur>=e.attValue.length;}peekChar(e){if(!e.attValue)throw new Error();return e.attValue[e._cur];}peek(e,t){if(!e.attValue)throw new Error();for(let i=0;i<t.length;i++)if(t[i]!==e.attValue[e._cur+i])return !1;return !0;}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256]);}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256]);}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e);}catch(t){if(this.atEnd(e))break;throw t;}}this.attributes.iceOptions=t;}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i});}parseExtmap(e){const t=this.extractOneOrMore(e,a);let i;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),i=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,s),r=T(T({entry:parseInt(t,10)},i&&{direction:i}),{},{extensionName:n});this.peekChar(e)===s&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r);}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t;}}class v extends I{constructor(...e){super(...e),S(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]});}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e);}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t;}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error");}digest(){return this.digested=!0,this.attributes;}parseGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===s;)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i});}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0;}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m);}parseIdentity(e){const t=this.extractOneOrMore(e,f),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const n=this.extractOneOrMore(e,e=>e!==s&&_(e));i.push({name:t,value:n});}this.attributes.identities.push({assertionValue:t,extensions:i});}parseMsidSemantic(e){this.peekChar(e)===s&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e);}catch(e){break;}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break;}{const i=this.extract(e,this.consumeTill,s);t.identifierList.push(i);}}this.attributes.msidSemantic=t;}}class y extends I{constructor(e){super(),S(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]};}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e);}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t;}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error");}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const o=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:o,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c);}this.attributes.candidates.push(l);}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e);}catch(e){break;}}this.attributes.remoteCandidatesList.push(t);}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0;}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]});}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill);}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill);}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField;}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find(e=>e.ssrcId===parseInt(t,10));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}});}parseFmtp(e){const t=this.extract(e,this.consumeTill,s);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach(e=>{let[t,i]=e.split("=");t=t.trim();const r="string"==typeof i?i.trim():null;"string"==typeof t&&t.length>0&&(n[t]=r);});const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}});}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n;}return t;}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,s),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,s);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else {const t={type:i};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===s&&(t.additional=this.extract(e,this.consumeTill))),n=t;}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else {const e=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]});}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0;}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0;}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0;}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t;}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t);}parseImageAttr(e){this.attributes.imageattr.push(e.attValue);}parseRid(e){const t=this.extractOneOrMore(e,e=>h(e)||a(e)||"_"===e||"-"===e);this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===s){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",");}catch(e){break;}}i.payloads=t,this.peekChar(e)===s&&this.extract(e,this.consume,s);}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break;}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n);}}try{this.extract(e,this.consume,";");}catch(e){break;}}}this.attributes.rids.push(i);}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill);}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5]);}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0]);}digest(){return this.digested=!0,this.attributes;}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken);}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10));}catch(e){break;}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i});}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e;}class b{constructor(){A(this,"eol",r);}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i;}printVersion(e){return "v=".concat(e).concat(this.eol);}printOrigin(e){return "o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol);}printSessionName(e){return e?"s=".concat(e).concat(this.eol):"";}printInformation(e){return e?"i=".concat(e).concat(this.eol):"";}printUri(e){return e?"u=".concat(e).concat(this.eol):"";}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t;}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t;}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):"";}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t;}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map(e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime)).join(" ")).concat(this.eol),t+=this.eol);}return t;}printKey(e){return e?"k=".concat(e).concat(this.eol):"";}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t;}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t;}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t;}printMedia(e){return "m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol);}printSessionAttributes(e){return new O(this.eol).print(e);}printMediaAttributes(e){return new N(this.eol).print(e);}}class w{constructor(e){A(this,"eol",void 0),this.eol=e;}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol);}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol);}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(s)).concat(this.eol);}printFingerprints(e){return e.length>0?e.map(e=>"a=fingerprint:".concat(e.hashFunction).concat(s).concat(e.fingerprint)).join(this.eol)+this.eol:"";}printExtmap(e){return e.map(e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(s).concat(e.extensionName).concat(e.extensionAttributes?"".concat(s).concat(e.extensionAttributes):"").concat(this.eol)).join("");}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol);}printUnrecognized(e){return e.map(e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol)).join("");}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t;}printGroups(e){let t="";return e.length>0&&(t+=e.map(e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map(e=>"".concat(s).concat(e)).join("")).concat(this.eol)).join("")),t;}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol;}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):"";}printIdentity(e){return 0===e.length?"":e.map(e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map(e=>"".concat(s).concat(e.name).concat(e.value?"=".concat(e.value):"")))).join(this.eol)+this.eol;}printMsidSemantic(e){if(!e)return "";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(s,"*"):e.identifierList.length>0&&(t+=e.identifierList.map(e=>"".concat(s).concat(e))),t+this.eol;}}class N extends w{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i;}printCandidates(e){return e.map(e=>"a=candidate:".concat(e.foundation).concat(s).concat(e.componentId).concat(s).concat(e.transport).concat(s).concat(e.priority).concat(s).concat(e.connectionAddress).concat(s).concat(e.port).concat(s,"typ").concat(s).concat(e.type).concat(e.relAddr?"".concat(s,"raddr").concat(s).concat(e.relAddr):"").concat(e.relPort?"".concat(s,"rport").concat(s).concat(e.relPort):"").concat(Object.keys(e.extension).map(t=>"".concat(s).concat(t).concat(s).concat(e.extension[t])).join("")).concat(this.eol)).join("");}printRemoteCandidatesList(e){return e.map(e=>"a=remote-candidates:".concat(e.join(s)).concat(this.eol)).join("");}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol;}printRTPRelated(e){if(!e.payloads)return "";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map(e=>this.printRTCPFeedback("*",e)).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map(t=>this.printRTCPFeedback(e.payloadType,t)).join("");return i;}printFmtp(e,t){if(!t)return "";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(s).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(s).concat(Object.keys(t.parameters).map(e=>"".concat(e,"=").concat(t.parameters[e])).join(";")).concat(this.eol);}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(s).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):"";}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(s),n=t;return "trr-int"===n.type?i+="ttr-int".concat(s).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(s).concat(n.parameter),n.additional&&(i+="".concat(s).concat(n.additional)))),i+this.eol;}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol);}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol);}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol);}printSSRC(e){return e.map(e=>Object.keys(e.attributes).map(t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(s).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol)).join("")).join("");}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol);}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol);}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol);}printRTCP(e){if(void 0===e)return "";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(s).concat(e.netType)),e.addressType&&(t+="".concat(s).concat(e.addressType)),e.address&&(t+="".concat(s).concat(e.address)),t+this.eol;}printMSId(e){return e.map(e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(s).concat(e.appdata):"").concat(this.eol)).join("");}printImageattr(e){return e.map(e=>"a=imageattr:".concat(e).concat(this.eol)).join("");}printRid(e){return e.map(e=>{let t="a=rid:".concat(e.id).concat(s).concat(e.direction);return e.payloads&&(t+="".concat(s,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(s).concat(e.params.map(e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val)).join(";"))),t+this.eol;}).join("");}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol);}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol);}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol);}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol);}printSSRCGroups(e){return e.map(e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map(e=>"".concat(s).concat(e.toString(10))).join("")).concat(this.eol)).join("");}}function D(e){return new C().parse(e);}function P(e,t){return new b().print(e,t);}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports;}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]});},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},i(8);})();}(zU);var JU=zU.exports;function XU(e){if(Array.isArray(e))return e.map(e=>e);if(!QU(e))return e;const t={};for(const i in e){const n=e[i];QU(n)||Array.isArray(n)?t[i]=XU(n):t[i]=n;}return t;}function QU(e){return !("object"!=typeof e||Array.isArray(e)||!e);}class ZU{constructor(e){sh(this,"input",[]),sh(this,"size",void 0),this.size=e;}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1);}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length;}}const $U={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},ex={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:$U,remoteCandidate:$U}},tx={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0},ix={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},nx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},rx={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function sx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function ox(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?sx(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):sx(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class ax{constructor(e,t){sh(this,"onFirstVideoReceived",void 0),sh(this,"onFirstVideoDecoded",void 0),sh(this,"onFirstAudioReceived",void 0),sh(this,"onFirstVideoDecodedTimeout",void 0),sh(this,"onFirstAudioDecoded",void 0),sh(this,"onSelectedLocalCandidateChanged",void 0),sh(this,"onSelectedRemoteCandidateChanged",void 0),sh(this,"videoIsReady",!1),sh(this,"videoIsReady2",{}),sh(this,"pc",void 0),sh(this,"options",void 0),sh(this,"intervalTimer",void 0),sh(this,"stats",XU(ex)),sh(this,"isFirstVideoReceived",{}),sh(this,"isFirstVideoDecoded",{}),sh(this,"isFirstAudioReceived",{}),sh(this,"isFirstAudioDecoded",{}),sh(this,"isFirstVideoDecodedTimeout",{}),sh(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval(async()=>{this.updateStats();},this.options.updateInterval);}getStats(){return this.stats;}getSelectedCandidatePair(){return new cg(e=>{e({local:ox({},$U),remote:ox({},$U)});});}setVideoIsReady(e){this.videoIsReady=e;}setVideoIsReady2(e,t){this.videoIsReady2[e]=t;}getVideoIsReady(e){return this.videoIsReady2[e]||!1;}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0;}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,s=0,o=0;for(const a of i)e[a].forEach((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,s+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d);});e.sendPacketLossRate=n<=0||s<=0?0:s/(n+s),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o);}}function cx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function dx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?cx(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):cx(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class lx extends ax{constructor(){super(...arguments),sh(this,"_stats",ex),sh(this,"lastDecodeVideoReceiverStats",new Map());}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=XU(ex);const i=t.filter(e=>"ssrc"===e.type);this.processSSRCStats(i);const n=t.find(e=>"VideoBwe"===e.type);n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats;}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth);}processSSRCStats(e){e.forEach(e=>{var t;const i=bn(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=XU(ix);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break;}case"video_recv":{const t=XU(tx),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.stats.framesDecodeCount&&(t.framesDecodeInterval=0);}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:dx({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break;}case"audio_recv":{const t=XU(rx);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break;}case"audio_send":{const t=XU(nx);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break;}}});}_getStats(){return new cg((e,t)=>{this.pc.getStats(e,t);});}statsResponsesToObjects(e){const t=[];return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach(t=>{i[t]=e.stat(t);}),t.push(i);}),t;}}function ux(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function hx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ux(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ux(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class px extends ax{constructor(){super(...arguments),sh(this,"_stats",ex),sh(this,"report",void 0),sh(this,"lastDecodeVideoReceiverStats",new Map()),sh(this,"lastVideoFramesRecv",new Map()),sh(this,"lastVideoFramesSent",new Map()),sh(this,"lastVideoFramesDecode",new Map()),sh(this,"lastVideoJBDelay",new Map()),sh(this,"lastAudioJBDelay",new Map()),sh(this,"mediaBytesSent",new Map()),sh(this,"mediaBytesRetransmit",new Map()),sh(this,"mediaBytesTargetEncode",new Map()),sh(this,"lastEncoderMs",new Map());}async updateStats(){this.report=await this.pc.getStats(),this._stats=XU(ex),this.report.forEach(e=>{switch(e.type){case aI.OUTBOUND:case aI.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===aI.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===aI.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break;}case aI.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break;}case aI.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e);}}),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats;}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:hx({},$U),remote:hx({},$U)};return e.forEach(i=>{let n;if(i.type===aI.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===aI.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol);};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r);}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r);}}}),t;}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime);}),this._stats.audioSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime);}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t);}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t);}}processCandidateStats(e){let t;e.type===aI.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===aI.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===aI.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.localCandidate)),e.type===aI.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.remoteCandidate)));}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=XU(rx),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples);}processVideoInboundStats(e){let t=this._stats.videoRecv.find(t=>t.ssrc===e.ssrc);t||(t=XU(tx),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0;}if(i){const n=i.stats,s=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&s>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=s,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<n.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(i.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount));}n&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:0}),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:hx({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum});}processVideoOutboundStats(e){let t=this._stats.videoSend.find(t=>t.ssrc===e.ssrc);t||(t=XU(ix),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else {const t=new ZU(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t);}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else {const t=new ZU(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t);}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else {const t=new ZU(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t);}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else {const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n;}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount);}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else {const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=XU(nx),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else {const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}findRemoteStatsId(e,t){var i;const n=Array.from(NI(i=this.report).call(i)).find(i=>i.type===t&&i.ssrc===e);return n?n.id:null;}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond});}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel);}processVideoTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(s=null==a?void 0:a.frameHeight)&&void 0!==s?s:e.frameHeight,u=null!==(o=null==a?void 0:a.framesPerSecond)&&void 0!==o?o:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0});}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)};}processVideoTrackReceiverStats(e,t,i){var n,r,s,o,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(s=null==c?void 0:c.frameHeight)&&void 0!==s?s:e.frameHeight,h=null!==(o=null==c?void 0:c.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0};}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs});}}processAudioTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(s=null!==(o=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==o?o:e.echoReturnLossEnhancement)&&void 0!==s?s:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d;}processAudioTrackReceiverStats(e,t,i){var n,r,s,o,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(s=null==l?void 0:l.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,_=null!==(o=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==o?o:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(u&&h&&(i.accelerateRate=u/h),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs});}i.outputLevel=E;let g=1920;m&&h&&(g=h/m/50,i.receivedFrames=Math.round(h/g)),f&&(i.droppedFrames=Math.round(f/g));}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp));}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return "";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:"";}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach(t=>{e+=t.diffMean();}),this.mediaBytesRetransmit.forEach(e=>{t=null===t?e.diffMean():t+e.diffMean();}),this.mediaBytesTargetEncode.forEach(e=>{i=null===i?e.diffMean():i+e.diffMean();});const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3));}}class _x extends ax{updateStats(){return cg.resolve();}}function Ex(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const s=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null;}();return s?s<76?new lx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return !!window.RTCStatsReport&&e.getStats()instanceof cg;}(e)?new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new _x(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r});}function mx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function fx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mx(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mx(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function gx(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:s,filterAudioFec:o,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(JU.parse(e).mediaDescriptions.forEach(e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0));}),!p||0===u.length)throw new Error("Cannot get video capabilities from SDP.");if(!h||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");u.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"});}),l.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"});}),r&&(l=l.filter(e=>{var t;return "rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());}),u=u.filter(e=>{var t;return "rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());})),s&&(u=u.filter(e=>{var t;return !/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"");})),o&&(l=l.filter(e=>{var t;return !/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"");})),a&&(null==a?void 0:a.length)>0&&(l=l.filter(e=>{var t;return bn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");})),c&&(null==c?void 0:c.length)>0&&(u=u.filter(e=>{var t;return bn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");}));const m=RC("UNSUPPORTED_VIDEO_CODEC");return m&&m.length>0&&(u=u.filter(e=>!(e.rtpMap&&bn(m).call(m,e.rtpMap.encodingName.toLowerCase())))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p};}function Tx(e){const t=JU.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n};}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t});}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return {iceParameters:i,dtlsParameters:n};}function Sx(e,t){const i=[],n=e.attributes.ssrcGroups.filter(e=>"FID"===e.semantic),r=e.attributes.ssrcGroups.find(e=>"SIM"===e.semantic),s=e.attributes.ssrcs;if(r)r.ssrcIds.forEach(e=>{var r;const s=null===(r=n.find(t=>t.ssrcIds[0]===e))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0});});else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0});}else {if(0===s.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:s[0].ssrcId});}return i;}function Rx(e,t){const{cname:i}=e;let n;t&&t.ip&&"number"==typeof t.port?(n=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],jC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(n.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),jC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):n=e.iceParameters.candidates.map(e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}));const r={fingerprints:e.dtlsParameters.fingerprints.map(e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let o;switch(e.dtlsParameters.role){case"server":o="passive";break;case"client":o="active";break;case"auto":o="actpass";}return {dtlsParameters:r,iceParameters:s,candidates:n,rtpCapabilities:Px(e.rtpCapabilities),setup:o,cname:i};}function Cx(e,t,i){const n=[],r=[];return e.forEach(e=>{let{ssrcId:s,rtx:o}=e;const a=nS(8,"track-"),c={ssrcId:s,attributes:fx({label:a,mslabel:i=i||nS(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==o){const e={ssrcId:o,attributes:fx({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[s,o]});}}),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t;})}),{ssrcs:n,ssrcGroups:r};}function Ix(e,t){t instanceof ew&&e.attributes.payloads.forEach(e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!wg()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"));});}function vx(e){const t=e.attributes.unrecognized.findIndex(e=>"x-google-flag"===e.attField&&"conference"===e.attValue);-1!==t&&e.attributes.unrecognized.splice(t,1);}function yx(e,t){var i;if(!(t instanceof Rw&&t._encoderConfig&&-1===t._hints.indexOf(jA.SCREEN_TRACK)))return;const n=t._encoderConfig;IA().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach(e=>{var t,i;bn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin));}),IA().supportMinBitrate&&!bn(i=t._hints).call(i,jA.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach(e=>{var t,i;bn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(RC("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)));});}function Ax(e){if("video"!==e.media.mediaType)return;const t=Sg();if(t.name!==Eg.SAFARI&&t.os!==_g.IOS)return;const i=e.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==i&&e.attributes.extmaps.splice(i,1);}function bx(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);if(t){e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"});const i=function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)));}(r,e.attributes.payloads);i.forEach(e=>{e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)||e.rtcpFeedbacks.push({type:"transport-cc"});});}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}if(!0===t.remb){const t=n.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);if(t){e.attributes.extmaps.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"});const i=function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)));}(r,e.attributes.payloads);i.forEach(e=>{e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)||e.rtcpFeedbacks.push({type:"goog-remb"});});}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"goog-remb"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}}function wx(e,t,i){if(wg())return;if("video"!==e.media.mediaType)return;if(!(t instanceof Rw))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!RC("SIMULCAST"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId),o={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<n;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:YT(r.attributes)}),o.ssrcIds.push(r.ssrcId+t),s&&(e.attributes.ssrcs.push({ssrcId:s.ssrcIds[1]+t,attributes:YT(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,s.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(o);}async function Ox(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection();i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(await i.createOffer()).sdp,{send:r,recv:s,sendrecv:o}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=gx(i,e,t,"sendonly"),r=gx(i,e,t,"recvonly"),s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(n,r,"videoExtensions",s,o,a),Dx(n,r,"videoCodecs",s,o,a),Dx(n,r,"audioExtensions",s,o,a),Dx(n,r,"audioCodecs",s,o,a),RC("RAISE_H264_BASELINE_PRIORITY")){const e=a.videoCodecs.findIndex(e=>{var t,i;return "h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]);});if(-1!==e){const t=a.videoCodecs.findIndex(e=>{var t;return "h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase());});if(t<e){jC.debug("raising H264 baseline profile priority");const i=a.videoCodecs[e];a.videoCodecs.splice(e,1),a.videoCodecs.splice(t,0,i);}-1!==t&&(o.videoCodecs=o.videoCodecs.filter(e=>{var t,i;return !("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]));})),-1!==t&&RC("FILTER_SEND_H264_BASELINE")&&(s.videoCodecs=s.videoCodecs.filter(e=>{var t,i;return !("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]));}));}}return {send:s,recv:o,sendrecv:a};}(e,t,n);try{i.close();}catch(e){}return {send:r,recv:s,sendrecv:o};}function Nx(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=gx(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(e,t,"videoExtensions",i,n,r),Dx(e,t,"videoCodecs",i,n,r),Dx(e,t,"audioExtensions",i,n,r),Dx(e,t,"audioCodecs",i,n,r),RC("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){const t=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t<e){jC.debug("raising H264 baseline profile priority");const i=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,i);}-1!==t&&(n.videoCodecs=n.videoCodecs.filter(e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])));}}return {send:i,recv:n,sendrecv:r};}function Dx(e,t,i,n,r,s){if("videoExtensions"===i||"audioExtensions"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}if("videoCodecs"===i||"audioCodecs"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}}function Px(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return {send:t,recv:i};}let r,s;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=n,{send:r,recv:s};}function Lx(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter(e=>{var t;return "opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());}).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1";});}function kx(e){e.mediaDescriptions.forEach(e=>{"video"!==e.media.mediaType&&"audio"!==e.media.mediaType||e.attributes.payloads.forEach(e=>{-1===e.rtcpFeedbacks.findIndex(e=>"rrtr"===e.type)&&e.rtcpFeedbacks.push({type:"rrtr"});});});}function Mx(e,t,i,n){let r=[];if(e===av.VIDEO){if(RC("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===RC("H264_PROFILE_LEVEL_ID");})),!Array.isArray(r)||0===r.length){let e=[];const s=[],o=[];i.videoCodecs.forEach(t=>{var i,r,a;bn(i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(i,n)&&e.push(t),bn(r=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(r,"vp8")&&s.push(t),bn(a=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(a,"h264")&&o.push(t);}),0===e.length&&(0!==s.length?(e=s,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: vp8"))):0!==o.length&&(e=o,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: h264")))),0!==e.length&&(r=t.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)));}if(RC("USE_PUB_RTX")){const e=r.map(e=>e.payloadType.toString()),i=t.videoCodecs.filter(t=>t.rtpMap&&"rtx"===t.rtpMap.encodingName&&bn(e).call(e,t.fmtp&&t.fmtp.parameters.apt||""));r=[...r,...i];}0===r.length&&(jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs);}else r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n);}),0===r.length&&(jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus");}));return r;}let Ux=class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname","o/i14u9pJrxRKAsu"),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:s,direction:o,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=o===TI.RECEIVE_ONLY?JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s;const u=o===TI.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=o===TI.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=o===TI.RECEIVE_ONLY?r.send.videoCodecs:Mx(av.VIDEO,u,h,c),_=o===TI.RECEIVE_ONLY?r.send.audioCodecs:Mx(av.AUDIO,u,h,d);for(const e of l.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=p.map(e=>e.payloadType.toString(10)),e.attributes.payloads=p,e.attributes.extmaps=u.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:4e4,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=_.map(e=>e.payloadType.toString(10)),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1;}toString(){return JU.print(this.sessionDesc);}hasMid(e){return Array.isArray(e)?e.every(e=>this.hasMid(e)):this.sessionDesc.mediaDescriptions.some(t=>t.attributes.mid===e);}send(e,t,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:s,ssrcGroups:o}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(s);if(a){if(wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0};}return {mid:a.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,s,n);let i;return -1===t?(i=this.createOrRecycleSendMedia(e,s,o,"sendonly",n,r),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=s,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid};}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{e.attributes.ssrcs=[];}),this.updateBundleMids();}receive(e,t,i){const n=[];return e.forEach(e=>{const r=e._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(r);let o,a=!1;-1===s?(a=!0,o=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(o=YT(this.sessionDesc.mediaDescriptions[s]),o.attributes.direction="recvonly"),n.push({mid:o.attributes.mid,needCreateTransceiver:a});}),n;}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:s,relatedAddress:o,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=i?i:"",priority:c?c+"":"",connectionAddress:null!=n?n:"",port:r?r+"":"",type:s?s+"":"",relAddr:null!=o?o:"",relPort:a?a+"":"",extension:{}};this.candidates.some(e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(e=>{e.attributes.candidates=this.candidates;}));}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates;}createOrRecycleRecvMedia(e,t,i,n,r){const s=e._mediaStreamTrack.kind,o=this.rtpCapabilities.recv,a=Mx(s,o,this.localCapabilities.send,s===av.AUDIO?r:n),c=s===av.VIDEO?o.videoExtensions:o.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:s,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l;}else this.sessionDesc.mediaDescriptions.push(l);return l;}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex(n=>{const r=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(wg()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid);}return !1;}return r&&n.attributes.mid===i;});}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex(t=>{const i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return "0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i;});}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t;}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}createOrRecycleSendMedia(e,t,i,n,r,s){const o=this.rtpCapabilities.send,a=e===av.VIDEO?o.videoCodecs:o.audioCodecs,c=e===av.VIDEO?o.videoExtensions:o.audioExtensions;wg()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,s);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}};const xx=["sdp"];function Vx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Fx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Vx(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Vx(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}let Bx=class e extends Ov{get currentLocalDescription(){return this.peerConnection.currentLocalDescription;}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription;}get peerConnectionState(){return this.peerConnection.connectionState;}get iceConnectionState(){return this.peerConnection.iceConnectionState;}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null;}get localCodecs(){return [];}set isInRestartIce(e){this._isInRestartIce=e;}get isInRestartIce(){return this._isInRestartIce;}constructor(t,i,n){super(t,i),sh(this,"direction",void 0),sh(this,"name",void 0),sh(this,"store",void 0),sh(this,"spec",void 0),sh(this,"peerConnection",void 0),sh(this,"initialOffer",void 0),sh(this,"transport",void 0),sh(this,"statsFilter",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"localCandidateAddress",null),sh(this,"useXR",RC("USE_XR")),sh(this,"filter",{filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC")}),sh(this,"extension",{useXR:this.useXR}),sh(this,"_isInRestartIce",!1),sh(this,"mutex",new pS("P2PConnection-mutex")),sh(this,"onLocalCandidate",void 0),sh(this,"remoteSDP",void 0),sh(this,"pendingCandidates",[]),sh(this,"localCapabilities",void 0),sh(this,"isReady",!1),sh(this,"restartCnt",0),sh(this,"curTurnServerIndex",0),this.store=i,this.spec=t,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,i.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=n?n:TI.SEND_ONLY,this.name=this.direction===TI.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1;}async establish(e){try{const t=await Ox(this.filter,this.extension);if(this.localCapabilities=Px(t),e){const{sdp:t}=e,i=qU(e,xx),n=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=gx(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(t,e,"videoExtensions",i,n,r),Dx(t,e,"videoCodecs",i,n,r),Dx(t,e,"audioExtensions",i,n,r),Dx(t,e,"audioCodecs",i,n,r),RC("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){const t=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t<e){jC.debug("raising H264 baseline profile priority");const i=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,i);}-1!==t&&RC("FILTER_SEND_H264_BASELINE")&&(i.videoCodecs=i.videoCodecs.filter(e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])));}}return {send:i,recv:n,sendrecv:r};}(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const s=Tx(r.sdp);await this.peerConnection.setLocalDescription(r);const o=await Nx(this.filter,this.extension,r.sdp);this.localCapabilities=Px(o);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Fx(Fx({},s),{},{sdp:r.sdp});}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp);return this.initialOffer=e,Fx(Fx({},t),{},{sdp:e.sdp});}}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await Nx(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];null!=s&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach(e=>{this.peerConnection.addIceCandidate(e);}),this.pendingCandidates=[]);}catch(e){throw new Kg(Hg.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],o=n.remoteSDP.receive(e,t,i);e.forEach((e,t)=>{if(o[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}else {const i=n.peerConnection.getTransceivers().find(e=>e.mid===o[t].mid);if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(o[t].mid));s.push(i),e._updateRtpTransceiver(i);}}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const a=o.map(e=>e.mid),c=yield IU(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=JU.parse(d),u=a.map(e=>{const t=l.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));}),h=s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h;}catch(e){const t=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield IU(n.stopSending(a,!0)),e;}yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield IU(n.setRemoteDescription({type:"answer",sdp:p})),s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o||null===o.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,mid:o.mid,transceiver:o};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async restartICE(t){try{if(this.store.p2pTransport===fC.Auto&&(this.store.p2pTransport=fC.SdRtn,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:t}=Tx(e.sdp);return this.store.descriptionStart(),this.direction===TI.SEND_ONLY&&(await this.peerConnection.setLocalDescription(e)),t;}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===TI.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:t}=Tx(e.sdp);return await this.peerConnection.setLocalDescription(e),t;}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0;}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return {local:Fx(Fx({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Fx(Fx({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})};}return this.statsFilter.getSelectedCandidatePair();}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;bn(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.startICECandidate();}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)this.localCandidateAddress=e.candidate.address,null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1;}else this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount);});}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var s;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(RT(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),RC("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),bn(s=[fC.Relay,fC.SdRtn]).call(s,i)&&(r.iceTransportPolicy="relay"),RC("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(r.iceTransportPolicy="relay");})));return RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),jC.debug("P2PConnection p2pTransport is ".concat(i)),r;}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter(e=>e.tcpport);jC.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const s=r.length>i?r[i]:r[0];switch(t){case fC.SdRtn:const t=e.filter(e=>{var t;return bn(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL;}),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case fC.Relay:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.tcpport)}));}return n;}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state));},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e);};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t));},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();jC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})," )"));}}));}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null));}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack);}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),bn(s=e._hints).call(s,jA.LOW_STREAM)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof Rw&&!this.isVP8Simulcast(r)&&(await this.updateRtpSenderEncodings(r,n.sender));}}catch(e){jC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."));}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach((e,t)=>{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof Rw&&!bn(i=d._hints).call(i,jA.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof Rw&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r));}}}isVP8Simulcast(e){var t,i,n,r,s;return !!(e instanceof Rw&&RC("SIMULCAST")&&"vp8"===this.store.codec&&!bn(t=e._hints).call(t,jA.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async e=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=JU.parse(t).mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId;}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),bn(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate());}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n);}};function jx(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function Gx(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=Sy(t.width),n.height=Sy(t.height);const r=Sy(t.framerate||15);document.body.append(i),document.body.append(n);let s=e._mediaStreamTrack;i.srcObject=new MediaStream([s]),i.play();const o=n.getContext("2d");if(!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not get canvas context");const a=IA(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(jC.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r);}o.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]));},n.stopCapture=Tb(()=>n.startCapture&&n.startCapture(),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),jC.debug("clean low stream renderer");},c;}var Wx,Hx,Kx,Yx,qx,zx,Jx,Xx,Qx,Zx,$x;DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"establish",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"connect",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"receive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"mockReceive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"stopReceiving",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"restartICE",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Bx.prototype,"close",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateEncoderConfig",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateSendParameters",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],Bx.prototype,"replaceTrack",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"muteLocal",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"unmuteLocal",null),function(e){e[e.HEIGHT=2033]="HEIGHT",e[e.FRAME_RATE=2034]="FRAME_RATE",e[e.WIDTH=2035]="WIDTH";}(Wx||(Wx={})),function(e){e[e.HEIGHT=2072]="HEIGHT",e[e.FRAME_RATE=2074]="FRAME_RATE",e[e.WIDTH=2076]="WIDTH";}(Hx||(Hx={})),function(e){e[e.FRAME_RATE=2002]="FRAME_RATE",e[e.WIDTH=2003]="WIDTH",e[e.HEIGHT=2004]="HEIGHT",e[e.PACKAGE_LOST=2005]="PACKAGE_LOST",e[e.AVG_ENCODE=2007]="AVG_ENCODE",e[e.NACKS=2009]="NACKS",e[e.PLIS=2010]="PLIS",e[e.FIRS=2011]="FIRS",e[e.BITRATE=2012]="BITRATE",e[e.PACKAGE_RATE=2031]="PACKAGE_RATE",e[e.ADAPTATION=2032]="ADAPTATION",e[e.ACTUAL_ENCODED=2060]="ACTUAL_ENCODED",e[e.BANDWIDTH=2061]="BANDWIDTH",e[e.RETRANSMIT=2062]="RETRANSMIT",e[e.TARGET_ENCODED=2064]="TARGET_ENCODED",e[e.TRANSMIT=2066]="TRANSMIT",e[e.FREEZE=2082]="FREEZE",e[e.DISABLED=2095]="DISABLED",e[e.PLAYER_STATUS=2128]="PLAYER_STATUS",e[e.QP_SUM=2143]="QP_SUM";}(Kx||(Kx={})),function(e){e[e.BITRATE=2069]="BITRATE",e[e.PACKAGE_LOST=2070]="PACKAGE_LOST",e[e.PACKAGE_RATE=2071]="PACKAGE_RATE",e[e.HEIGHT=2073]="HEIGHT",e[e.FRAME_RATE=2075]="FRAME_RATE",e[e.WIDTH=2077]="WIDTH";}(Yx||(Yx={})),function(e){e[e.JITTER=-1]="JITTER",e[e.PACKAGE_LOST=2014]="PACKAGE_LOST",e[e.WIDTH=2018]="WIDTH",e[e.HEIGHT=2019]="HEIGHT",e[e.FRAME_RATE=2020]="FRAME_RATE",e[e.JITTER_BUFFER=2023]="JITTER_BUFFER",e[e.CURRENT_DELAY=2024]="CURRENT_DELAY",e[e.NACKS=2026]="NACKS",e[e.PLIS=2027]="PLIS",e[e.FIRS=2028]="FIRS",e[e.BITRATE=2029]="BITRATE",e[e.PACKAGE_RATE=2078]="PACKAGE_RATE",e[e.FREEZE=2084]="FREEZE",e[e.DISABLED=2101]="DISABLED",e[e.PLAYER_STATUS=2129]="PLAYER_STATUS",e[e.QP_SUM=2144]="QP_SUM",e[e.I_FRAME_DELAY=2149]="I_FRAME_DELAY";}(qx||(qx={})),function(e){e[e.FRAME_RATE_DECODE=2021]="FRAME_RATE_DECODE",e[e.FRAME_RATE_RENDER=2022]="FRAME_RATE_RENDER",e[e.FREEZE_TIME=2109]="FREEZE_TIME",e[e.FREEZE_TIME_RENDER=2147]="FREEZE_TIME_RENDER";}(zx||(zx={})),function(e){e[e.PCM_LEVEL=2104]="PCM_LEVEL";}(Jx||(Jx={})),function(e){e[e.PACKAGE_LOST=-1]="PACKAGE_LOST",e[e.LEVEL=2038]="LEVEL",e[e.BITRATE=2039]="BITRATE",e[e.PACKAGE_RATE=2040]="PACKAGE_RATE",e[e.AEC_RETURN_LOSS=2041]="AEC_RETURN_LOSS",e[e.AEC_RETURN_LOSS_ENH=2042]="AEC_RETURN_LOSS_ENH",e[e.FREEZE=2081]="FREEZE",e[e.DISABLED=2096]="DISABLED";}(Xx||(Xx={})),function(e){e[e.BITRATE=2044]="BITRATE",e[e.PACKAGE_LOST=2045]="PACKAGE_LOST",e[e.PACKAGE_RATE=2046]="PACKAGE_RATE",e[e.CURRENT_DELAY=2047]="CURRENT_DELAY",e[e.JITTER_BUFFER=2054]="JITTER_BUFFER",e[e.JITTER=2055]="JITTER",e[e.FREEZE=2083]="FREEZE",e[e.DISABLED=2102]="DISABLED",e[e.PCM_LEVEL=2105]="PCM_LEVEL",e[e.PLAYER_STATUS=2130]="PLAYER_STATUS",e[e.CONCEALED_SAMPLES=2148]="CONCEALED_SAMPLES";}(Qx||(Qx={})),function(e){e[e.FREEZE_TIME=-1]="FREEZE_TIME",e[e.LEVEL=2043]="LEVEL";}(Zx||(Zx={})),function(e){e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE";}($x||($x={}));const eV=1e3,tV=3;function iV(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)));}function nV(e){const t={[$x.CONN_TYPE]:0,[$x.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[$x.CONN_TYPE]=1),"tcp"===i&&(t[$x.CONN_TYPE]=3),"tls"===i&&(t[$x.CONN_TYPE]=4);break;}case"srflx":t[$x.CONN_TYPE]=2;}return t;}class rV extends dT{constructor(e){super(),sh(this,"store",void 0),sh(this,"uploadWRTCStatsTimer",void 0),sh(this,"uploadOutboundDenoiserStatsTimer",void 0),sh(this,"uploadExtStatsTimer",void 0),sh(this,"uploadExtUsageStatsTimer",void 0),sh(this,"uploadInboundExtStatsTimer",void 0),sh(this,"requestStats",void 0),sh(this,"requestTransportStats",void 0),sh(this,"requestLocalMedia",void 0),sh(this,"requestRemoteMedia",void 0),sh(this,"requestAllTracks",void 0),sh(this,"requestVideoIsReady",void 0),sh(this,"requestUploadStats",void 0),sh(this,"requestUpload",void 0),sh(this,"uploadOutboundStarted",!1),sh(this,"uploadInboundStarted",!1),sh(this,"uploadTransportStarted",!1),sh(this,"uploadExtensionUsageStarted",!1),sh(this,"lastRecvStats",void 0),sh(this,"lastSendStats",void 0),sh(this,"lastFullRecvStats",void 0),sh(this,"lastFullSendStats",void 0),sh(this,"needUploadRenderFreezeTime",!0),this.store=e;}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;let t,i;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){const n={};if(this.uploadTransportStarted&&t){const r=this.getTransportStats(t,i,e);r&&(n.misc=[r]);}if(this.uploadOutboundStarted&&t){const i=this.getOutboundStats(t,e?this.lastSendStats:this.lastFullSendStats,e);i&&(n.outbound=[i]);}if(this.uploadInboundStarted&&i){const t=this.getInboundStats(i,e?this.lastRecvStats:this.lastFullRecvStats,e);t&&(n.inbound=t);}this.requestUploadStats(n);}this.lastRecvStats=i,this.lastSendStats=t,e||(this.lastFullRecvStats=i,this.lastFullSendStats=t);}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;let e=1;this.uploadWRTCStatsTimer=window.setInterval(()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted)return this.stopUploadWRTCStats();this.uploadWRTCStats(e!==tV),++e===tV+1&&(e=1);},eV);}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0);}getTransportStats(e,t,i){if(!this.requestStats)return;if(i)return null==e.rtt?void 0:{addition:{[$x.RTT]:e.rtt,[$x.CONN_TYPE]:void 0}};const n=nV(e);if(this.store.useP2P){if(t){const e=nV(t);n[$x.CONN_TYPE]+=e[$x.CONN_TYPE]<<3;}n[$x.CONN_TYPE]+=110;}else n[$x.CONN_TYPE]+=100;return {addition:n};}getOutboundStats(e,t,i){if(!this.requestUploadStats||!this.requestLocalMedia)return;const n=this.requestLocalMedia();if(!n||0===n.length)return;let r,s,o;return n.forEach(n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case lv.LocalVideoLowTrack:case lv.LocalVideoTrack:if(a===lv.LocalVideoTrack){const n=function(e,t,i,n,r){const s=t.videoSend.find(t=>t.ssrc===e);if(!s)return;const o={},{sentFrame:a,inputFrame:c}=s;if(c&&a){const e=c.frameRate,t=a.frameRate;o[Kx.FREEZE]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i;}(e,t)?1:0;}if(iV(o,Kx.QP_SUM,s.qpSumPerFrame),r)return o;switch(a&&(iV(o,Kx.HEIGHT,a.height),iV(o,Kx.WIDTH,a.width),iV(o,Kx.FRAME_RATE,a.frameRate)),o[Kx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":o[Kx.ADAPTATION]=0;break;case"cpu":o[Kx.ADAPTATION]=1;break;case"bandwidth":o[Kx.ADAPTATION]=2;break;case"other":o[Kx.ADAPTATION]=3;}o[Kx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],iV(o,Kx.NACKS,s.nacksCount),iV(o,Kx.PLIS,s.plisCount),iV(o,Kx.FIRS,s.firsCount),iV(o,Kx.AVG_ENCODE,s.avgEncodeMs);const d=i&&i.videoSend.find(t=>t.ssrc===e);if(d){let e=r?eV:eV*tV;d.timestamp&&s.timestamp&&(e=s.timestamp-d.timestamp),null!=d.packets&&null!=s.packets&&iV(o,Kx.PACKAGE_RATE,1e3*(s.packets-d.packets)/e),null!=s.packetsLost&&null!=d.packetsLost&&iV(o,Kx.PACKAGE_LOST,s.packetsLost-d.packetsLost),null!=d.bytes&&null!=s.bytes&&iV(o,Kx.BITRATE,8*(s.bytes-d.bytes)/e);}return o;}(d[0].ssrcId,e,t,c,i),r=i?null:function(e,t,i){const n=t.videoSend.find(t=>t.ssrc===e);if(!n)return null;const r={},s=n.inputFrame,o=s&&s.height||i&&i._videoHeight||0,a=s&&s.width||i&&i._videoWidth||0,c=s&&s.frameRate||0;return iV(r,Wx.HEIGHT,o),iV(r,Wx.WIDTH,a),iV(r,Wx.FRAME_RATE,c),r;}(d[0].ssrcId,e,c),o=i?null:function(e){const t={};return iV(t,Kx.RETRANSMIT,e.bitrate.retransmit),iV(t,Kx.TARGET_ENCODED,e.bitrate.targetEncoded),iV(t,Kx.ACTUAL_ENCODED,e.bitrate.actualEncoded),iV(t,Kx.TRANSMIT,e.bitrate.transmit),iV(t,Kx.BANDWIDTH,e.sendBandwidth),t;}(e);s=Object.assign({},n,r,o);}else o=i?void 0:function(e,t,i){const n=t.videoSend.find(t=>t.ssrc===e);if(!n)return;const r={},s=n.sentFrame;if(s&&(iV(r,Yx.HEIGHT,s.height),iV(r,Yx.WIDTH,s.width),iV(r,Yx.FRAME_RATE,s.frameRate)),i){const t=i.videoSend.find(t=>t.ssrc===e);if(t){let e=eV*tV;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&iV(r,Yx.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&iV(r,Yx.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&iV(r,Yx.BITRATE,8*(n.bytes-t.bytes)/e);}}return r;}(d[0].ssrcId,e,t);break;case lv.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find(t=>t.ssrc===e);if(!r)return;const s={};s[Xx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const o=n._source.getAccurateVolumeLevel(),a=r.inputLevel;iV(s,Xx.LEVEL,100*(null==a?o:a)),iV(s,Jx.PCM_LEVEL,100*o),iV(s,Xx.AEC_RETURN_LOSS,r.aecReturnLoss),iV(s,Xx.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),s[Xx.FREEZE]=0;const c=i&&i.audioSend.find(t=>t.ssrc===e);if(c){let e=eV*tV;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&iV(s,Xx.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&iV(s,Xx.PACKAGE_RATE,1e3*(r.packets-c.packets)/e);}return s;}(d[0].ssrcId,e,t,c);}}),{high:s,low:o,audio:r};}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach(n=>{let[s,o]=n;const a={peer:s.uid};if(o.has(av.VIDEO)&&s.videoTrack){const n=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,r=s.videoTrack?function(e,t,i,n,r,s,o){const a=t.videoRecv.find(t=>t.ssrc===e);if(!a)return;const c={},{receivedFrame:d,outputFrame:l,decodeFrameRate:u}=a,h=i&&i.videoRecv.find(t=>t.ssrc===e);if(c[qx.FREEZE]=r&&mV.isRemoteVideoFreeze(n,a,h)?1:0,iV(c,zx.FRAME_RATE_DECODE,u),iV(c,qx.QP_SUM,a.qpSumPerFrame),a.framesRateFirefox&&iV(c,qx.FRAME_RATE,a.framesRateFirefox),d&&iV(c,qx.FRAME_RATE,d.frameRate),h){const e=t.timestamp-i.timestamp||(o?eV:tV*eV);null!=a.packetsLost&&null!=h.packetsLost&&iV(c,qx.PACKAGE_LOST,a.packetsLost-h.packetsLost),null!=h.bytes&&null!=a.bytes&&iV(c,qx.BITRATE,8*(a.bytes-h.bytes)/e),null!=h.packets&&null!=a.packets&&iV(c,qx.PACKAGE_RATE,1e3*(a.packets-h.packets)/e);}if(o)return c;if(d?(iV(c,qx.HEIGHT,d.height),iV(c,qx.WIDTH,d.width)):n&&(iV(c,qx.HEIGHT,n._videoHeight||0),iV(c,qx.WIDTH,n._videoWidth||0)),l&&iV(c,zx.FRAME_RATE_RENDER,l.frameRate),iV(c,qx.JITTER_BUFFER,a.jitterBufferMs),iV(c,qx.CURRENT_DELAY,a.currentDelayMs),iV(c,qx.FIRS,a.firsCount),iV(c,qx.NACKS,a.nacksCount),iV(c,qx.PLIS,a.plisCount),n){c[qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i}=e;if(t&&t.length>0&&iV(c,zx.FREEZE_TIME,t.splice(0,1)[0]),s&&"visible"===Dw.visibility){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),iV(c,zx.FREEZE_TIME_RENDER,t);}}}if(c[qx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],h&&void 0!==a.totalInterFrameDelay&&void 0!==a.totalSquaredInterFrameDelay&&void 0!==h.totalInterFrameDelay&&void 0!==h.totalSquaredInterFrameDelay){const e=a.totalInterFrameDelay-h.totalInterFrameDelay,t=a.totalSquaredInterFrameDelay-h.totalSquaredInterFrameDelay,i=a.framesDecodeCount-h.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(c[qx.I_FRAME_DELAY]=r);}return c;}(s._videoSSRC,e,t,s.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r);}if(o.has(av.AUDIO)&&s.audioTrack){const n=s.audioTrack?function(e,t,i,n,r){const s=t.audioRecv.find(t=>t.ssrc===e);if(!s)return;const o={},a=i&&i.audioRecv.find(t=>t.ssrc===e),{receivedFrames:c,droppedFrames:d}=s;var l,u;if(iV(o,Qx.JITTER,s.jitterMs),null!=c&&null!=d&&(o[Qx.FREEZE]=(u=d,0===(l=c)||100*u/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?eV:eV*tV);null!=s.packets&&null!=a.packets&&iV(o,Qx.PACKAGE_RATE,1e3*(s.packets-a.packets)/e),null!=a.bytes&&null!=s.bytes&&iV(o,Qx.BITRATE,8*(s.bytes-a.bytes)/e),null!=s.packetsLost&&null!=a.packetsLost&&iV(o,Qx.PACKAGE_LOST,s.packetsLost-a.packetsLost);}if(r)return o;const h=n._source.getAccurateVolumeLevel(),p=s.outputLevel;if(iV(o,Zx.LEVEL,100*(null==p?h:p)),iV(o,Qx.PCM_LEVEL,100*h),n&&(o[Qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),iV(o,Qx.JITTER_BUFFER,s.jitterBufferMs),iV(o,Qx.CURRENT_DELAY,s.jitterBufferMs),o[Qx.PLAYER_STATUS]=ab[Gb.getPlayerState(n.getTrackId())],a){const e=s.concealedSamples-a.concealedSamples;e>0&&iV(o,Qx.CONCEALED_SAMPLES,e);}return o;}(s._audioSSRC,e,t,s.audioTrack,i):void 0;n&&(a.audio=n);}(a.video||a.audio)&&r.push(a);}),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,r;}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats();}stopUploadTransportStats(){this.uploadTransportStarted=!1;}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find(e=>e instanceof tw);if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(mI.DENOISER_STATS,t);}},2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach(e=>{e.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});});},2e3));}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0);}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval(()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach(e=>{let[t,i]=e;if(i.has(av.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});}if(i.has(av.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});}});},2e3));}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0));}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map();this.uploadExtUsageStatsTimer=window.setInterval(async()=>{const t=Date.now(),i={connectionInterval:RC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of s)t.has(av.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(av.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:o,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(o))&&void 0!==n?n:0,l=2===a?e+RC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,s;t.set(o,l),i[o]?(2===a&&(i[o].value=a),c>i[o].level&&(i[o].level=c),"remote"===d&&(i[o].remoteUidCount+=1),i[o].totalTs=null!==(r=t.get(o))&&void 0!==r?r:0):i[o]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(s=t.get(o))&&void 0!==s?s:0};}return Object.keys(i).map(e=>{const{level:t,value:n,totalTs:r}=i[e];return {id:e,level:t,value:n,totalTs:r};});}(n,e);const o=Date.now(),a=o>t?o:t+1;this.requestUpload&&this.requestUpload(mI.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a});},RC("EXTENSION_USAGE_UPLOAD_INTERVAL"));}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0);}}class sV{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_;}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_;}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack;}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack;}get dataChannels(){return this._dataChannels;}constructor(e,t){sh(this,"uid",void 0),sh(this,"_uintid",void 0),sh(this,"_trust_in_room_",!0),sh(this,"_trust_audio_enabled_state_",!0),sh(this,"_trust_video_enabled_state_",!0),sh(this,"_trust_audio_mute_state_",!0),sh(this,"_trust_video_mute_state_",!0),sh(this,"_audio_muted_",!1),sh(this,"_video_muted_",!1),sh(this,"_audio_enabled_",!0),sh(this,"_video_enabled_",!0),sh(this,"_audio_added_",!1),sh(this,"_video_added_",!1),sh(this,"_is_pre_created",!1),sh(this,"_video_pre_subscribed",!1),sh(this,"_audio_pre_subscribed",!1),sh(this,"_trust_video_stream_added_state_",!0),sh(this,"_trust_audio_stream_added_state_",!0),sh(this,"_audioTrack",void 0),sh(this,"_videoTrack",void 0),sh(this,"_dataChannels",[]),sh(this,"_audioSSRC",void 0),sh(this,"_videoSSRC",void 0),sh(this,"_audioOrtc",void 0),sh(this,"_videoOrtc",void 0),sh(this,"_cname",void 0),sh(this,"_rtxSsrcId",void 0),sh(this,"_videoMid",void 0),sh(this,"_audioMid",void 0),this.uid=e,this._uintid=t;}}var oV;function aV(e,t){var i;let n;switch(t){case lv.LocalAudioTrack:n=JI.Audio;break;case lv.LocalVideoTrack:n=bn(i=e._hints).call(i,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:n=JI.Low;}return n;}function cV(e){const t=IA();if(e.some(e=>e._bypassWebAudio))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing");}function dV(e,t){cV(e);const i=t||new nw();return e.forEach(e=>i.addAudioTrack(e)),i;}function lV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function uV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?lV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):lV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}!function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY";}(oV||(oV={}));class hV extends dT{get state(){return this._state;}set state(e){const t=this._state;this._state=e,this.emit(hv.StateChange,t,this._state);}constructor(e,t){super(),sh(this,"store",void 0),sh(this,"statsUploader",void 0),sh(this,"sendConnection",void 0),sh(this,"recvConnection",void 0),sh(this,"localTrackMap",new Map()),sh(this,"remoteUserMap",new Map()),sh(this,"localDataChannels",[]),sh(this,"pendingLocalTracks",[]),sh(this,"pendingRemoteTracks",[]),sh(this,"statsCollector",void 0),sh(this,"dtlsFailedCount",0),sh(this,"sendMutex",new pS("P2PChannel2-send-mutex")),sh(this,"recvMutex",new pS("P2PChannel2-recv-mutex")),sh(this,"_state",uv.Disconnected),sh(this,"_restartStates",["disconnected","failed"]),sh(this,"reconnectInterval",void 0),sh(this,"uploadUnplinkStarted",!1),sh(this,"uploadDownlinkStarted",!1),sh(this,"uplinkStateUploadInterval",void 0),sh(this,"downlinkStatsUploadInterval",void 0),sh(this,"handleMuteLocalTrack",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const a=o.find(e=>"videoLowTrack"===e[0]);if(a){a[1].track._originMediaStreamTrack.stop();}await this.sendConnection.muteLocal(o.map(e=>{let[,{id:t}]=e;return t;}));let c=!1;var r,s;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(lv.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.id);const d=this.createMuteMessage(o);await yT(this,hv.RequestMuteLocal,d);const l="video"===e.trackMediaType?Av.MUTE_LOCAL_VIDEO:Av.MUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const s=this.createUnmuteMessage(r),o="video"===e.trackMediaType?Av.UNMUTE_LOCAL_VIDEO:Av.UNMUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:o,message:s}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s),await this.sendConnection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!this.sendConnection||!i||void 0===i[1].id||this.state!==uv.Connected)return void t();if(await(null===(s=this.sendConnection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),i[0]===lv.LocalVideoTrack&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));});},RC("ICE_RESTART_INTERVAL"));}async startP2PConnection(e,t){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.");}async connect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support connect.");}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Bx(e,this.store,TI.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return {iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp};}{this.state=uv.New,this.sendConnection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Bx(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return {iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp};}}finally{i&&i();}}async p2pConnect(e){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected;}async addRemoteCandidate(e,t){if(t===TI.RECEIVE_ONLY){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e);}else {if(!this.recvConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e);}}publish(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==uv.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter(e=>-1===n.pendingLocalTracks.indexOf(e));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t));}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",r);}),n.bindLocalTrackEvents(s);const o=yield IU(n.sendConnection.send(s.map(e=>{let{track:t}=e;return t;}),n.store.codec,n.store.audioCodec)),a=(yield IU(o.next())).value,c=n.createGatewayPublishMessage(s,a);try{yield c;}catch(e){throw o.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&s.forEach(e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t);}),n.unbindLocalTrackEvents(s),e;}yield IU(o.next()),s.forEach(e=>{let{type:t}=e;n.statsCollector.addLocalStats(t);}),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(s,a),s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",void 0,r);}),n.startUploadUplinkState();}finally{r();}})();}async unpublish(e){if(!this.sendConnection||this.state!==uv.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(t=>!bn(e).call(e,t)));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find(e=>"videoLowTrack"===e[0]);if(i){i[1].track.close();}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return {type:t,track:i};})),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t);}),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===uv.Connected){if(i){i[1].track.close();}return n;}e.forEach(e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1);});}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach(i=>{let[n,{track:r,ssrcs:s}]=i;const o={stream_type:aV(r,n),ssrcs:s};r._muted||!r._enabled?e.push(o):t.push(o);}),e.length>0&&e.forEach(e=>{yT(this,hv.RequestMuteLocal,[e]);}),t.length>0&&t.forEach(e=>{yT(this,hv.RequestUnmuteLocal,[e]);});};e(),this.uplinkStateUploadInterval=window.setInterval(()=>{e();},3e3);}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval));}publishLowStream(e){return PU(function*(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support publishLowStream.");})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]);}async unpublishLowStream(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.");}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:s,mid:o,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Nw(s,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new Ow(s,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,o):this.remoteUserMap.set(e,new Map([[t,o]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex(i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r;});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,e.uid));}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n);}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter(i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid;});if(n.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),this.recvConnection||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0;}}),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach(e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),r.forEach(e=>{let[,{kind:t}]=e;yT(this,hv.RequestP2PMuteRemote,t);}));}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach(e=>{let[,t]=e;[av.VIDEO,av.AUDIO].forEach(e=>{t.has(e)?yT(this,hv.RequestP2PUnmuteRemote,e):yT(this,hv.RequestP2PMuteRemote,e);});});e(),this.downlinkStatsUploadInterval=window.setInterval(()=>{e();},3e3);}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval));}getAllDataChannels(){return this.localDataChannels;}async massSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribe.");}async massSubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.");}async massUnsubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.");}async massUnsubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.");}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1);}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t);}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;}).concat(i.trackList);}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;});}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new pS("P2PChannel2-send-mutex"),this.sendMutex=new pS("P2PChannel2-recv-mutex"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e);});}e.track.close();}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=uv.Disconnected;}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats();}getRemoteVideoIsReady(e){var t;return (null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1;}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return {width:e.track._videoWidth||0,height:e.track._videoHeight||0};}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0;}getLocalMedia(e){return this.localTrackMap.get(e);}hasLocalMedia(){return this.localTrackMap.size>0;}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{};}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return {uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0};});const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop());}),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.MediaReconnectStart,t.uid);}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")));}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return !0;}return !1;}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t});}async restartICE(e,t){let i,n;if(e===TI.SEND_ONLY){if(!this.sendConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection;}else {if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection;}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e;}{const e=await n.restartICE();if(e){const t=await vT(this,hv.RequestP2PRestartICE,{direction:TI.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1;}}}finally{i();}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find(e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId);}),r=e.audioSend.find(e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId);});if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5;}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t;}async muteLocalTrack(e){return new cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}filterTobePublishedTracks(e,t,i){const n=[],r=IA(),s=this.getAllTracks();e=HT(e=e.filter(e=>-1===s.indexOf(e)));let o=!1,a=!1;for(const s of e){if(s instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(s instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e){if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0);}else if(a){const e=n.find(e=>{let{type:t}=e;return t===lv.LocalAudioTrack;});if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s);}else {if(!r.webAudioMediaStreamDest||s instanceof nw||s._bypassWebAudio)n.push({track:s,type:lv.LocalAudioTrack});else {const e=new nw();e.addAudioTrack(s),n.push({track:e,type:lv.LocalAudioTrack});}a=!0;}}}return n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack));}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return {track:i,type:t};})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,{track:s,type:o}=e;switch(o){case lv.LocalAudioTrack:r=JI.Audio;break;case lv.LocalVideoTrack:r=bn(n=s._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:r=JI.Low;}return {kind:o===lv.LocalAudioTrack?av.AUDIO:av.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:s.muted||!s.enabled};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC});});}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t);});}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(hv.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),bn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&(await iS(800)),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i);},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);},e.onLocalCandidate=t=>{this.emit(hv.LocalCandidate,{candidate:t,direction:e.direction});};}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0;}async handleDisconnect(e){const t=e===TI.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,jC.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===TI.SEND_ONLY?this.restartICE(e):vT(this,hv.RequestP2PRestartICE,{direction:TI.SEND_ONLY}));}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}]);}else Array.from(n.entries()).forEach(t=>{let[n,r]=t;i.push([e,{kind:n,id:r}]);});return i;}createUnsubscribeMessage(e){const t=[];return e.forEach(e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}));}}),t;}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t));});}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink)),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}));}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return "connected"!==e&&"connected"!==t;}return !0;}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof ew){const i=this.filterTobeUnmutedTracks(e[t]);if(0===i.length)continue;const n=this.createUnmuteMessage(i);return void(await yT(this,hv.RequestUnmuteLocal,n));}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(e=>{let[,{ssrcs:t}]=e;return !!t;}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return !(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e));},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks();}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0;}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");}}getLowVideoTrack(e,t){const i=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=uV(uV({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,uV(uV({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock");}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0});}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return !1;const n=this.remoteUserMap.get(e);if(!n)return !1;const r=n.get(t);if(!r)return !1;const s=await this.recvConnection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel2] reset connection to ").concat(e)),this.state===uv.Connected?(jC.debug("[".concat(this.store.clientId,"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first")),this.disconnectForReconnect()):(this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0));}async publishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED);}async unpublishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED);}async subscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async unsubscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}hasPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}setPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async preConnect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED);}getEstablishParams(){throw new Kg(Hg.NOT_SUPPORTED);}async reSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED);}async updateVideoStreamParameter(e,t){throw new Kg(Hg.NOT_SUPPORTED);}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}}function pV(e){return function(t,i,n){const r=t[i];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];switch(e){case oV.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n);}finally{e();}}case oV.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n);}finally{e();}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i)),t=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n);}finally{e(),t();}}}},n;};}function _V(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function EV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?_V(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):_V(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}DI([pV(oV.SEND_ONLY),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],hV.prototype,"p2pConnect",null),DI([pV(oV.SEND_ONLY),PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],hV.prototype,"unpublish",null),DI([pV(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],hV.prototype,"unpublishLowStream",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number,String]),PI("design:returntype",cg)],hV.prototype,"subscribe",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number,String]),PI("design:returntype",cg)],hV.prototype,"mockSubscribe",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String,Boolean]),PI("design:returntype",cg)],hV.prototype,"unsubscribe",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],hV.prototype,"muteRemote",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],hV.prototype,"unmuteRemote",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],hV.prototype,"hasRemoteMediaWithLock",null),DI([pV(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],hV.prototype,"disconnectForReconnect",null),DI([pV(oV.RECEIVE_ONLY),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],hV.prototype,"remoteMediaSsrcChanged",null);class mV{constructor(e){sh(this,"store",void 0),sh(this,"onStatsException",void 0),sh(this,"onUploadPublishDuration",void 0),sh(this,"onStatsChanged",void 0),sh(this,"localStats",new Map()),sh(this,"remoteStats",new Map()),sh(this,"updateStatsInterval",void 0),sh(this,"trafficStats",void 0),sh(this,"trafficStatsPeerList",[]),sh(this,"uplinkStats",void 0),sh(this,"exceptionMonitor",void 0),sh(this,"p2pChannel",void 0),sh(this,"scalabilityMode",oI.L1T1),sh(this,"updateStats",()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel));}),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new TU(),this.exceptionMonitor.on("exception",(e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i);});}reset(){this.localStats=new Map(),this.remoteStats=new Map(),this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0;}getLocalAudioTrackStats(){return this.localStats.get(lv.LocalAudioTrack)||EV({},XA);}getLocalVideoTrackStats(){return this.localStats.get(lv.LocalVideoTrack)||EV({},QA);}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t;},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r));}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r));});return i;}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n);}else Array.from(this.remoteStats.entries()).forEach(e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n);});return t;}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t;},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r));}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r));});return i;}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(lv.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(lv.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(lv.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate),this.remoteStats.forEach(e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate);});let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0};}addLocalStats(e){this.localStats.set(e,void 0);}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear();}addRemoteStats(e){this.remoteStats.set(e,{});}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear();}addP2PChannel(e){this.p2pChannel=e;}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter(e=>void 0!==e.B_ppad||void 0!==e.B_ppvd);e.peer_delay.filter(e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid)).forEach(e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid));}),this.trafficStats=e;}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&jC.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e;}static isRemoteVideoFreeze(e,t,i){if(!e)return !1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r;}static isRemoteAudioFreeze(e){return !!e&&e._isFreeze();}isLocalVideoFreeze(e){return !(!e.inputFrame||!e.sentFrame)&&e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3;}updateLocalStats(e){Array.from(this.localStats.entries()).forEach(t=>{let[i,n]=t;switch(i){case lv.LocalVideoTrack:case lv.LocalVideoLowTrack:{const t=n,s=EV({},QA),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find(e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(lv.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(jC.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode);}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100);}var r;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break;}case lv.LocalAudioTrack:{const t=n,r=EV({},XA),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find(e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else {const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t));}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0;}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(lv.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break;}}});}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{var i,n;let[r,{videoStats:s,audioStats:o,videoPcStats:a}]=t;const c=o,d=s,l=a,u=EV({},ZA),h=EV({},eb),p=EV({},$A),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let g;g=e instanceof hV?e.getStats(!0):e.getStats();const T=null===(i=g)||void 0===i?void 0:i.audioRecv.find(e=>e.ssrc===m),S=null===(n=g)||void 0===n?void 0:n.videoRecv.find(e=>e.ssrc===f),R=this.trafficStats&&this.trafficStats.peer_delay.find(e=>e.peer_uid===r);if(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&mV.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),S){"H264"!==S.codec&&"H265"!==S.codec&&"VP8"!==S.codec&&"VP9"!==S.codec&&"AV1X"!==S.codec&&"AV1"!==S.codec||(h.codecType=S.codec),h.receiveBytes=S.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,h.renderFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,S.outputFrame&&(h.renderFrameRate=S.outputFrame.frameRate),S.receivedFrame?(h.receiveFrameRate=S.receivedFrame.frameRate,h.receiveResolutionHeight=S.receivedFrame.height,h.receiveResolutionWidth=S.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==S.framesRateFirefox&&(h.receiveFrameRate=Math.round(S.framesRateFirefox)),h.receivePackets=S.packets,h.receivePacketsLost=S.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.receiveDelay=S.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f);E&&t&&mV.isRemoteVideoFreeze(E,S,l)&&(h.totalFreezeTime+=1),h.freezeRate=h.totalFreezeTime/h.totalDuration;}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:u,videoStats:h,videoPcStats:S,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h);});}}function fV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function gV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class TV extends dT{constructor(e,t,i,n){super(),sh(this,"spec",void 0),sh(this,"token",void 0),sh(this,"websocket",void 0),sh(this,"pingpongTimer",void 0),sh(this,"reconnectMode","retry"),sh(this,"serviceMode",void 0),sh(this,"reqId",0),sh(this,"commandReqId",0),sh(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong();}),sh(this,"handleWebSocketMessage",e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):this.serviceMode===RI.INJECT?this.emit(jI.INJECT_STREAM_STATUS,t):(eI.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===RI.TRANSCODE?1:2}),this.emit(jI.PUBLISH_STREAM_STATUS,t));}),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new zv("live-streaming",i),this.websocket.on(SI.CONNECTED,this.handleWebSocketOpen),this.websocket.on(SI.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,jI.REQUEST_NEW_ADDRESS).then(e).catch(t);}),this.websocket.on(SI.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode;});}init(e){return this.websocket.init(e);}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new LI(Hg.UNEXPECTED_ERROR);const o=gV({command:e,sdkVersion:"4.20.2"===EC?"0.0.1":EC,seq:s,requestId:s,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new LI(Hg.WS_DISCONNECT);const a=()=>new cg((e,t)=>{this.websocket.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.websocket.once(SI.CONNECTED,e);});"connected"!==this.websocket.state&&(await a()),o.clientRequest&&(o.clientRequest.workerToken=this.token);const c=new cg((e,t)=>{const i=()=>{t(new LI(Hg.WS_ABORT));};this.websocket.once(SI.RECONNECTING,i),this.websocket.once(SI.CLOSED,i),this.once("@".concat(s,"-").concat(this.spec.sid),t=>{e(t);});});n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(o);let l=null;try{l=await c;}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i);}return n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l;}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext");}close(){const e="4.20.2"===EC?"0.0.1":EC;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0);}handleResponseError(e){switch(e.code){case WI.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void jC.warning("live stream response already exists stream");case WI.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case WI.LIVE_STREAM_RESPONSE_BAD_STREAM:case WI.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new LI(Hg.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new LI(Hg.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new LI(Hg.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new LI(Hg.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new LI(Hg.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new LI(Hg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw();}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(sS);},6e3);}}function SV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function RV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?SV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):SV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class CV extends dT{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ES,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ES;super(),sh(this,"onLiveStreamWarning",void 0),sh(this,"onLiveStreamError",void 0),sh(this,"onInjectStatusChange",void 0),sh(this,"spec",void 0),sh(this,"retryTimeout",1e4),sh(this,"connection",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"wsRetryConfig",void 0),sh(this,"streamingTasks",new Map()),sh(this,"isStartingStreamingTask",!1),sh(this,"taskMutex",new pS("live-streaming")),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"transcodingConfig",void 0),sh(this,"injectConfig",RV({},BI)),sh(this,"injectLoopTimes",0),sh(this,"uapResponse",void 0),sh(this,"lastTaskId",1),sh(this,"statusError",new Map()),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t;}async setTranscodingConfig(e){const t=RV(RV({},FI),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(jC.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map(e=>RV(RV(RV({},UI),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),function(e){Zg(e.width)||zg(e.width,"config.width",0,1e4),Zg(e.height)||zg(e.height,"config.height",0,1e4),Zg(e.videoBitrate)||zg(e.videoBitrate,"config.videoBitrate",1,1e6),Zg(e.videoFrameRate)||zg(e.videoFrameRate,"config.videoFrameRate"),Zg(e.lowLatency)||Yg(e.lowLatency,"config.lowLatency"),Zg(e.audioSampleRate)||qg(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Zg(e.audioBitrate)||zg(e.audioBitrate,"config.audioBitrate",1,128),Zg(e.audioChannels)||qg(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Zg(e.videoGop)||zg(e.videoGop,"config.videoGop"),Zg(e.videoCodecProfile)||qg(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Zg(e.userCount)||zg(e.userCount,"config.userCount",0,17),Zg(e.backgroundColor)||zg(e.backgroundColor,"config.backgroundColor",0,16777215),Zg(e.userConfigExtraInfo)||Xg(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Zg(e.transcodingUsers)&&(Qg(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach((e,t)=>{MI(e.uid),Zg(e.x)||zg(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Zg(e.y)||zg(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Zg(e.width)||zg(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Zg(e.height)||zg(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Zg(e.zOrder)||zg(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Zg(e.alpha)||zg(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1);})),Zg(e.watermark)||VI(e.watermark,"watermark"),Zg(e.backgroundImage)||VI(e.backgroundImage,"backgroundImage"),e.images&&!Zg(e.images)&&(Qg(e.images,"config.images"),e.images.forEach((e,t)=>{VI(e,"images[".concat(t,"]"));}));}(t);const i=[];t.images&&i.push(...t.images.map(e=>RV(RV(RV({},xI),e),{},{zOrder:255}))),t.backgroundImage&&(i.push(RV(RV(RV({},xI),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(RV(RV(RV({},xI),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map(e=>RV({},e)),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map(e=>"number"==typeof e.uid?cg.resolve(e.uid):pA(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await cg.all(n)).forEach((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e);}),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(NI(r=this.streamingTasks).call(r)).map(e=>e.taskId).join("#")});jC.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig));}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(t=>{jC.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{jC.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"));}).catch(e=>{jC.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e);});});}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t;}async startLiveStreamingTask(e,t,i){var n;if(Array.from(NI(n=this.streamingTasks).call(n)).find(e=>e.mode===RI.INJECT)&&t===RI.INJECT)return new LI(Hg.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===RI.TRANSCODE)throw new LI(Hg.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};jC.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new LI(Hg.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t));}catch(e){throw s(),e;}switch(t){case RI.TRANSCODE:r.transcodingConfig=RV({},this.transcodingConfig);break;case RI.RAW:break;case RI.INJECT:r={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes};}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const n=new cg((t,n)=>{iS(this.retryTimeout).then(()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0;});}),a=await cg.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===RI.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),n]);this.isStartingStreamingTask=!1,jC.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),s();}catch(n){if(s(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n);}}stopLiveStreamingTask(e){return new cg((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new LI(Hg.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t();},this.connection.request("request",{clientRequest:{command:r===RI.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===RI.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==RI.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===RI.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e);}).catch(i);});}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==RI.INJECT)throw new LI(Hg.INVALID_OPERATION,"can not find inject stream task to control");return (await this.connection.request("request",{clientRequest:{command:"ControlStream",url:e,control:t,audioVolume:i,position:n}})).serverResponse;}resetAllTask(){var e;const t=Array.from(NI(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch(t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t);});}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map(),this.isStartingStreamingTask=!1,this.statusError=new Map(),this.cancelToken=sC.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0;}async connect(e){if(this.connection)throw new LI(Hg.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new TV(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(jI.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(jI.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(jI.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(jI.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new LI(Hg.UNEXPECTED_ERROR,"can not get new live streaming address list"));vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e).then(e=>{this.uapResponse=e,t(e.addressList);}).catch(i);}),await this.connection.init(t.addressList),this.connection;}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new LI(Hg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return jC.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n);}case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e);}case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(NI(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(jC.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{jC.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url);}).catch(e=>{jC.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e);}));return;}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void jC.debug("inject stream server status",e);}}hasUrl(e){return this.streamingTasks.has(e);}}class IV{constructor(){sh(this,"destChannelMediaInfos",new Map()),sh(this,"srcChannelMediaInfo",void 0);}setSrcChannelInfo(e){tv(e),this.srcChannelMediaInfo=e;}addDestChannelInfo(e){tv(e),this.destChannelMediaInfos.set(e.channelName,e);}removeDestChannelInfo(e){kI(e),this.destChannelMediaInfos.delete(e);}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo;}getDestChannelMediaInfo(){return this.destChannelMediaInfos;}}function vV(e){if(!(e instanceof IV)){return new LI(Hg.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new LI(Hg.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();}if(0===i.size){return new LI(Hg.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw();}}class yV extends dT{constructor(e,t,i){super(),sh(this,"ws",void 0),sh(this,"requestId",1),sh(this,"heartBeatTimer",void 0),sh(this,"joinInfo",void 0),sh(this,"clientId",void 0),sh(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck();}),sh(this,"onClose",e=>{this.emit("close"),this.dispose();}),sh(this,"onMessage",e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t);}),this.joinInfo=e,this.clientId=t,this.ws=new zv("cross-channel-".concat(this.clientId),i),this.ws.on(SI.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting");}),this.ws.on(SI.CONNECTED,this.onOpen),this.ws.on(SI.ON_MESSAGE,this.onMessage),this.ws.on(SI.CLOSED,this.onClose);}isConnect(){return "connected"===this.ws.state;}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t;}waitStatus(e){return new cg((t,i)=>{const n=window.setTimeout(()=>{i(new LI(Hg.TIMEOUT,"wait status timeout, status: ".concat(e)));},5e3);this.once(e,r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new LI(Hg.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0);}),this.once("dispose",()=>{window.clearTimeout(n),i(new LI(Hg.WS_ABORT));});});}async request(e){if("closed"===this.ws.state)throw new LI(Hg.WS_DISCONNECT);const t=()=>new cg((e,t)=>{this.ws.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.ws.once(SI.CONNECTED,e);});"connected"!==this.ws.state&&(await t());const i=this.sendMessage(e),n=new cg((e,t)=>{const n=()=>{t(new LI(Hg.WS_ABORT));};this.ws.once(SI.RECONNECTING,n),this.ws.once(SI.CLOSED,n),this.once("req_".concat(i),e),iS(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(SI.RECONNECTING,n),this.ws.off(SI.CLOSED,n),t(new LI(Hg.TIMEOUT,"cross channel ws request timeout"));});}),r=await n;if(!r||200!==r.code)throw new LI(Hg.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r;}async connect(e){this.ws.removeAllListeners(SI.REQUEST_NEW_URLS),this.ws.on(SI.REQUEST_NEW_URLS,t=>{t(e);}),await this.ws.init(e);}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close();}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t;}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval(()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date(),requestId:0});},3e3);}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0;}}class AV extends dT{set state(e){e!==this._state&&(e!==qI.RELAY_STATE_FAILURE&&(this.errorCode=zI.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e);}get state(){return this._state;}constructor(e,t,i,n,r){super(),sh(this,"joinInfo",void 0),sh(this,"sid",void 0),sh(this,"clientId",void 0),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"workerToken",void 0),sh(this,"requestId",0),sh(this,"signal",void 0),sh(this,"prevChannelMediaConfig",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"_resolution",void 0),sh(this,"_state",qI.RELAY_STATE_IDLE),sh(this,"errorCode",zI.RELAY_OK),sh(this,"onStatus",e=>{jC.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.SRC_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.DEST_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE));}),sh(this,"onReconnect",async()=>{jC.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",YI.NETWORK_DISCONNECTED),this.state=qI.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==qI.RELAY_STATE_IDLE&&(jC.error("auto restart channel media relay failed",e.toString()),this.errorCode=zI.SERVER_CONNECTION_LOST,this.state=qI.RELAY_STATE_FAILURE);});}),this.joinInfo=e,this.clientId=t,this.sid=rS(),this.signal=new yV(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r;}async startChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_IDLE)throw new LI(Hg.INVALID_OPERATION);this.state=qI.RELAY_STATE_CONNECTING,await this.connect(),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e);}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e;}this.prevChannelMediaConfig=e;}async updateChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e;}async setVideoProfile(e){if(this._resolution=e,this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);const t=this.genMessage(KI.SetVideoProfile);await this.signal.request(t),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"));}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),jC.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=qI.RELAY_STATE_IDLE,this.dispose();}dispose(){jC.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=sC.CancelToken.source(),this.state=qI.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0;}async connect(){const e=await fA(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",YI.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect);}async sendStartRelayMessage(e){const t=this.genMessage(KI.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(KI.SetSdkProfile,e);await this.signal.request(i),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(KI.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",YI.PACKET_JOINED_SRC_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(KI.SetSourceUserId,e);await this.signal.request(r),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(KI.SetDestChannel,e);await this.signal.request(s),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",YI.PACKET_JOINED_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(KI.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",YI.PACKET_SENT_TO_DEST_CHANNEL),this.state=qI.RELAY_STATE_RUNNING,jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution);}async sendUpdateMessage(e){const t=this.genMessage(KI.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",YI.PACKET_UPDATE_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"));}async sendStopRelayMessage(){const e=this.genMessage(KI.StopPacketTransfer);await this.signal.request(e),jC.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"));}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:EC,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.20.2"===s.sdkVersion&&(s.sdkVersion="0.0.1");let o=null,a=null;switch(e){case KI.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case KI.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},s;case KI.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:a.uid+""},s;case KI.SetDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},s;case KI.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case KI.Reconnect:return s.clientRequest={command:"Reconnect"},s;case KI.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case KI.UpdateDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},s;case KI.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height};}return s;}}function bV(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new CU(n=new wU(function(i){i(e[t](n));}),1)};}return t[void 0!==xu&&th||"@@iterator"]=function(){return this;},t.next=function(e){return i?(i=!1,e):n("next",e);},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e);}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e);}),t;}var wV=i(OU);function OV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function NV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function DV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function PV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?DV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class LV extends Nv{get peerConnectionState(){return this.peerConnection.connectionState;}get iceConnectionState(){return this.peerConnection.iceConnectionState;}get currentLocalDescription(){return this.peerConnection.currentLocalDescription;}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription;}get localCodecs(){return [...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"statsFilter",void 0),sh(this,"useRTX",!1),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(LV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=gx(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,PV(PV({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{constructor(e){sh(this,"sessionDesc",void 0),sh(this,"localCapabilities",void 0),sh(this,"rtpCapabilities",void 0),sh(this,"candidates",void 0),sh(this,"iceParameters",void 0),sh(this,"dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,sdkCodec:a,cname:c}=e,d=JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=s,this.localCapabilities=o,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){const o=d.mediaDescriptions[e];if(o.attributes.iceUfrag=t.iceUfrag,o.attributes.icePwd=t.icePwd,o.attributes.fingerprints=i.fingerprints,o.attributes.candidates=n,o.attributes.setup=s,"video"===o.media.mediaType){o.media.fmts=r.videoCodecs.map(e=>e.payloadType.toString(10));let e=r.videoCodecs.filter(e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:bn(i=t.encodingName.toLowerCase()).call(i,a);});0===e.length&&(e=r.videoCodecs),o.attributes.payloads=e,o.attributes.extmaps=r.videoExtensions;}"audio"===o.media.mediaType&&(o.media.fmts=r.audioCodecs.map(e=>e.payloadType.toString(10)),o.attributes.payloads=r.audioCodecs,o.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(o);}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1;}toString(){return JU.print(this.sessionDesc);}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=Cx(t,this.cname),s=this.sessionDesc.mediaDescriptions.find(t=>e===av.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),o=n[0].attributes.label,a=n[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(n),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(r),{id:o,mslabel:a};}batchSend(e){return e.map(e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0);});}stopSending(e){this.sessionDesc.mediaDescriptions.forEach(t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach(t=>{bn(e).call(e,t.attributes.label||"")?r.push(t):i.push(t);}),t.attributes.ssrcGroups.forEach(e=>{var t;bn(t=r.map(e=>e.ssrcId)).call(t,e.ssrcIds[0])||n.push(e);}),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n;});}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}receive(e,t,i){e.forEach((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex(e=>e.attributes.mid===i.kind),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r;});}stopReceiving(e){}updateCandidates(e){e===cv.TCP?this.candidates.forEach(e=>{-1===this.candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this.candidates.push(NV(NV({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}));}):this.candidates=this.candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t;}mungRecvMediaDsec(e,t){const i=YT(e);return Ix(i,t),yx(i,t),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find(t=>e===av.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid);if(n){const e=n.attributes.ssrcs.find(e=>e.attributes.label===t);var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i));}}mungMediaDesc(e){const t=YT(e);return vx(t),function(e){const t=e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}(t),t;}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return [i];}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:s});const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}send(e,t){var i=this;return PU(function*(){const n=yield IU(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map(e=>i.peerConnection.addTrack(e._mediaStreamTrack)),s=yield IU(i.peerConnection.createOffer()),o=JU.parse(s.sdp),a=e.map(e=>{const t=e._mediaStreamTrack,n=o.mediaDescriptions.find(e=>e.attributes.mid===t.kind);if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter(e=>e.attributes.label===t),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find(e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}];}return [{ssrcId:n[0].ssrcId}];}(n,t.id,i.useRTX);});let c;try{c=yield a;}catch(e){throw r.forEach(e=>{bg()&&e.replaceTrack(null),i.peerConnection.removeTrack(e);}),e;}const d=i.mungSendOfferSDP(s.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield IU(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(i.applySendEncodings(r,e)),yield IU(i.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map((e,t)=>{const i=e._mediaStreamTrack.id;return {localSSRC:a[t],id:i};});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{n();}})();}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{bg()&&e.replaceTrack(null),this.peerConnection.removeTrack(e);});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),s=new cg((t,n)=>{const s=setTimeout(()=>{n(new Error("Cannot receive track, id: ".concat(i)));},1e4),o=n=>{const a=Sg();if(("Safari"===a.name&&11===Number(a.version)||Og())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(r);}if(n.track.id===i)return this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(n.track);};this.peerConnection.addEventListener("track",o);}),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return {track:await s,id:i};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map(e=>{if(bg()&&e.track)e.track.enabled=!1;else {const t=e.getParameters();t.encodings.forEach(e=>e.active=!1),e.setParameters(t);}});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map(async e=>{if(bg()&&e.track)e.track.enabled=!0;else {const t=e.getParameters();t.encodings.forEach(e=>e.active=!0),await e.setParameters(t);}});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString();yield IU(t.peerConnection.setLocalDescription(n)),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e);}finally{i();}})();}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter(t=>{var i;return (null===(i=t.track)||void 0===i?void 0:i.id)===e;});1===i.length&&(await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find(e=>{var i;return (null===(i=e.track)||void 0===i?void 0:i.id)===t;});i&&(await i.replaceTrack(e._mediaStreamTrack));}createDataChannels(e,t){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}stopDataChannels(e){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.");}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[],sdpSemantics:"plan-b"};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>{var i;return (null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id;});}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!IA().supportSetRtpSenderParameters)return jC.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof Rw)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(RC("DSCP_TYPE")&&jg()){var s;const e=RC("DSCP_TYPE");bn(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e);}const o=t.getParameters(),a=null===(i=o.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(o,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(o.encodings))),await t.setParameters(o);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];n&&r&&(await this.updateRtpSenderEncodings(r,n));}}catch(e){jC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."));}}mungSendOfferSDP(e,t){const i=JU.parse(e);return t.forEach((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find(e=>e.attributes.mid===n.kind);r&&Ix(r,e);}),JU.print(i);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0;}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map((t,i)=>{let{id:n,mslabel:r}=t;const{kind:s}=e[i];return new cg((e,t)=>{const i=setTimeout(()=>{t(new Error("Cannot receive track, id: ".concat(n)));},1e4),o=t=>{const a=Sg();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(s,n,t.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:r,id:n});}if(t.track.id===n)return this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:t.track,id:n});};this.peerConnection.addEventListener("track",o);});}),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await cg.all(t);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=LV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function kV(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function MV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function UV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?MV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):MV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}DI([kV,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],LV.prototype,"connect",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],LV.prototype,"stopSending",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,Object]),PI("design:returntype",cg)],LV.prototype,"receive",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],LV.prototype,"stopReceiving",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],LV.prototype,"muteRemote",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],LV.prototype,"unmuteRemote",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],LV.prototype,"muteLocal",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],LV.prototype,"unmuteLocal",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],LV.prototype,"close",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],LV.prototype,"updateEncoderConfig",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],LV.prototype,"updateSendParameters",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],LV.prototype,"replaceTrack",null),DI([kV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],LV.prototype,"getRemoteSSRC",null);const xV="9",VV=4e4;function FV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function BV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?FV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):FV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class jV extends Nv{get currentLocalDescription(){return this.peerConnection.currentLocalDescription;}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription;}get peerConnectionState(){return this.peerConnection.connectionState;}get iceConnectionState(){return this.peerConnection.iceConnectionState;}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null;}get localCodecs(){return [...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"remoteCodecs",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"recoveredDataChannelIds",[]),sh(this,"currentDataChannelId",1),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(jV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i});}else jC.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.");}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=Px(i),this.initialOffer=e,BV(BV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n");this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:VV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}preloadRemoteMedia(){const e=RC("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;s<e;s++){const e=2*s+2e4,o=2*s+VV,{ssrcs:a,ssrcGroups:c}=Cx([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=Cx([{ssrcId:o,rtx:RC("USE_SUB_RTX")?o+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s+1)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||1===t&&(bg()||Lg())||0===t&&RC("USE_SUB_RTX")||kg()?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0};}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t};}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n);}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t);}),{mids:i,needExchangeSDP:n};}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||wg()||kg()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0");}),this.updateBundleMids();}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r]);}),this.updateBundleMids();}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}updateCandidates(e){const t=this._candidates.filter(e=>"udp"===e.transport);if(e===cv.TCP){if(0===t.length)return;if(RC("TCP_CANDIDATE_ONLY")){const e=this._candidates.filter(e=>"tcp"===e.transport);t.forEach(t=>{-1===e.findIndex(e=>e.connectionAddress===t.connectionAddress)&&e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}));}),this._candidates=e;}else {const e=[];t.forEach(t=>{e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}));}),this._candidates=[...t,...e];}}else if(e===cv.RELAY){if(0!==t.length)return;{const e=this._candidates.filter(e=>"tcp"===e.transport);e.forEach(e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}));}),this._candidates=[...t,...e];}}else 0===t.length?(this._candidates.filter(e=>"tcp"===e.transport).forEach(e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}));}),this._candidates=t):this._candidates=this._candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t;}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex(i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid);}return !1;}return n;});}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return {mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:xV,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0};}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter(e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction);else if(a=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from ").concat(e.attributes.payloads," to ").concat(l)),e.attributes.payloads=l,e.media.fmts=t;}),!0;}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs;}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:s}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});const u=this.peerConnection.getTransceivers()[0];if(null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver),RC("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t);}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)jC.debug("[P2PConnection] Channels are already available and can be reused directly.");else {const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i);}t.forEach(e=>{e._updateOriginDataChannel(i);});const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),jC.debug("[P2PConnection] createDataChannels by exchanging SDP.");}else jC.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return;}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()));}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e);}catch(e){throw e instanceof Kg?e:new Kg(Hg.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()));}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r,transceiver:o};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive no need to exchange SDP."));return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:t.receiver.track,id:e,transceiver:t};});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()));}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()));}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e);}finally{i();}})();}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1;}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return {local:BV(BV({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:BV(BV({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})};}return this.statsFilter.getSelectedCandidatePair();}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state));},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e);};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e));},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();jC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"));}}));}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null));}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack);}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),(bn(s=e._hints).call(s,jA.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof Rw&&!this.isVP8Simulcast(r)&&(await this.updateRtpSenderEncodings(r,n.sender));}}catch(e){jC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."));}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach((e,t)=>{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof Rw&&!bn(i=d._hints).call(i,jA.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof Rw&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r));}}}isVP8Simulcast(e){var t,i,n,r,s;return !!(e instanceof Rw&&RC("SIMULCAST")&&"vp8"===this.store.codec&&!bn(t=e._hints).call(t,jA.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=jV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function GV(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function WV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function HV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?WV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):WV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}DI([GV,PI("design:type",Function),PI("design:paramtypes",[Array,Array]),PI("design:returntype",cg)],jV.prototype,"updateRemoteRTPCapabilities",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],jV.prototype,"connect",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Object,Array]),PI("design:returntype",cg)],jV.prototype,"createDataChannels",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,Object]),PI("design:returntype",cg)],jV.prototype,"receive",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],jV.prototype,"batchReceive",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],jV.prototype,"stopReceiving",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],jV.prototype,"muteRemote",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],jV.prototype,"unmuteRemote",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],jV.prototype,"muteLocal",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],jV.prototype,"unmuteLocal",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],jV.prototype,"close",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],jV.prototype,"updateEncoderConfig",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],jV.prototype,"updateSendParameters",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],jV.prototype,"replaceTrack",null),DI([GV,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],jV.prototype,"getRemoteSSRC",null);const KV="v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0\na=msid-semantic: WMS\na=ice-lite\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:0\n",YV="9",qV=2e4,zV=4e4;class JV{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=JU.parse(KV);this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}updateRemoteRTPCapabilities(e){const t=JU.parse(KV);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=i.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1;}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;s<e;s++){const e=2*s+qV,o=2*s+zV,{ssrcs:a,ssrcGroups:c}=Cx([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=Cx([{ssrcId:o,rtx:RC("USE_SUB_RTX")?o+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||bg()||Og()||Lg()||0===t&&RC("USE_SUB_RTX")?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0};}}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n);}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t);}),{mids:i,needExchangeSDP:n};}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||wg()||bg()||Og()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0");}),this.updateBundleMids();}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r]);}),this.updateBundleMids();}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}updateCandidates(e){e===cv.TCP?this._candidates.forEach(e=>{-1===this._candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this._candidates.push(HV(HV({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}));}):this._candidates=this._candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t;}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex(i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid);}return !1;}return n;});}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter(e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction);else if(a=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from ").concat(e.attributes.payloads," to ").concat(l)),e.attributes.payloads=l,e.media.fmts=t;}),!0;}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs;}}function XV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function QV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?XV(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):XV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}class ZV extends Nv{get currentLocalDescription(){return this.peerConnection.currentLocalDescription;}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription;}get peerConnectionState(){return this.peerConnection.connectionState;}get iceConnectionState(){return this.peerConnection.iceConnectionState;}get localCodecs(){let e;return this.localCapabilities&&(e=Px(this.localCapabilities)),[...new Set(e&&e.send.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t,i){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"remoteCodecs",void 0),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("NVExtentionsConnection-mutex")),sh(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,QV(QV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new LI(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new JV({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:Px(this.localCapabilities),cname:s});const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i});}else jC.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.");}async updateRemoteConnect(e){var t,i,n,r;(null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0)&&(null===(r=this.remoteSDP)||void 0===r||r.updateRemoteCodec([],this.remoteCodecs,this.store.codec));null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const s=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),jC.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.");}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From NVExtentionsConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof LI?e:new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.");t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);return i&&"open"===i.readyState?jC.debug("[P2PConnection] Channels are already available and can be reused directly."):(i=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)),void t.forEach(e=>{e._updateOriginDataChannel(i);});}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,"NVExtentionsConnection.createDataChannels failed; ".concat(e.toString()));}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e);}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,"NVExtentionsConnection.stopDataChannels failed; ".concat(e.toString()));}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."));}else jC.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r};}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()));}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),jC.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.");}else jC.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:t.receiver.track,id:e};});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(e.toString()));}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(e.toString()));}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From NVExtentionsConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("restartICE change iceTransportPolicy from [".concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("restart ICE failed, abort operation",e);}finally{i();}})();}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}getP2PConnectionParams(){var e;if(null===(e=this.peerConnection.currentLocalDescription)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error();return QV(QV({},Tx(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities});}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l<e.length;l++){const u=e[l],h=t[l];if(h&&h instanceof Rw){var i,n,r;if(this.isVP8Simulcast(h))continue;const e={},t={};switch(h._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced";}var s,o,a,c;if(null!==(i=h._encoderConfig)&&void 0!==i&&i.bitrateMax)t.maxBitrate=1e3*(null===(s=h._encoderConfig)||void 0===s?void 0:s.bitrateMax);if(bn(n=h._hints).call(n,jA.LOW_STREAM))null!==(o=h._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=Sy(h._encoderConfig.frameRate)),null!==(a=h._encoderConfig)&&void 0!==a&&a.scaleResolutionDownBy&&(null===(c=h._encoderConfig)||void 0===c?void 0:c.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=h._encoderConfig.scaleResolutionDownBy);if(RC("DSCP_TYPE")&&jg()){var d;const e=RC("DSCP_TYPE");bn(d=["very-low","low","medium","high"]).call(d,e)&&(t.networkPriority=e);}const l=u.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];wg()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await u.sender.setParameters(l);}}}catch(e){jC.debug("Apply RTPSendEncodings failed.");}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach((e,t)=>{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof Rw&&!bn(i=d._hints).call(i,jA.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof Rw&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r));}}}isVP8Simulcast(e){var t,i,n,r,s;return !!(e instanceof Rw&&RC("SIMULCAST")&&"vp8"===this.store.codec&&!bn(t=e._hints).call(t,jA.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("exchanging ".concat(i," ").concat(t," SDP during NVExtentionsConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=ZV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function $V(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From NVExtentionsConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function eF(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=wV,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new tF(t.call(e));i="@@asyncIterator",n="@@iterator";}throw new TypeError("Object is not async iterable");}function tF(e){function t(e){if(Object(e)!==e)return cg.reject(new TypeError(e+" is not an object."));var t=e.done;return cg.resolve(e.value).then(function(e){return {value:e,done:t};});}return tF=function(e){this.s=e,this.n=e.next;},tF.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments));},return:function(e){var i=this.s.return;return void 0===i?cg.resolve({value:e,done:!0}):t(i.apply(this.s,arguments));},throw:function(e){var i=this.s.return;return void 0===i?cg.reject(e):t(i.apply(this.s,arguments));}},new tF(e);}DI([$V,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],ZV.prototype,"connect",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Array,Array]),PI("design:returntype",cg)],ZV.prototype,"updateRemoteRTPCapabilities",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],ZV.prototype,"updateRemoteConnect",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Object,Array]),PI("design:returntype",cg)],ZV.prototype,"createDataChannels",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,Object]),PI("design:returntype",cg)],ZV.prototype,"receive",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],ZV.prototype,"batchReceive",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],ZV.prototype,"stopReceiving",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],ZV.prototype,"muteRemote",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],ZV.prototype,"unmuteRemote",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],ZV.prototype,"muteLocal",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],ZV.prototype,"unmuteLocal",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ZV.prototype,"close",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],ZV.prototype,"updateEncoderConfig",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],ZV.prototype,"updateSendParameters",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],ZV.prototype,"replaceTrack",null),DI([$V,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],ZV.prototype,"getRemoteSSRC",null);class iF extends Nv{get currentLocalDescription(){return this.peerConnection.currentLocalDescription;}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription;}get peerConnectionState(){return this.peerConnection.connectionState;}get iceConnectionState(){return this.peerConnection.iceConnectionState;}get localCodecs(){return this._p2pConnection.localCodecs;}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"cname",void 0),sh(this,"mutex",new pS("DataChannelConnection-mutex")),sh(this,"dataChannel",void 0),sh(this,"_p2pConnection",void 0),sh(this,"establishPromise",void 0),sh(this,"_nvMedia",void 0),this.store=t,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(iF.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new ZV(e,t,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise;}async establish(){var e;const t=null===(e=this._nvMedia)||void 0===e?void 0:e.getLocalRtpCapabilities();return await this._p2pConnection.establish(t);}getP2PConnectionParams(){return this._p2pConnection.getP2PConnectionParams();}async connect(e,t,i,n,r,s){return this.cname=s,await this._p2pConnection.connect(e,t,i,n,r,s),await new cg((e,t)=>{const n=setTimeout(()=>{this.closeSignal(),t(new LI(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(i))));},2e3);this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void e();},this.dataChannel.onerror=e=>{this.closeSignal(),t(e);};}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)};}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t);}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From DataChannelConnection.send"));try{return yield*bV(eF(n._p2pConnection.send(e,t,i)));}finally{r();}})();}async stopSending(e,t){return this._p2pConnection.stopSending(e,t);}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t);}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e);}async receive(e,t,i,n){return this._nvMedia?(jC.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(jC.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n));}async batchReceive(e){return [...(await this._p2pConnection.batchReceive(e))];}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e);}async muteRemote(e){return await this._p2pConnection.muteRemote(e);}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e);}async muteLocal(e){return await this._p2pConnection.muteLocal(e);}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e);}restartICE(e){var t=this;return PU(function*(){return yield*bV(eF(t._p2pConnection.restartICE(e)));})();}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection);}getStats(){return this._p2pConnection.getStats();}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e);}updateRemoteConnect(e){var t;null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e);}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t);}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t);}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t);}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t);}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i);},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t);},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t);};}closeSignal(){this.dataChannel.close(),this.peerConnection.close();}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0;}setConfiguration(e){this._p2pConnection.setConfiguration(e);}}function nF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function rF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function sF(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?rF(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):rF(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}function oF(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=wV,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new aF(t.call(e));i="@@asyncIterator",n="@@iterator";}throw new TypeError("Object is not async iterable");}function aF(e){function t(e){if(Object(e)!==e)return cg.reject(new TypeError(e+" is not an object."));var t=e.done;return cg.resolve(e.value).then(function(e){return {value:e,done:t};});}return aF=function(e){this.s=e,this.n=e.next;},aF.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments));},return:function(e){var i=this.s.return;return void 0===i?cg.resolve({value:e,done:!0}):t(i.apply(this.s,arguments));},throw:function(e){var i=this.s.return;return void 0===i?cg.reject(e):t(i.apply(this.s,arguments));}},new aF(e);}DI([nF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],iF.prototype,"connect",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[Array,Array]),PI("design:returntype",cg)],iF.prototype,"updateRemoteRTPCapabilities",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[Object,Array]),PI("design:returntype",cg)],iF.prototype,"createDataChannels",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,Object]),PI("design:returntype",cg)],iF.prototype,"receive",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],iF.prototype,"stopReceiving",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],iF.prototype,"muteRemote",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],iF.prototype,"unmuteRemote",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],iF.prototype,"muteLocal",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],iF.prototype,"unmuteLocal",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iF.prototype,"close",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],iF.prototype,"updateEncoderConfig",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],iF.prototype,"updateSendParameters",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],iF.prototype,"replaceTrack",null),DI([nF,PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],iF.prototype,"getRemoteSSRC",null);class cF extends dT{get state(){return this._state;}set state(e){const t=this._state;this._state=e,this.emit(hv.StateChange,t,this._state);}constructor(e,t){super(),sh(this,"store",void 0),sh(this,"statsUploader",void 0),sh(this,"connection",void 0),sh(this,"localTrackMap",new Map()),sh(this,"remoteUserMap",new Map()),sh(this,"localDataChannels",[]),sh(this,"remoteDataChannelMap",new Map()),sh(this,"pendingLocalTracks",[]),sh(this,"pendingRemoteTracks",[]),sh(this,"pendingLocalDataChannels",[]),sh(this,"pendingRemoteDataChannels",[]),sh(this,"statsCollector",void 0),sh(this,"isPlanB",!1),sh(this,"shouldForwardP2PCreation",void 0),sh(this,"iceFailedCount",0),sh(this,"dtlsFailedCount",0),sh(this,"mutex",new pS("P2PChannel-mutex")),sh(this,"_state",uv.Disconnected),sh(this,"_pcStatsUploadType",RC("NEW_ICE_RESTART")?dv.FIRST_CONNECTION:dv.OLD_FIRST_CONNECTION),sh(this,"_isInRestartIce",!1),sh(this,"_isStartRestartIce",!1),sh(this,"_restartStates",["disconnected","failed"]),sh(this,"_restartTimer",void 0),sh(this,"_isFirstConnected",!0),sh(this,"handleMuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){s[1].track._originMediaStreamTrack.stop();}await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createMuteMessage(r);await yT(this,hv.RequestMuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){const t=s[1];if(t.track._originMediaStreamTrack.stop(),!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}else {const i=Gx(e,bT(this,hv.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createUnmuteMessage(r);await yT(this,hv.RequestUnmuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),await this.connection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceMixingTrack",async(e,t,i,n)=>{if(!this.connection||this.state!==uv.Connected)return void t();const r=dV([e]);let s;jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof n&&n||(s=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t();}catch(e){i(e);}finally{var o;null===(o=s)||void 0===o||o();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!this.connection||!i||this.state!==uv.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t);}if(i[0]===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetRTCStats",e=>{e(this.statsCollector.getRTCStats());}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!IA().supportUnifiedPlan||RC("CHROME_FORCE_PLAN_B")&&jg(),this.shouldForwardP2PCreation=RC("FORWARD_P2P_CREATION")&&IA().supportPCSetConfiguration&&function(){const e=Rg();return e===_g.ANDROID||e===_g.IOS||e===_g.HARMONY_OS;}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection));}async startP2PConnection(e,t){var i;this.state=uv.New;const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new iF(e,this.store):this.isPlanB?new LV(e,this.store):new jV(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=RC("NEW_ICE_RESTART")?dv.FIRST_CONNECTION:dv.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise;}async connect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof iF?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected);}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter(e=>{var t;let[i]=e;return bn(t=[lv.LocalVideoLowTrack,lv.LocalVideoTrack]).call(t,i);}),i=t.map(e=>{let[,{id:t}]=e;return t;}),n=t.map(e=>{let[t]=e;return t;});if(this.connection instanceof jV){if(eI.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!bn(e).call(e,this.store.codec)){const t=["vp8","h264"].find(t=>bn(e).call(e,t));t&&(this.store.codec=t,jC.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")));}this.connection.updateRemoteRTPCapabilities(i,e);}}async preConnect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const o=await this.connection.connect(e,t,i,n,r,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected,o;}getEstablishParams(){if(this.connection instanceof iF)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams");}async publishDataChannel(e){if(!this.connection||this.state!==uv.Connected){if(this.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return void e.forEach(e=>{var t;bn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e);});}const t=this.filterTobePublishedDataChannels(e);0!==t.length&&(t.forEach(e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t);}),await this.connection.createDataChannels(this.store.uid,t),t.forEach(e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t);}));}publish(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==uv.Connected){if(n.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter(e=>-1===n.pendingLocalTracks.indexOf(e));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t));}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));yield*bV(oF(n.doPublish(n.connection,s)));}finally{r();}})();}doPublish(e,t){var i=this;return PU(function*(){t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?"audio":"video",r);}),i.bindLocalTrackEvents(t);const n=t.map(e=>{let{track:t}=e;return t;}),r=yield IU(e.send(t.map(e=>{let{track:t}=e;return t;}),i.store.codec,i.store.audioCodec)),s=(yield IU(r.next())).value,o=i.createGatewayPublishMessage(t,s);let a;try{a=yield o;}catch(e){throw r.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&t.forEach(e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t);}),i.unbindLocalTrackEvents(t),e;}const c=i.mapPubResToRemoteConfig(o,a),d=(yield IU(r.next(c))).value,l=RC("ENABLE_VIDEO_SEI");n.forEach(async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===av.VIDEO?await async function(e,t){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(mU.has(e))return;if(!e.track)return;const i={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams();}catch(e){return void jC.error("create video-encoded-streams error",e&&e.message);}let s=[];t.on("sei-to-send",e=>{s.push(e);});const o=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const o=s.shift();o&&(t.data=EU(t.data,o)),r.enqueue(t);}});r.readable.pipeThrough(o).pipeTo(r.writable);}else {if(!bg())return;{if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const r=lU(),s=new MessageChannel();await new cg(e=>r.onmessage=t=>{"registered"===t.data&&e(void 0);});const o=new RTCRtpScriptTransform(r,{name:"tx",port:s.port2},[s.port2]);e.transform=o,await new cg(e=>r.onmessage=t=>{"started"===t.data&&e(void 0);}),t.on("sei-to-send",e=>{s.port1.postMessage({sei:e});}),s.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));},i.worker=r;}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n);}const t=mU.get(e);if(t){mU.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate();}catch(e){jC.warning(e&&e.message);}}}mU.set(e,i),e.track.addEventListener("ended",n);}(t.sender,e):e.trackMediaType===av.AUDIO&&(await async function(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(uU.has(e))return;if(!e.track)return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.error("create audio-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n);}});n.readable.pipeThrough(r).pipeTo(n.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"tx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>n.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i));},t.worker=n;}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i);}const t=uU.get(e);if(t){uU.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate();}catch(e){jC.warning(e&&e.message);}}}uU.set(e,t),e.track.addEventListener("ended",i);}(t.sender)));}),t.forEach(e=>{let{type:t}=e;i.statsCollector.addLocalStats(t);}),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?"audio":"video",void 0,r);});})();}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof Rw))return jC.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof jV||this.connection instanceof LV))return jC.warn("[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=yy(e,t)),i.maxFramerate=e.framerate?Sy(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i;}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==lv.LocalVideoLowTrack||!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else {const t=n._originMediaStreamTrack;if(!t.canvas)return jC.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Sy(t.width)),t.height&&(i.height=Sy(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=Tb(()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture();},Sy(t.framerate)));}(t,e);}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&"object"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),jC.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n);}publishLowStream(e){var t=this;return PU(function*(){if(!t.connection||t.state!==uv.Connected)return;const i=yield IU(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(lv.LocalVideoTrack);if(!r)throw new Kg(Hg.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(lv.LocalVideoLowTrack))throw new Kg(Hg.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const s=[{track:t.getLowVideoTrack(r.track,e),type:lv.LocalVideoLowTrack}];if(yield*bV(oF(t.doPublish(t.connection,s))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(lv.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield IU(t.connection.muteLocal([e])));}}finally{i();}})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(jC.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await vT(this,hv.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]);}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==av.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==av.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1);}if(e)await vT(this,hv.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===av.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(hv.MediaReconnectEnd,t.uid);}),this.pendingRemoteTracks=[];}async unpublish(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach(e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1);});const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find(e=>"videoLowTrack"===e[0]);if(i){i[1].track.close();}return this.doUnpublish(this.connection,t);}async unpublishDataChannel(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach(e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1);});const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach(e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1);}),0===this.localDataChannels.length&&(await this.connection.stopDataChannels(this.store.uid)),t.map(e=>e.id)):void 0;}async unpublishLowStream(){if(!this.connection||this.state!==uv.Connected)return;const e=this.localTrackMap.get(lv.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[lv.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t);}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return {type:t,track:i};})),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t);}),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i;}async subscribeDataChannel(e,t){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter(t=>{var i;return !(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id));});if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach(t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex(i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id;});-1!==n&&this.pendingRemoteDataChannels.splice(n,1);}),i.map(e=>e.id);}async subscribe(e,t,i,n,r){var s;if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let o,a,c;if(r){const i=r.find(e=>{let{stream_type:i}=e;return i===t;});if(!i)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof jV&&(c=n.transceiver),o=n.track,a=n.id;}else {const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof jV&&(c=r.transceiver),o=r.track,a=r.id;}t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Nw(o,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new Ow(o,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),RC("ENABLE_VIDEO_SEI")&&c&&(t==av.VIDEO?await gU(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t);}}):t==av.AUDIO&&(await pU(c.receiver)));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex(i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r;});-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(hv.MediaReconnectEnd,e.uid));}async massSubscribe(e){return this.massSubscribeNoLock(e);}async massSubscribeNoLock(e){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter(e=>{var t;let{user:i,mediaType:n}=e;return !(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n));});const t=await this.connection.batchReceive(e.map(e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return {kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)};}));e.forEach((e,i)=>{let{user:n,mediaType:r}=e;const{track:s,id:o,transceiver:a}=t[i];r===av.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(s):(n._audioTrack=new Nw(s,n.uid,n._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(n._audioTrack.getTrackId()))),a&&n._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(s):(n._videoTrack=new Ow(s,n.uid,n._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(n._videoTrack.getTrackId()))),a&&n._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._videoTrack));const c=this.remoteUserMap.get(n);c?c.set(r,o):this.remoteUserMap.set(n,new Map([[r,o]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex(e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i;});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,n.uid));});}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter(i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid;});if(n.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),this.connection&&this.state===uv.Connected||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0;}}),!this.connection||this.state!==uv.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map(e=>{let[,{id:t}]=e;return t;}));const s=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach(e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),s;}async unsubscribeDataChannel(e,t){if(t.forEach(e=>{const t=this.pendingRemoteDataChannels.findIndex(t=>t.id===e.id);-1!==t&&this.pendingRemoteDataChannels.splice(t,1);}),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach(e=>{e._close();});const n=this.remoteDataChannelMap.get(e);return i.forEach(e=>{n&&n.delete(e.id);}),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map(e=>e.id);}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e);}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter(e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid;});e.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),t=t.concat(e);}if(!this.connection||this.state!==uv.Connected)return void t.forEach(e=>{let{user:t,kind:i}=e;var n;if(i===av.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;}});const i=BT(e).call(e,(e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r);},[]);if(0===i.length)return;await this.connection.stopReceiving(i.map(e=>{let[,{id:t}]=e;return t;}));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach(e=>{let[t,{kind:i}]=e;var n,r;i===av.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===av.AUDIO){var s;this.unbindRemoteTrackEvents(t._audioTrack),null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0;}}),n;}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1);}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t);}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;}).concat(i.trackList);}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;});}getAllDataChannels(){return this.localDataChannels;}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new pS("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e);});}e.track.close();}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=uv.Disconnected;}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats();}getRemoteVideoIsReady(e){var t;return (null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1;}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return {width:e.track._videoWidth||0,height:e.track._videoHeight||0};}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0;}getLocalMedia(e){return this.localTrackMap.get(e);}hasLocalMedia(){return this.localTrackMap.size>0;}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{};}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return {uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0};});const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.connection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop());}),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.MediaReconnectStart,t.uid);}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach(e=>{this.pendingLocalDataChannels.push(e);}),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteDataChannel(t,e);});}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")));}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&r===t)return !0;}return !1;}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t});}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return !0;}return !1;}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t});}restartICE(e){var t=this;return PU(function*(){if(!t.connection||t.state!==uv.Connected||t.connection instanceof iF)return;const i=yield IU(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield IU(t.connection.restartICE(e));const r=yield IU(n.next());if(r.done)return;const s=r.value,o=yield s;switch(t.reportPCDisconnectedOrFailed(e),e){case cv.TCP:t._pcStatsUploadType=dv.TCP_RESTART;break;case cv.RELAY:t._pcStatsUploadType=dv.RELAY_RESTART;break;default:t._pcStatsUploadType=dv.OLD_RESTART;}t._isInRestartIce=!0,n.next(o);}catch(e){var r;null===(r=n)||void 0===r||r.throw(e);}finally{i();}})();}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find(e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId)),r=e.audioSend.find(e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId));if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5;}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t;}async muteLocalTrack(e){return new cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}async replaceTrack(e,t){var i;if(jC.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==uv.Connected)return;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e);}if(r===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=HT(e=e.filter(e=>-1===r.indexOf(e)));let s,o=!1;const a=this.localTrackMap.get(lv.LocalAudioTrack);for(const r of e){if(r instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(r instanceof ew)if(a){const e=a.track;if(e instanceof nw)cV([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else {const t=dV([e,r]);jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t);}}else if(s instanceof nw)cV([r]),s.addAudioTrack(r);else if(s||!r._useAudioElement&&IA().webAudioMediaStreamDest&&!r._bypassWebAudio){s=dV(s?[r,s]:[r]);}else s=r;}return s&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(s.getTrackId(),"]")),n.push({track:s,type:lv.LocalAudioTrack})),n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}filterTobePublishedDataChannels(e){return e=(e=HT(e)).filter(e=>-1===this.localDataChannels.findIndex(t=>t.id===e.id));}filterTobeUnpublishedDataChannels(e){return e=(e=(e=HT(e)).filter(e=>-1!==this.localDataChannels.indexOf(e))).filter(e=>e._originDataChannel);}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)));}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return {track:i,type:t};})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.GET_RTC_STATS,this.handleGetRTCStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,s,{track:o,type:a}=e;switch(a){case lv.LocalAudioTrack:r=JI.Audio,s={dtx:o instanceof tw&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case lv.LocalVideoTrack:r=bn(n=o._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});break;case lv.LocalVideoLowTrack:r=JI.Low,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});}return {stream_type:r,attributes:s,ssrcs:t[i]};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC});});}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t);});}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(hv.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),RC("NEW_ICE_RESTART")){var i;if(bn(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(t));"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE,t);}},i=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),jC.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},n=RC("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout(()=>{if(RC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&IA().supportPCSetConfiguration)t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);else if(wg())t(cv.UDP),this._restartTimer=window.setTimeout(i,4e3);else {if(t(cv.TCP),IA().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout(()=>{t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);},n));this._restartTimer=window.setTimeout(i,n);}},800));}}else {if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{if("disconnected"===e.iceConnectionState&&RC("ICE_RESTART")){"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE);}},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},4e3);"failed"===t&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect());}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i);},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);};}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0;}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}]);}else Array.from(n.entries()).forEach(t=>{let[n,r]=t;i.push([e,{kind:n,id:r}]);});return i;}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach(t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t);}),i;}createUnsubscribeMessage(e){const t=[];return e.forEach(e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}));}}),t;}createUnsubscribeAllMessage(e){const t=new Map();return e.forEach(e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===av.VIDEO?e|=ZI.Video:e|=ZI.Audio,t.set(i,e);}else n===av.VIDEO?t.set(i,ZI.Video):t.set(i,ZI.Audio);}),{users:Array.from(t.entries()).map(e=>{let[t,i]=e;return {stream_id:t.uid,stream_type:i};})};}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t));});}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink)),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}));}isP2PDisconnected(){if(this.connection){return "connected"!==this.connection.peerConnectionState;}return !0;}mapPubResToRemoteConfig(e,t){return e.map((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find(e=>{let{stream_type:t}=e;return r===t;}))||void 0===n?void 0:n.attributes;});}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof ew){var t;const n=this.filterTobeUnmutedTracks(e[i]);if(0===n.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(n.map(e=>{let[,{id:t}]=e;return t;})));const r=this.createUnmuteMessage(n);return void(await yT(this,hv.RequestUnmuteLocal,r));}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return !(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e));},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks();}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0;}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&(await vT(this,hv.RequestUnpublishForReconnectPC,t)),this.disconnectForReconnect(),this.emit(hv.RequestReconnectPC);}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");}}getLowVideoTrack(e,t){const i=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=sF(sF({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,sF(sF({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.on("sei-to-send",e=>{o.emit("sei-to-send",e);}),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock");}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof jV){var r,s,o,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();eI.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(s=h.candidateType)&&void 0!==s?s:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(o=p.protocol)&&void 0!==o?o:"",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i});}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0});}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return !1;const n=this.remoteUserMap.get(e);if(!n)return !1;const r=n.get(t);if(!r)return !1;const s=await this.connection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] reset connection to ").concat(e)),this.state===uv.Connected?(jC.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===$I.datachannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)));}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof jV&&("disconnected"!==this.connection.iceConnectionState&&"checking"!==this.connection.iceConnectionState&&"failed"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===dv.TCP_RESTART&&e===cv.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,dv.DISCONNECTED_OR_FAILED)));}}function dF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s);}finally{i();}},i;}function lF(e){let t=RF();return function(e,t){let i=e.appId;void 0!==i&&(MF(t,10),wF(t,i));let n=e.cid;void 0!==n&&(MF(t,16),MF(t,n));let r=e.cname;void 0!==r&&(MF(t,26),wF(t,r));let s=e.deviceId;void 0!==s&&(MF(t,34),wF(t,s));let o=e.elapse;void 0!==o&&(MF(t,40),UF(t,o));let a=e.fileSize;void 0!==a&&(MF(t,48),UF(t,TF(a)));let c=e.height;void 0!==c&&(MF(t,56),UF(t,TF(c)));let d=e.jpg;void 0!==d&&(MF(t,66),MF(t,d.length),function(e,t){let i=yF(e,t.length);e.bytes.set(t,i);}(t,d));let l=e.networkType;void 0!==l&&(MF(t,72),UF(t,TF(l)));let u=e.osType;void 0!==u&&(MF(t,80),UF(t,TF(u)));let h=e.requestId;void 0!==h&&(MF(t,90),wF(t,h));let p=e.sdkVersion;void 0!==p&&(MF(t,98),wF(t,p));let _=e.sequence;void 0!==_&&(MF(t,104),UF(t,TF(_)));let E=e.sid;void 0!==E&&(MF(t,114),wF(t,E));let m=e.timestamp;void 0!==m&&(MF(t,120),UF(t,m));let f=e.uid;void 0!==f&&(MF(t,128),MF(t,f));let g=e.vid;void 0!==g&&(MF(t,136),MF(t,g));let T=e.width;void 0!==T&&(MF(t,144),UF(t,TF(T)));let S=e.service;void 0!==S&&(MF(t,152),MF(t,S));let R=e.callbackData;void 0!==R&&(MF(t,162),wF(t,R));let C=e.jpgEncryption;void 0!==C&&(MF(t,168),MF(t,C));let I=e.requestType;void 0!==I&&(MF(t,176),MF(t,I));let v=e.scorePorn;void 0!==v&&(MF(t,185),LF(t,v));let y=e.scoreSexy;void 0!==y&&(MF(t,193),LF(t,y));let A=e.scoreNeutral;void 0!==A&&(MF(t,201),LF(t,A));let b=e.scene;void 0!==b&&(MF(t,208),MF(t,b));let w=e.ossFilePrefix;void 0!==w&&(MF(t,218),wF(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){MF(t,226);let i=RF();pF(e,i),MF(t,i.limit),OF(t,i),CF(i);}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i);}(t);}function uF(e){return function(e){let t={};e:for(;!vF(e);){let i=kF(e);switch(i>>>3){case 0:break e;case 1:t.code=kF(e);break;case 2:t.msg=bF(e,kF(e));break;case 3:{let i=_F(e);t.data=hF(e),e.limit=i;break;}default:EF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function hF(e){let t={};e:for(;!vF(e);){let i=kF(e);switch(i>>>3){case 0:break e;case 1:t.requestId=bF(e,kF(e));break;case 2:t.requestType=kF(e)>>>0;break;case 3:t.scorePorn=PF(e);break;case 4:t.scoreSexy=PF(e);break;case 5:t.scoreNeutral=PF(e);break;case 6:t.requestScene=kF(e)>>>0;break;case 7:t.scene=kF(e)>>>0;break;default:EF(e,7&i);}}return t;}function pF(e,t){let i=e.service;void 0!==i&&(MF(t,8),MF(t,i));let n=e.vendor;void 0!==n&&(MF(t,16),MF(t,n));let r=e.token;void 0!==r&&(MF(t,26),wF(t,r));let s=e.callbackUrl;void 0!==s&&(MF(t,34),wF(t,s));}function _F(e){let t=kF(e),i=e.limit;return e.limit=e.offset+t,i;}function EF(e,t){switch(t){case 0:for(;128&NF(e););break;case 2:IF(e,kF(e));break;case 5:IF(e,4);break;case 1:IF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],cF.prototype,"startP2PConnection",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"connect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",void 0)],cF.prototype,"updateRemoteRTPCapabilities",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"preConnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"publishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublish",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"unpublishLowStream",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"subscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number,Number,Array]),PI("design:returntype",cg)],cF.prototype,"subscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massSubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Boolean]),PI("design:returntype",cg)],cF.prototype,"unsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"unsubscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massUnsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"muteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"unmuteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"hasRemoteMediaWithLock",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"disconnectForReconnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],cF.prototype,"updateBitrateLimit",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],cF.prototype,"remoteMediaSsrcChanged",null);let mF=new Float32Array(1);new Uint8Array(mF.buffer);let fF=new Float64Array(1),gF=new Uint8Array(fF.buffer);function TF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let SF=[];function RF(){const e=SF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0};}function CF(e){SF.push(e);}function IF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function vF(e){return e.offset>=e.limit;}function yF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function AF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function bF(e,t){let i=AF(e,t),n=String.fromCharCode,r=e.bytes,s="<22>",o="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+i];0==(128&u)?o+=n(u):192==(224&u)?e+1>=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function wF(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4;}MF(e,n);let r=yF(e,n),s=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?s[r++]=n:(n<2048?s[r++]=n>>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function OF(e,t){let i=yF(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,s=t.limit;e<s;e++)n[e+i]=r[e];}function NF(e){return e.bytes[AF(e,1)];}function DF(e,t){let i=yF(e,1);e.bytes[i]=t;}function PF(e){let t=AF(e,8),i=e.bytes;return gF[0]=i[t++],gF[1]=i[t++],gF[2]=i[t++],gF[3]=i[t++],gF[4]=i[t++],gF[5]=i[t++],gF[6]=i[t++],gF[7]=i[t++],fF[0];}function LF(e,t){let i=yF(e,8),n=e.bytes;fF[0]=t,n[i++]=gF[0],n[i++]=gF[1],n[i++]=gF[2],n[i++]=gF[3],n[i++]=gF[4],n[i++]=gF[5],n[i++]=gF[6],n[i++]=gF[7];}function kF(e){let t,i=0,n=0;do{t=NF(e),i<32&&(n|=(127&t)<<i),i+=7;}while(128&t);return n;}function MF(e,t){for(t>>>=0;t>=128;)DF(e,127&t|128),t>>>=7;DF(e,t);}function UF(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=yF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}function xF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const VF=new Map([["moderation",1],["supervise",2]]);class FF extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mv.CONNECTION_STATE_CHANGE,t,e);}get inspectType(){return this._inspectType;}set inspectType(e){var t;this._inspectMode=BT(t=e.map(e=>VF.get(e)||0)).call(t,(e,t)=>e+t),this._inspectType=e;}get quality(){return this._quality;}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this.qualityRatio;},6e4));}constructor(e){super(),sh(this,"name","AgoraRTCVideoContentInspect"),sh(this,"_connectionState",_v.CONNECTING),sh(this,"_innerConnectionState",void 0),sh(this,"sequence",0),sh(this,"inspectStartTime",void 0),sh(this,"workerManagerConnection",void 0),sh(this,"workerConnection",void 0),sh(this,"workerMessageLengthLimit",void 0),sh(this,"inspectIntervalMinimum",void 0),sh(this,"qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"wmSequence",0),sh(this,"inspectInterval",void 0),sh(this,"inspectTimer",null),sh(this,"ossFilePrefix",void 0),sh(this,"extraInfo",void 0),sh(this,"_inspectType",void 0),sh(this,"_inspectMode",void 0),sh(this,"_quality",1),sh(this,"qualityTimer",null),sh(this,"_inspectId",void 0),sh(this,"_needWorkUrlOnly",!1),sh(this,"inspectImage",()=>{if(this.connectionState!==_v.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval(()=>{this.connectionState===_v.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState);},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage();}),this._inspectId=nS(5,"inspect-"),this.workerMessageLengthLimit=RC("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=RC("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=RC("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new zv("worker-manager-"+this._inspectId,ES),this.on(mv.STATE_CHANGE,(e,t)=>{this._innerConnectionState=e,jC.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Ev[e]," ").concat(t||""));}),this.handleWorkerManagerEvents(),this.workerConnection=new zv("worker-"+this._inspectId,ES),this.handleWorkerEvents();}async init(e,t){this.emit(mv.STATE_CHANGE,Ev.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(mv.CONNECTION_STATE_CHANGE,(e,t)=>{t===_v.CONNECTED&&n();}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e);}).catch(e=>{r(e);});});}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=RC("VIDEO_INSPECT_WORKER_MANAGER_PORT");return {addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return "wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i);}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,responseTime:p};},(t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(mv.STATE_CHANGE,Ev.AP_CONNECTED);const{addressList:s}=r;return this.wmSequence++,s;}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4);}async connectWorker(e){await this.workerConnection.init([e]);}handleWorkerManagerEvents(){this.workerManagerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.20.2",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0);}),this.workerManagerConnection.on(SI.CLOSED,()=>{this._innerConnectionState<Ev.GET_WORKER_MANAGER_RESPONSE&&jC.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"));}),this.workerManagerConnection.on(SI.FAILED,()=>{this._innerConnectionState<Ev.GET_WORKER_MANAGER_RESPONSE&&jC.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"));}),this.workerManagerConnection.on(SI.RECONNECTING,()=>{this._innerConnectionState<Ev.GET_WORKER_MANAGER_RESPONSE&&jC.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"));}),this.workerManagerConnection.on(SI.ON_MESSAGE,async e=>{this.emit(mv.STATE_CHANGE,Ev.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw jC.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new LI(Hg.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw jC.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new LI(Hg.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=RC("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(mv.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n);}}),this.workerManagerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{i(e);}),this.workerManagerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t);});}handleWorkerEvents(){this.workerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=_v.CONNECTED;}),this.workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const i=uF(new Uint8Array(e.data));if(RC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&jC.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(mv.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=BT(t=Object.keys(e)).call(t,(t,i)=>e[t]>e[i]?t:i,"porn"),r=Object.keys(e).find(e=>e===n);this.emit(mv.INSPECT_RESULT,r);}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"));}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"",i.msg));}else jC.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,"invalid worker message type"));}),this.workerConnection.on(SI.CLOSED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.FAILED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===_v.CONNECTED?_v.RECONNECTING:_v.CONNECTING;}),this.workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this.workerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(mv.REQUEST_NEW_WORKER_URL,t=>{e([t]);}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e=>{this.connectWorkerManager(e,!0);}).catch(e=>{t(e);});});}static intToLong(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}async requestToInspectImage(){this.sequence++;const e=AT(this,mv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0);}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,"Only the track being published can be inspected"));}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:FF.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this.sequence,sid:o,timestamp:FF.intToLong(c),uid:a,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=lF(h);if(p.byteLength<this.workerMessageLengthLimit){if(RC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xF(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xF(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({},h);delete e.jpg,jC.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e));}return p;}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a});}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=sC.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=_v.CLOSED,this.emit(mv.STATE_CHANGE,Ev.CLOSED);}}function BF(e){let t=function(){const e=HF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0};}();return function(e,t){let i=e.appId;void 0!==i&&(tB(t,10),QF(t,i));let n=e.cid;void 0!==n&&(tB(t,16),tB(t,n));let r=e.cname;void 0!==r&&(tB(t,26),QF(t,r));let s=e.deviceId;void 0!==s&&(tB(t,34),QF(t,s));let o=e.elapse;void 0!==o&&(tB(t,40),nB(t,o));let a=e.fileSize;void 0!==a&&(tB(t,48),nB(t,WF(a)));let c=e.height;void 0!==c&&(tB(t,56),nB(t,WF(c)));let d=e.jpg;void 0!==d&&(tB(t,66),tB(t,d.length),JF(t,d));let l=e.networkType;void 0!==l&&(tB(t,72),nB(t,WF(l)));let u=e.osType;void 0!==u&&(tB(t,80),nB(t,WF(u)));let h=e.requestId;void 0!==h&&(tB(t,90),QF(t,h));let p=e.sdkVersion;void 0!==p&&(tB(t,98),QF(t,p));let _=e.sequence;void 0!==_&&(tB(t,104),nB(t,WF(_)));let E=e.sid;void 0!==E&&(tB(t,114),QF(t,E));let m=e.timestamp;void 0!==m&&(tB(t,120),nB(t,m));let f=e.uid;void 0!==f&&(tB(t,128),tB(t,f));let g=e.vid;void 0!==g&&(tB(t,136),tB(t,g));let T=e.width;void 0!==T&&(tB(t,144),nB(t,WF(T)));let S=e.service;void 0!==S&&(tB(t,152),tB(t,S));let R=e.callbackData;void 0!==R&&(tB(t,162),tB(t,R.length),JF(t,R));let C=e.ticket;void 0!==C&&(tB(t,170),QF(t,C));let I=e.vendorConfigs;void 0!==I&&(tB(t,178),QF(t,I));}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i);}(t);}function jF(e){return function(e){let t={};e:for(;!YF(e);){let i=eB(e);switch(i>>>3){case 0:break e;case 1:t.code=eB(e);break;case 2:t.msg=XF(e,eB(e));break;case 3:t.requestId=XF(e,eB(e));break;case 4:t.timestamp=iB(e,!1);break;default:GF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function GF(e,t){switch(t){case 0:for(;128&ZF(e););break;case 2:KF(e,eB(e));break;case 5:KF(e,4);break;case 1:KF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}function WF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let HF=[];function KF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function YF(e){return e.offset>=e.limit;}function qF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function zF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function JF(e,t){let i=qF(e,t.length);e.bytes.set(t,i);}function XF(e,t){let i=zF(e,t),n=String.fromCharCode,r=e.bytes,s="<22>",o="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+i];0==(128&u)?o+=n(u):192==(224&u)?e+1>=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function QF(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4;}tB(e,n);let r=qF(e,n),s=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?s[r++]=n:(n<2048?s[r++]=n>>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function ZF(e){return e.bytes[zF(e,1)];}function $F(e,t){let i=qF(e,1);e.bytes[i]=t;}function eB(e){let t,i=0,n=0;do{t=ZF(e),i<32&&(n|=(127&t)<<i),i+=7;}while(128&t);return n;}function tB(e,t){for(t>>>=0;t>=128;)$F(e,127&t|128),t>>>=7;$F(e,t);}function iB(e,t){let i,n=0,r=0,s=0;return i=ZF(e),n=127&i,128&i&&(i=ZF(e),n|=(127&i)<<7,128&i&&(i=ZF(e),n|=(127&i)<<14,128&i&&(i=ZF(e),n|=(127&i)<<21,128&i&&(i=ZF(e),r=127&i,128&i&&(i=ZF(e),r|=(127&i)<<7,128&i&&(i=ZF(e),r|=(127&i)<<14,128&i&&(i=ZF(e),r|=(127&i)<<21,128&i&&(i=ZF(e),s=127&i,128&i&&(i=ZF(e),s|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|s<<24,unsigned:t};}function nB(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=qF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}const rB={},sB={},oB=4294967296,aB=oB*oB,cB=aB/2,dB=_B(0,!0),lB=_B(0),uB=EB(0,-2147483648,!1),hB=EB(-1,2147483647,!1),pB=EB(-1,-1,!0);function _B(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=sB[e],n)?n:(i=EB(e,0,!0),r&&(sB[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=rB[e],n)?n:(i=EB(e,e<0?-1:0,!1),r&&(rB[e]=i),i);}function EB(e,t,i){return {low:0|e,high:0|t,unsigned:!!i};}function mB(e,t){if(isNaN(e))return t?dB:lB;if(t){if(e<0)return dB;if(e>=aB)return pB;}else {if(e<=-cB)return uB;if(e+1>=cB)return hB;}return e<0?t?dB:lB:EB(e%oB|0,e/oB|0,t);}function fB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}class gB extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Cv.CONNECTION_STATE_CHANGE,e,t);}get quality(){return this._quality;}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this._qualityRatio;},6e4));}constructor(e){var t;super(),sh(this,"name","AgoraRTCImageModeration"),sh(this,"_connectionState",Rv.CONNECTING),sh(this,"_sequence",0),sh(this,"_moderationStartTime",void 0),sh(this,"_workerConnection",void 0),sh(this,"_workerMessageLengthLimit",void 0),sh(this,"_qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"_moderationInterval",void 0),sh(this,"_moderationTimer",null),sh(this,"_moderationMode",1),sh(this,"_quality",1),sh(this,"_qualityTimer",null),sh(this,"_ticket",void 0),sh(this,"_moderationIntervalMinimum",void 0),sh(this,"_uploadFailedNum",0),sh(this,"_uploadNum",0),sh(this,"_uploadTimer",null),sh(this,"_extraInfo",void 0),sh(this,"_vendor",""),sh(this,"_encoder",new TextEncoder()),sh(this,"_moderationId",void 0),sh(this,"inspectImage",()=>{if(this.connectionState!==Rv.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval(()=>{this.connectionState===Rv.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState);},this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage();}),this._moderationId=nS(5,"image-moderation-"),this._workerMessageLengthLimit=RC("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=RC("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=RC("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new zv("worker-"+this._moderationId,ES),this.on(Cv.STATE_CHANGE,(e,t)=>{jC.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Iv[e]," ").concat(t||""));}),this.handleWorkerEvents();}async init(e,t){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(Cv.CONNECTION_STATE_CHANGE,(e,t)=>{e===Rv.CONNECTED&&n();}),this.requestAP(e,i,t).then(e=>{this.connectWorker(e);}).catch(e=>{r(e);});});}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),jC.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===Rv.CONNECTED&&this.inspectImage();}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers.some(e=>!!e.wss)){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("IMAGE_MODERATION_WORKER_HOST");return {addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return "wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation");}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p};},(t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(Cv.STATE_CHANGE,Iv.AP_CONNECTED);const{addressList:s,ticket:o}=r;return this._ticket=o,s;}async connectWorker(e){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_WORKER),await this._workerConnection.init(e,1e4);}handleWorkerEvents(){this._workerConnection.on(SI.CONNECTED,async()=>{this.emit(Cv.STATE_CHANGE,Iv.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Rv.CONNECTED;}),this._workerConnection.on(SI.CLOSED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.FAILED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===Rv.CONNECTED?Rv.RECONNECTING:Rv.CONNECTING;}),this._workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const t=jF(new Uint8Array(e.data));RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,jC.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{eI.reportApiInvoke(this._connectInfo.sid||null,{name:hT.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:pT.TRACER}).onError(new LI(Hg.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null;},RC("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))));}else jC.error("[".concat(this._moderationId,"] Unexpected message type from worker"));}),this._workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this._workerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t);});}static intToLong(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}async requestToInspectImage(){const e=AT(this,Cv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0);}else RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("Only the track being published can be inspected");}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:gB.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this._sequence,sid:o,timestamp:mB(c),uid:a,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=BF(h);if(p.byteLength<this._workerMessageLengthLimit){if(RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fB(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fB(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}({},h);delete e.jpg,jC.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e));}return p;}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a});}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=sC.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=Rv.CLOSED,this.emit(Cv.STATE_CHANGE,Iv.CLOSED);}}function TB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function SB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?TB(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):TB(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}const RB=Date.now(),CB=20,IB=new Map(),vB=new Map();async function yB(e){const t=IB.get(e),i=Array.isArray(t)&&t[t.length-1],n=vB.get(e);if(!i)return void(n.isSyncing=!1);const r={uid:i.uid,payload:i.payload};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const s=i.sendTs-n.firstSendTs,o=s-(Date.now()-n.firstRecvTs);o>0&&(n.firstRecvTs=Date.now()-s);let a=i.mediaDelay+o;a<=0?(t.pop(),AB(i.context,r),a=0):a=Math.min(a,CB),setTimeout(()=>t.length&&yB(e),a);}function AB(e,t){e.safeEmit(mT.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t);}function bB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return AB(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=IB.get(n)||[],s=r.findIndex(t=>e.sendTs>=t.sendTs),o=SB(SB({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?r.push(o):r.splice(s,0,o),IB.set(n,r);let a=!1;var c;vB.has(n)?a=!(null===(c=vB.get(n))||void 0===c||!c.isSyncing):vB.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||yB(n);}const wB=Sg().name;function OB(){return !function(e,t,i){const n=Sg();if(n.os!==_g.IOS||!n.osVersion)return !1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e;}(16,0,!0)&&!function(e,t,i){const n=Sg();if(n.name!==Eg.SAFARI||!n.osVersion)return !1;const r=n.version.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e;}(16,0,!0);}function NB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function DB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NB(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NB(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}pS.setLogger(jC);class PB extends dT{get connectionState(){return this._gateway.state;}get remoteUsers(){return this._users;}get localTracks(){return this._p2pChannel.getAllTracks(!0);}get uid(){return this._uid;}get channelName(){return this._channelName;}get localDataChannels(){return this._p2pChannel.getAllDataChannels();}get mode(){return this._config.mode;}get role(){var e;return (null===(e=this._config)||void 0===e?void 0:e.role)||"audience";}get codec(){return this._config.codec;}get audioCodec(){return this._config.audioCodec||"opus";}get isStringUID(){return !!this._joinInfo&&!!this._joinInfo.stringUid;}get __className__(){return "Client";}constructor(e){let t;if(super(),sh(this,"store",void 0),sh(this,"_uid",void 0),sh(this,"_channelName",void 0),sh(this,"_uintUid",void 0),sh(this,"_users",[]),sh(this,"_config",void 0),sh(this,"_clientId",void 0),sh(this,"_appId",void 0),sh(this,"_sessionId",null),sh(this,"_key",void 0),sh(this,"_rtmConfig",{}),sh(this,"_joinInfo",void 0),sh(this,"_gateway",void 0),sh(this,"_statsCollector",void 0),sh(this,"_configDistribute",void 0),sh(this,"_leaveMutex",new pS("client-leave")),sh(this,"_publishMutex",new pS("client-publish")),sh(this,"_renewTokenMutex",new pS("client-renewtoken")),sh(this,"_subscribeMutex",new pS("client-subscribe")),sh(this,"_encryptionMode","none"),sh(this,"_encryptionSecret",null),sh(this,"_encryptionSalt",null),sh(this,"_encryptDataStream",!1),sh(this,"_encryptDataStreamKey",null),sh(this,"_encryptDataStreamIv",null),sh(this,"_proxyServer",void 0),sh(this,"_turnServer",{servers:[],mode:"auto"}),sh(this,"_cloudProxyServerMode","disabled"),sh(this,"_isDualStreamEnabled",!1),sh(this,"_defaultStreamFallbackType",void 0),sh(this,"_lowStreamParameter",void 0),sh(this,"_streamFallbackTypeCacheMap",new Map()),sh(this,"_remoteStreamTypeCacheMap",new Map()),sh(this,"_axiosCancelSource",sC.CancelToken.source()),sh(this,"_audioVolumeIndicationInterval",void 0),sh(this,"_networkQualityInterval",void 0),sh(this,"_userOfflineTimeout",void 0),sh(this,"_streamRemovedTimeout",void 0),sh(this,"_injectStreamingClient",void 0),sh(this,"_liveTranscodeStreamingClient",void 0),sh(this,"_liveRawStreamingClient",void 0),sh(this,"_channelMediaRelayClient",void 0),sh(this,"_networkQualitySensitivity","normal"),sh(this,"_p2pChannel",void 0),sh(this,"_useLocalAccessPoint",!1),sh(this,"_setLocalAPVersion",void 0),sh(this,"_joinAndNotLeaveYet",!1),sh(this,"_numberOfJoinCount",0),sh(this,"_remoteDefaultVideoStreamType",void 0),sh(this,"_inspect",void 0),sh(this,"_moderation",void 0),sh(this,"_license",void 0),sh(this,"_pendingPublishedUsers",[]),sh(this,"ntpAlignErrorCount",0),sh(this,"remoteInboundOffset",0),sh(this,"_handleLocalTrackEnable",(e,t,i)=>{this.publish(e,!1).then(t).catch(i);}),sh(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i);}),sh(this,"_handleUserOnline",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return void jC.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&jC.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find(t=>t.uid===e.uid);if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(mT.USER_JOINED,t));else {const t=new sV(e.uid,e.uint_id||e.uid);this._users.push(t),jC.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(mT.USER_JOINED,t);}}),sh(this,"_handleUserOffline",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:WT(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),jC.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(mT.USER_LEAVED,t,e.reason));}),sh(this,"_handleAddAudioOrVideoStream",(e,t,i,n,r,s,o)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(t,this.channelName))return;const a=this._users.find(e=>e.uid===t);if(!a)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));jC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),s&&(a._audioOrtc=s)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==o&&(a._rtxSsrcId=o),s&&(a._videoOrtc=s)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(jC.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.safeEmit(mT.USER_PUBLISHED,a,e)),"video"===e?eI.onGatewayStream(this._sessionId,YC.ON_ADD_VIDEO_STREAM,qC.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):eI.onGatewayStream(this._sessionId,YC.ON_ADD_AUDIO_STREAM,qC.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then(t=>{if(t&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof cF))return this._p2pChannel.unsubscribe(a,e,!0).then(()=>this._subscribe(a,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),sh(this,"_handleRemoveStream",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);if(!t)return void jC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));jC.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"audio"),jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"video");}:t.hasVideo?i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"video");}:t.hasAudio&&(i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"audio");}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof cF&&this._p2pChannel.unsubscribe(t).then(e=>{if(e)return this._gateway.unsubscribe(e,t.uid);}),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),eI.onGatewayStream(this._sessionId,YC.ON_REMOVE_STREAM,qC.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i();}),sh(this,"_handleSetStreamLocalEnable",(e,t,i)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(t,this.channelName))return;const n=this._users.find(e=>e.uid===t);if(!n)return void jC.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));jC.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";jC.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e);}}else {n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e);}}const s="audio"===e?n.hasAudio:n.hasVideo;return r!==s?!r&&s?(jC.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(mT.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),jC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(mT.USER_UNPUBLISHED,n,e)):void 0;}),sh(this,"_handleMuteStream",(e,t,i)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e,this.channelName))return;jC.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find(t=>t.uid===e);if(!n)return void jC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t);}}else {n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t);}}const s="audio"===t?n.hasAudio:n.hasVideo;if(r!==s){if(!r&&s){return ("audio"===t?n._audioSSRC:n._videoSSRC)?(jC.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(mT.USER_PUBLISHED,n,t)):void jC.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."));}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),jC.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(mT.USER_UNPUBLISHED,n,t);}}),sh(this,"_handleP2PLost",async e=>{jC.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():jC.warning("[".concat(this._clientId,"] P2PLost stream not found"),e);}),sh(this,"_handleTokenWillExpire",()=>{jC.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_WILL_EXPIRE);}),sh(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),jC.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")));}),sh(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(mT.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(mT.NETWORK_QUALITY,e);}),sh(this,"_handleP2PAddAudioOrVideoStream",(e,t,i,n)=>{const r=this._users.find(e=>e.uid===t);if(!r)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));jC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const s="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._audioMid=n)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._videoMid=n)),("audio"===e?r.hasAudio:r.hasVideo)&&!s&&(jC.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(mT.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),this._config=e,this._clientId=nS(5,"client-"),this.store=new AC(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),jC.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(EC," build: ").concat(gC,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{IT(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions);}catch(e){jC.warning("[".concat(this._clientId,"] ").concat(e.toString()));}this._statsCollector=new mV(this.store),this._statsCollector.onStatsException=(e,t,i)=>{jC.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(mT.EXCEPTION,{code:e,msg:t,uid:i});},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find(t=>t.uid===e);r&&eI.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid});},this.store.useDataChannel=IA().supportDataChannel&&RC("SIGNAL_CHANNEL"),this.store.useP2P="p2p"===e.mode,this._gateway=new xy(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||ES,httpRetryConfig:e.httpRetryConfig||ES,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._configDistribute=new RA(),this.store.useP2P?(this._p2pChannel=new hV(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new cF(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents();}async joinMeta(e,t,i,n,r){let s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=arguments.length>6&&void 0!==arguments[6]&&arguments[6];SC("JOIN_GATEWAY_USE_443PORT_ONLY",s),SC("JOIN_GATEWAY_USE_DUAL_DOMAIN",o);const a=this._gateway.signal.websocket;return a instanceof qv&&(a.use443PortOnly=s,a.tryDoubleDomain=o),async function(e,t,i){ug.get(e)||ug.set(e,[]),hg.get(e)||hg.set(e,t),pg.get(e)||pg.set(e,0);const n=ug.get(e),r=hg.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(pg.get(e)===r){const e=lg();n.push(e),await e.promise;}pg.set(e,pg.get(e)+1);for(var s=arguments.length,o=new Array(s>3?s-3:0),a=3;a<s;a++)o[a-3]=arguments[a];const c=await i(...o);return pg.set(e,pg.get(e)-1),pg.get(e)===r-1&&n.length>0&&(n[0].resolve(),n.shift()),0===pg.get(e)&&(ug.set(e,[]),hg.set(e,0),pg.set(e,0)),c;}("client.join",RC("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r);}async join(e,t,i,n,r){const s=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const o=pC(),a=_C()?window.isSecureContext:"Browser Not Support";if(!_C()&&!o||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";jC.warning(e);}const c=rS();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),jC.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const d=eI.reportApiInvoke(c,{name:hT.JOIN,options:[e,t,i,n],states:{isHttps:o,isSecureContext:a},tag:pT.TRACER});eI.setAppId(e);try{if(!i&&null!==i)throw new LI(Hg.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Xg(i,"token",1,2047),Xg(e,"appid",1,2047),kI(t),n&&MI(n),r&&Xg(r,"optionalInfo",1,2047);}catch(e){throw d.onError(e),e;}if(jC.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._leaveMutex.isLocked){jC.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),jC.debug("[".concat(this._clientId,"] join: continue"));}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const e=new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw d.onError(e),e;}this._sessionId||(this._sessionId=c,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";const l=DB(DB({},this._rtmConfig),{},{clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(l.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(l.stringUid=n,this._uintUid?(l.uid=this._uintUid,this._uintUid=void 0):l.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(l.aesmode=this._encryptionMode,l.aespassword=await aT(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(l.aessalt=this._encryptionSalt);}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret){if(window.crypto.subtle){const e=new TextEncoder(),t=RC("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(l.appId+this._encryptionSecret+this._encryptionSecret):e.encode(l.appId+l.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,s=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:DC,hash:"SHA-256",salt:i},n,r+NC);return new Uint8Array(s).subarray(r/8);}(this._encryptionMode,t,XT(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:DC,hash:"SHA-256",salt:i},n,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"]);}(this._encryptionMode,t,XT(this._encryptionSalt));}else a?jC.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):jC.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;}else this._encryptDataStream=!1,jC.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:l.stringUid});const u=this._sessionId;setTimeout(()=>{"CONNECTING"===this.connectionState&&u===this._sessionId&&eI.joinChannelTimeout(this._sessionId,5);},5e3);try{var h;let n;const r=l.cloudProxyServer;if(bn(h=["proxy3","proxy4","proxy5"]).call(h,r)){const e=RC("PROXY_SERVER_TYPE3");Array.isArray(e)?l.proxyServer=e[0]:l.proxyServer=e;}if(eI.setProxyServer(l.proxyServer),jC.setProxyServer(l.proxyServer),this.store.requestAPStart(),l.stringUid&&!l.uid){let e;[e,n]=await cg.all([pA(l.stringUid,l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store),hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store)]),jC.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(l.stringUid," => ").concat(e)),l.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e;}else n=await hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store);if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(l,this._axiosCancelSource.token),this._configDistribute.on(sv.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e);});},0),this._key=i||e;const s=n.gatewayInfo,o=l.uid?l.uid:s.uid;this._joinInfo=DB(DB({},l),{},{cid:s.cid,uid:o,vid:s.vid,apResponse:s.res,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs}),this.store.intUid=o;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));d.onSuccess(a),this._appId=e,this._channelName=l.cname,this._uid=a,this.store.uid=a,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(bg()?"beforeunload":"pagehide",this._handleBeforeUnload);},0);const c=l.stringUid?"string uid: ".concat(l.stringUid,",uid: ").concat(l.uid):"uid: ".concat(this._uid);return jC.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout(()=>{jC.startUpload();},5e3),this.store.joinEnd(),p=this,bn(rI).call(rI,p)||rI.push(p),a;}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Hg.OPERATION_ABORTED?jC.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t):jC.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t),t.code!==Hg.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),d.onError(t),t;}var p;}_joinGateway(){if(!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!RC("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then(e=>e).catch(e=>{if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;if(e.code===Hg.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;throw e;}).then(e=>{if(e instanceof LI){if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT){if(jC.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const e=RC("PROXY_SERVER_TYPE3");if(Array.isArray(e)){if(this._joinInfo.apUrl){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(this._joinInfo.apUrl)[1].split("."),i=t.slice(t.length-2).join(".");e.forEach(e=>{this._joinInfo&&bn(e).call(e,i)&&(this._joinInfo.proxyServer=e);}),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=e[0]);}else this._joinInfo.proxyServer=e[0];}else this._joinInfo.proxyServer=e;const t=RC("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);t&&t[1]&&"443"!==t[1]&&jC.setProxyServer(this._joinInfo.proxyServer),"443"!==RC("STATS_COLLECTOR_PORT").toString()&&eI.setProxyServer(this._joinInfo.proxyServer);return eI.reportApiInvoke(this._sessionId,{name:hT.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),RC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&this._joinInfo.turnServer.servers.forEach(e=>{"forceturn"in e&&(e.forceturn=!0);}),this._gateway.join(this._joinInfo,this._key);}if(jC.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return eI.reportApiInvoke(this._sessionId,{name:hT.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:pT.TRACER}).onSuccess(),this._joinGateway();}return e;}).then(e=>e);}async leave(){jC.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(bg()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=rI.indexOf(e);-1!==t&&rI.splice(t,1);}(this);const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return jC.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),jC.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e();}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof lb))return this._publishDataChannel(e);e=[e];}if(0===e.length)throw new LI(Hg.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new LI(Hg.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof lb))throw new LI(Hg.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new LI(Hg.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()));}jC.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach(e=>{const t=this._configDistribute.getBitrateLimit();e instanceof Rw&&t&&e.setBitrateLimit(t.uplink);});try{await this._publishHighStream(i),jC.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))));}catch(e){throw jC.error("[".concat(this._clientId,"] publish error"),e.toString()),e;}finally{n();}}async _publishDataChannel(e){zg(e.id,"id",0,65535,!0),Yg(e.ordered,"ordered"),Xg(e.metadata,"metadata",0,512),jC.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex(t=>t.id===e.id))throw new LI(Hg.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&RC("FORCE_TURN")&&!RC("TURN_ENABLE_TCP")&&!RC("TURN_ENABLE_UDP"))throw new LI(Hg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=new aP(e);if(await this._p2pChannel.publishDataChannel([i]),!this._p2pChannel.isP2PDisconnected()){if("number"!=typeof i._originDataChannelId)throw jC.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new LI(Hg.CREATE_DATACHANNEL_ERROR);try{const t={streamId:e.id,ordered:e.ordered,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS"),metadata:e.metadata,channelId:i._originDataChannelId};await this._gateway.publishDataChannel(this._uid,t,!0),await i._waitTillOpen();}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e;}}return jC.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i;}catch(e){throw jC.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e;}finally{t();}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e){if(Array.isArray(e))t=e;else {if(!(e instanceof lb))return this._unpublishDataChannel([e]);t=[e];}}else this.store.useP2P||(await this._unpublishDataChannel()),t=this._p2pChannel.getAllTracks(!0);jC.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map(e=>"".concat(e.getTrackId()," "))," "));const i=await this._publishMutex.lock();try{if(this._p2pChannel instanceof hV){const e=await this._p2pChannel.unpublish(t);e&&(await this._gateway.sendExtensionMessage(vv.UNPUBLISH,{unpubMsg:e},!0));}else {const e=await this._p2pChannel.unpublish(t);e&&(await this._gateway.unpublish(e,this._uid)),jC.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map(e=>"".concat(e.getTrackId()))));}}catch(e){throw jC.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e;}finally{i&&i();}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),jC.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map(e=>"".concat(e.id," "))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&(await this._gateway.unpublishDataChannel(i)),jC.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map(e=>"".concat(e.id))));}catch(e){throw jC.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e;}finally{t&&t();}}async subscribe(e,t,i){return "datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t);}async presubscribe(e,t){if(qg(t,"mediaType",["audio","video"]),this._p2pChannel instanceof hV)throw new LI(Hg.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===av.AUDIO,n=t===av.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:s,ortc:o,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==s)throw new LI(Hg.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find(t=>t.uid===e);l||(l=new sV(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=s,l._audio_pre_subscribed=!0,o&&(l._audioOrtc=o)),n&&(l._videoSSRC=s,l._video_pre_subscribed=!0,o&&(l._videoOrtc=o),null!=a&&(l._rtxSsrcId=a)),jC.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(s)),await this._p2pChannel.subscribe(l,t,s,a,o);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u;}catch(t){throw jC.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t;}finally{r();}}async _subscribeDataChannel(e,t){var i;if(zg(t,"channelId",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e))throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new LI(Hg.INVALID_REMOTE_USER,"user is not published");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find(e=>e.id===t);if(!n)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);const r=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&bn(t).call(t,n.id))try{var s;if("number"!=typeof n._originDataChannelId)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new LI(Hg.CREATE_DATACHANNEL_ERROR);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(s=n.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen();}catch(t){if((null==t?void 0:t.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id);}return jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n;}finally{r();}}async _p2pSubscribe(e,t,i){if(qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t;}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not published");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t;}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i;}const n=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this._p2pChannel instanceof hV&&(await this._p2pChannel.subscribe(e,t,i,n));}catch(e){throw e;}jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set fallback failed"),e);});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user object");return i;}catch(t){throw jC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t;}finally{n();}}async _subscribe(e,t,i){if(this._p2pChannel instanceof hV)return this._p2pSubscribe(e,t);if(qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t;}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not published");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t;}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i;}let n="audio"===t?e._audioSSRC:e._videoSSRC,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?av.AUDIO:av.VIDEO,ssrcId:n};const a=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==n&&(n=i,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?av.AUDIO:av.VIDEO,ssrcId:n}),RU.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,s,r);try{await this._gateway.subscribe(e.uid,o,!0);}catch(i){if((null==i?void 0:i.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t);}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t);}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i;}jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set fallback failed"),e);});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user object");return i;}catch(t){throw jC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t;}finally{a();}}async massSubscribe(e){if(Qg(e,"subscribeList"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map(),n=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i);}).join("; ")));const r=(e=[...e]).map(e=>{let{user:t,mediaType:i}=e;return {user:t,mediaType:i};}),s=await this._p2pChannel.globalLock();try{var o;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:s,mediaType:o}=n;if(qg(o,"mediaType",["audio","video"]),!s){const e=new LI(Hg.INVALID_PARAMS,"user property does not exist in subscribeList item");throw jC.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e;}if(!this._users.find(e=>e===s)){const i=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");jC.error("[".concat(this._clientId,"] can not massSubscribe ").concat(s.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue;}if("audio"===o&&(!s.hasAudio||void 0===s._audioSSRC)||"video"===o&&(!s.hasVideo||void 0===s._videoSSRC)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);jC.error("[".concat(this._clientId,"] can not subscribe ").concat(s.uid," with mediaType ").concat(o,", remote user is not published")),r[t].error=i,e.splice(t,1);continue;}const a=ZI.Video|ZI.LwoVideo,c=i.get(s);if(c){if("video"===o?c&a:c&ZI.Audio){e.splice(t,1),jC.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(s.uid,", mediaType:").concat(o," twice"));continue;}i.set(s,c|("video"===o?a:ZI.Audio));}else i.set(s,"video"===o?a:ZI.Audio);}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:s}=n,o=ZI.Video|ZI.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,s)){await this._p2pChannel.unmuteRemoteNoLock(r,s);const n=i.get(r);i.set(r,"video"===s?n^o:n^ZI.Audio),e.splice(t,1);}}this.store.massSubscribe(e.map(e=>({userId:e.user.uid,type:e.mediaType})),t);const a=BT(o=Array.from(i.entries())).call(o,(e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&ZI.Audio&&(r.audio_ssrc=i._audioSSRC),n&ZI.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e;},[]);try{e.length>0&&(await this._p2pChannel.massSubscribeNoLock(e.map(e=>{let{user:t,mediaType:i}=e;return {user:t,mediaType:i,ssrcId:i===av.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===av.VIDEO?t._rtxSsrcId:void 0};})));const i=new Map();if(a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach(e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:s}=e;(n||r||s)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:s});});}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach(t=>{let[i,n]=t;const r=this.remoteUsers.find(e=>e.uid===i);if(r){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=av.VIDEO:n.audio_error_code&&(t=av.AUDIO),e.push({user:r,mediaType:t});}}),e.length>0&&(await this._p2pChannel.massUnsubscribeNoLock(e));}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=kv(i);jC.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new LI(Hg.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc));}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack);}return this.store.massSubscribe(r.filter(e=>!e.error).map(e=>({userId:e.user.uid,type:e.mediaType})),void 0,Date.now()),r.forEach(e=>{var i;eI.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===av.VIDEO,audio:e.mediaType===av.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===av.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0);}),jC.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i);}).join("; "))),r;}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t;}}finally{s(),n();}}async unsubscribe(e,t,i){if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i);}else await this._unsubscribeDataChannel(e,i);if(t&&qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t;}jC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const n=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof hV)await this._p2pChannel.unsubscribe(e,t);else {const i=await this._p2pChannel.unsubscribe(e,t);i&&(await this._gateway.unsubscribe(i,e.uid)),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&WT(this._users,e),jC.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t));}}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning("disconnecting p2p, abort unsubscribe request.");throw jC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t;}finally{n();}}async _unsubscribeDataChannel(e,t){if(t&&zg(t,"id",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t;}let i;if("number"==typeof t){const n=e._dataChannels.find(e=>e.id===t);n&&(i=[n]);}else i=e._dataChannels;if(void 0===i){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i;}jC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map(e=>e.id)));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&(await this._gateway.unsubscribeDataChannel(t,e.uid)),jC.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t));}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning("disconnecting p2p, abort unsubscribe request.");throw jC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t;}}async massUnsubscribe(e){if(Qg(e,"unsubscribeList"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");jC.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";");}).join())),e=[...e];const t=new Map();for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new LI(Hg.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw jC.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e;}qg(r,"mediaType",["video","audio",void 0]);if(!this._users.find(e=>e===n)){jC.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue;}const s=ZI.Video|ZI.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&ZI.Audio;break;default:a=o&(ZI.Audio|s);}if(a){jC.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue;}r?"audio"===r?t.set(n,o|ZI.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|ZI.Audio|s);}else r?"audio"===r?t.set(n,ZI.Audio):"video"===r&&t.set(n,s):t.set(n,ZI.Audio|s);}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&(await this._gateway.massUnsubscribe(t)),jC.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";");}).join()));}catch(e){if(e.code===Hg.DISCONNECT_P2P)return void jC.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw jC.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e;}}async setLowStreamParameter(e){!function(e){if(!e)throw new Kg(Hg.INVALID_PARAMS);Zg(e.width)||Jg(e.width,"streamParameter.width"),Zg(e.height)||Jg(e.height,"streamParameter.height"),Zg(e.framerate)||Jg(e.framerate,"streamParameter.framerate"),Zg(e.bitrate)||zg(e.bitrate,"streamParameter.bitrate");}(e),(!e.width&&e.height||e.width&&!e.height)&&jC.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),jC.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,lv.LocalVideoLowTrack);}async enableDualStream(){if(!IA().supportDualStream)throw eI.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new LI(Hg.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new LI(Hg.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream();}catch(e){throw eI.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e;}this._isDualStreamEnabled=!0,eI.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),jC.info("[".concat(this._clientId,"] enable dual stream"));}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(lv.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&(await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid));}catch(e){throw eI.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e;}this._isDualStreamEnabled=!1,eI.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),jC.info("[".concat(this._clientId,"] disable dual stream"));}}async setClientRole(e,t){if(function(e){qg(e,"role",["audience","host"]);}(e),t&&IT(t),"rtc"===this.mode||"p2p"===this.mode)throw jC.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new LI(Hg.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new LI(Hg.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new LI(Hg.INVALID_OPERATION,"can not set client role to audience when publishing stream");await this._gateway.setClientRole(e,t),this._config.role=e,jC.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level));}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0;}getNtpWallTimeInMs(){return "visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset;}setProxyServer(e,t){if(Xg(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");}this._proxyServer=e,eI.setProxyServer(this._proxyServer),jC.setProxyServer(this._proxyServer),jC.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."));}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");}if(RT(e))return this._turnServer={servers:e,mode:"original-manual"},void jC.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>CT(e)),this._turnServer={servers:e,mode:"manual"},jC.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."));}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new LI(Hg.INVALID_OPERATION,"you should set license before join channel");}if(Xg(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new LI(Hg.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,jC.info("[".concat(this._clientId,"] set license success"),e);}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new LI(Hg.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new LI(Hg.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")));}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,jC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode);}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Stop proxy server after leave channel");eI.setProxyServer(),jC.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",jC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]};}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new LI(Hg.INVALID_PARAMS,"accessPoints is required.");Qg(e.accessPoints.serverList,"accessPoints.serverList"),Xg(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{zg(e,t,0,65535,!0);};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");RC("CLOSE_AFB_FOR_LOCAL_AP")&&(SC("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),SC("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,s=e.accessPoints.serverList.map(e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e),o=s.map(e=>"".concat(e,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,SC("WEBCS_DOMAIN",o),SC("WEBCS_DOMAIN_BACKUP_LIST",o),SC("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Qg(e.report.hostname,"report.hostname"),SC("EVENT_REPORT_DOMAIN",e.report.hostname[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(SC("EVENT_REPORT_DOMAIN",s[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",s[1]||s[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),SC("STATS_COLLECTOR_PORT",a),e.report?SC("ENABLE_EVENT_REPORT",!0):SC("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Qg(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=s[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),SC("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Qg(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=s;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),SC("CDS_AP",l.map(e=>"".concat(e,":").concat(u))),e.cds?SC("ENABLE_CONFIG_DISTRIBUTE",!0):SC("ENABLE_CONFIG_DISTRIBUTE",!1),jC.info("set local access point v2 success");}setLocalAccessPoints(e,t){if(Qg(e,"serverList"),Xg(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map(e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,SC("WEBCS_DOMAIN",e),SC("WEBCS_DOMAIN_BACKUP_LIST",e),SC("GATEWAY_DOMAINS",[t]),SC("EVENT_REPORT_DOMAIN",e[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),SC("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),jC.info("[".concat(this._clientId,"] set local access point success"));}async setRemoteDefaultVideoStreamType(e){if(qg(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType;}catch(e){throw jC.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e;}else jC.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e));}async setRemoteVideoStreamType(e,t){qg(t,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout(()=>{const t=this._users.find(t=>t.uid===e);t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution();},2e3);}catch(e){throw jC.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e;}jC.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t);}async setStreamFallbackOption(e,t){qg(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t);}catch(e){throw jC.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e;}jC.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t);}setEncryptionConfig(e,t,i,n){!function(e){qg(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"]);}(e),Xg(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(bn(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new LI(Hg.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes");}else if(i)throw new LI(Hg.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Yg(n,"encryptDataStream"),!bn(r).call(r,e))throw new LI(Hg.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0;}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||jC.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=QT(i));}async renewToken(e){if(Xg(e,"token",1,2047),!this._key||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(RC("USE_NEW_TOKEN")){jC.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await gA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES);jC.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t});}else jC.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});jC.debug("[".concat(this._clientId,"] renewToken success"));}catch(e){throw this._key=t,this._joinInfo.token=t,jC.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e;}finally{i();}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?jC.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(mT.VOLUME_INDICATOR,e);},RC("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3);}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e;}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming");}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new LI(Hg.LIVE_STREAMING_TASK_CONFLICT);const i=t?RI.TRANSCODE:RI.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i);}setLiveTranscoding(e){return this._createLiveStreamingClient(RI.TRANSCODE).setTranscodingConfig(e);}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new LI(Hg.INVALID_PARAMS,"can not find live streaming url to stop");await cg.all(t.map(t=>t&&t.stopLiveStreamingTask(e)));}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const i=this._createLiveStreamingClient(RI.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,RI.INJECT);}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(RI.INJECT),i=Array.from(NI(e=t.streamingTasks).call(e)).find(e=>e.mode===RI.INJECT);if(!this._joinInfo||!i)throw new LI(Hg.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url);}async startChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e);}async updateChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e);}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0);}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder();e.payload=t.encode(e.payload);}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=BT(n=Array.from(i)).call(n,(e,t)=>e+t,0),s={serverTs:0,seq:LC++,length:i.length,checkSum:r},o=new Uint8Array(lS(r,2)),a=new ArrayBuffer(PC),c=new DataView(a);c.setUint32(0,s.serverTs),c.setUint16(4,s.seq),c.setUint16(6,s.length),c.setUint16(8,s.checkSum);const d=16-i.length%16;i=ZT(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:OC,additionalData:o},t,i);return ZT(new Uint8Array(a),new Uint8Array(l));}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new LI(Hg.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(EI.DATA_STREAM,{payload:QT(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-RB},!i);}sendMetadata(e){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new LI(Hg.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(EI.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:QT(e)});}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(HC),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send custom report, not joined");await eI.sendCustomReportMessage(this._joinInfo.sid,e);}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats();}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats();}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats();}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats();}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats();}async pickSVCLayer(e,t){qg(t.spatialLayer,"spatialLayer",[0,1,2,3]),qg(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t);}catch(e){throw jC.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e;}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(Yg(t,"apRTM"),zg(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,jC.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i);}_reset(){if(jC.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=sC.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map(),this._remoteStreamTypeCacheMap=new Map(),this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach(e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach(e=>e._close()),e._dataChannels.length=0);}),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new pS("client-publish"),this._subscribeMutex=new pS("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0;}catch(e){}if(this._moderation)try{this.setImageModeration(!1);}catch(e){}}_startSession(e,t){var i;const n=e||rS();e?jC.debug("[".concat(this._clientId,"] new Session ").concat(n)):jC.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n;const s={lts:new Date().getTime(),mode:this.mode,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1};t?eI.sessionInit(this._sessionId,DB({cname:t.channel,appid:t.appId},s)):this._joinInfo?eI.sessionInit(this._sessionId,DB({cname:this._joinInfo.cname,appid:this._joinInfo.appId},s)):this._gateway.joinInfo&&eI.sessionInit(this._sessionId,DB({cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId},s)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n);}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&RC("FORCE_TURN")&&!RC("TURN_ENABLE_TCP")&&!RC("TURN_ENABLE_UDP"))throw new LI(Hg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");jC.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this._p2pChannel instanceof hV){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(vv.PUBLISH,e,!0);}catch(e){throw i.throw(e),e;}await i.next();}this._p2pChannel.reportPublishEvent(!0,null);}else {const n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0);}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw i.throw(e),e;}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[]);}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof Rw&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!t.muted&&t.enabled||(await this._p2pChannel.muteLocalTrack(t));}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===Hg.WS_ABORT)return;throw t;}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));jC.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0);}catch(t){if(t.code!==Hg.DISCONNECT_P2P)throw e.throw(t),t;}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0);}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===Hg.WS_ABORT)return;throw e;}}_createLiveStreamingClient(e){if(!this._joinInfo||!this._appId){return new LI(Hg.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();}const t=()=>new CV(this._joinInfo,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES),i=e=>{e.onLiveStreamError=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_ERROR,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_ERROR,e,t);},e.onLiveStreamWarning=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_WARNING,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_WARNING,e,t);},e.on(GI.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,"can not find join info to get worker manager"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i);});};switch(e){case RI.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case RI.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case RI.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(GI.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,"can not find join info to get worker manager"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i);}),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.safeEmit(mT.INJECT_STREAM_STATUS,e,t,i);}),this._injectStreamingClient;}}_createChannelMediaRelayClient(){if(!this._joinInfo){return new LI(Hg.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();}if(!this._channelMediaRelayClient){const{sendResolutionWidth:e,sendResolutionHeight:t}=this.getLocalVideoStats(),i={width:e,height:t};this._channelMediaRelayClient=new AV(this._joinInfo,this._clientId,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES,i),this._channelMediaRelayClient.on("state",e=>{e===qI.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.safeEmit(mT.CHANNEL_MEDIA_RELAY_STATE,e);}),this._channelMediaRelayClient.on("event",e=>{this.safeEmit(mT.CHANNEL_MEDIA_RELAY_EVENT,e);}),this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t));};}return this._channelMediaRelayClient;}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];Array.isArray(i)&&i.length>0&&i.forEach(e=>{const{uid:i,stream_id:n,ordered:s,max_retrans_times:o,metadata:a}=e,c=this._users.find(e=>e._uintid===i);if(!c)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));jC.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),bn(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i);if(!(-1!==c._dataChannels.findIndex(t=>t.id===e.stream_id))){const e={id:n,ordered:!!s,maxRetransmits:o,metadata:a},i=new oP(e);c._dataChannels.push(i),jC.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(mT.USER_PUBLISHED,c,"datachannel",e);}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(jC.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString());}));}),t&&(this.safeEmit(mT.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach(e=>{const{uid:t,stream_id:i}=e,n=this._users.find(e=>e._uintid===t);if(!n)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=n._dataChannels.find(t=>t.id===e.stream_id);r&&(jC.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then(e=>{if(n._dataChannels=n._dataChannels.filter(e=>e!==r),e)return this._gateway.unsubscribeDataChannel(e,n.uid);}),jC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(mT.USER_UNPUBLISHED,n,"datachannel",r._config));});}_handleRemoveDataChannels(e){const t=this._users.find(t=>t.uid===e.uid);if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){jC.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach(e=>{this.safeEmit(mT.USER_UNPUBLISHED,t,"datachannel",e._config);});};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then(e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid);}),i();}}else jC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"));}_handleGatewayEvents(){this._gateway.on(XI.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect();}),this._gateway.on(XI.CONNECTION_STATE_CHANGE,(e,t,i)=>{var n;if(i===ET.FALLBACK)return;const r=()=>{this.safeEmit(mT.CONNECTION_STATE_CHANGE,e,t,i);};if(eI.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:hT.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:pT.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),jC.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach(e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0);}),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var s;this._streamFallbackTypeCacheMap.forEach((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e);});}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e);});}),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(s=this._joinInfo)||void 0===s?void 0:s.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{jC.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"));}).catch(e=>{jC.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e));}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter(e=>!e._trust_in_room_).forEach(e=>{jC.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid});});},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach(e=>{e._trust_audio_mute_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,av.AUDIO,!1)),e._trust_video_mute_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,av.VIDEO,!1)),e._trust_audio_enabled_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(jC.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}));}));},1e3));}r();}),this._gateway.on(XI.REQUEST_NEW_GATEWAY_LIST,(e,t)=>{if(!this._joinInfo)return t(new LI(Hg.UNEXPECTED_ERROR,"can not recover, no join info"));uA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store).then(t=>{this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const i=[];t.gatewayInfo.gatewayAddrs.forEach(e=>{let{address:t}=e;const[n,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r});}),e(i);}).catch(t);}),this._gateway.on(XI.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(mT.NETWORK_QUALITY,e);}),this._gateway.on(XI.STREAM_TYPE_CHANGE,(e,t)=>{this.safeEmit(mT.STREAM_TYPE_CHANGED,e,t);eI.reportApiInvoke(this._sessionId,{name:hT.STREAM_TYPE_CHANGE,options:[e,t],tag:pT.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}));}),this._gateway.on(XI.IS_P2P_DISCONNECTED,e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0);}),this._gateway.on(XI.NEED_RENEW_SESSION,()=>{this._startSession();}),this._gateway.on(XI.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e));}catch(e){i(e);}}),this._gateway.on(XI.JOIN_RESPONSE,(e,t)=>{if(this.store.useP2P)return;const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:s,setup:o,cname:a}=Rx(e.ortc,t);this._p2pChannel.connect(n,i,r,s,o,a);}),this._gateway.on(XI.REQUEST_DC_CONNECTION_PARAMS,e=>{e(this._p2pChannel.getEstablishParams());}),this._gateway.on(XI.RESET_SIGNAL,e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents();}),this._gateway.on(XI.DATACHANNEL_FAILBACK,()=>{this._joinGateway();}),this._gateway.on(XI.DATACHANNEL_PRECONNECT,async(e,t,i,n)=>{var r,s,o,a,c,d;await this._p2pChannel.startP2PConnection({turnServer:null===(r=this._joinInfo)||void 0===r?void 0:r.turnServer},!0);const l=function(e,t){let i;return t&&t.ip&&"number"==typeof t.port?(i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],jC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(i.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),jC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],i;}(e,t);return this._p2pChannel.preConnect({iceUfrag:"".concat(null===(s=this._joinInfo)||void 0===s?void 0:s.apResponse.cid,"_").concat(null===(o=this._joinInfo)||void 0===o?void 0:o.apResponse.cert),icePwd:"".concat(null===(a=this._joinInfo)||void 0===a?void 0:a.apResponse.cid,"_").concat(null===(c=this._joinInfo)||void 0===c?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(d=RC("FINGERPRINT"))&&void 0!==d?d:e.fingerprint}]},l,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(i).catch(n);});}_handleGatewaySignalEvents(){this._gateway.signal.on(fI.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(fI.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(fI.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc)),this._gateway.signal.on(fI.ON_ADD_VIDEO_STREAM,e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId)),this._gateway.signal.on(fI.ON_REMOTE_DATASTREAM_UPDATE,e=>{this._handleUpdateDataChannel(e);}),this._gateway.signal.on(fI.ON_REMOTE_FULL_DATASTREAM_INFO,e=>{this._handleUpdateDataChannel({added:e.datastreams,deleted:[]},!0);}),this._gateway.signal.on(fI.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(fI.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(fI.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,av.AUDIO,!0)),this._gateway.signal.on(fI.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,av.AUDIO,!1)),this._gateway.signal.on(fI.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,av.VIDEO,!0)),this._gateway.signal.on(fI.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,av.VIDEO,!1)),this._gateway.signal.on(fI.RECEIVE_METADATA,e=>{const t=XT(e.metadata);this.safeEmit(mT.RECEIVE_METADATA,e.uid,t);}),this._gateway.signal.on(fI.ON_DATA_STREAM,async e=>{var t;if(!e)return;let i=XT(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<PC)throw new LI(Hg.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(PC));const t=await async function(e,t,i){const n=i.subarray(0,PC),r=n.slice(8,PC),s=(r[0]<<8)+r[1],o=(n[6]<<8)+n[7],a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:OC,additionalData:new Uint8Array(lS(s,2))},t,i.subarray(PC));return new Uint8Array(a).subarray(0,o);}(this._encryptDataStreamIv,this._encryptDataStreamKey,i);i=t;}let n=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),i=this.remoteUsers.find(t=>t.uid===e.uid),r=null==t?void 0:t.audioRecv.find(e=>e.ssrc===(null==i?void 0:i._audioSSRC));n=null==r?void 0:r.jitterBufferMs;}null==n&&(n=0),bB(DB(DB({},e),{},{payload:i}),n,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)});}),this._gateway.signal.on(fI.ON_CRYPT_ERROR,()=>{JT(()=>{jC.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(mT.CRYPT_ERROR);},this._sessionId);}),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{jC.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,ET.TOKEN_EXPIRE),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset();}),this._gateway.signal.on(fI.ON_STREAM_FALLBACK_UPDATE,e=>{jC.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(mT.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover");}),this._gateway.signal.on(fI.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),jC.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))));}),this._gateway.signal.on(fI.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0);}),this._gateway.signal.on(fI.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1);}),this._gateway.signal.on(_I.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case EI.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some(e=>{let{stream_type:t}=e;return t===JI.Audio;}),s=e.some(e=>{let{stream_type:t}=e;return t!==JI.Audio;}),o=e.some(e=>{let{stream_type:t}=e;return t===JI.Screen||t===JI.ScreenLow;});"offer"===t.state&&eI.publish(this._joinInfo.sid,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Hg.TIMEOUT,audio:r,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:o,audioName:r?null===(i=e.find(e=>{let{stream_type:t}=e;return t===JI.Audio;}))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:s?null===(n=e.find(e=>{let{stream_type:t}=e;return t!==JI.Audio;}))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0});}break;}case EI.SUBSCRIBE:t&&eI.subscribe(this._joinInfo.sid,{succ:!1,ec:Hg.TIMEOUT,audio:t.stream_type===av.AUDIO,video:t.stream_type===av.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,t.ssrcId)});}}),this._gateway.signal.on(fI.ON_P2P_OK,e=>{this.uid,this._uid;}),this._gateway.signal.on(fI.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;RC("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter(e=>!sI(e.string_id||e.stream_id,this.channelName)));const t=[],i=[];for(const n of e.users){let e=this._users.find(e=>e._uintid===n.stream_id);e?e._trust_in_room_=!0:(e=new sV(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(mT.USER_JOINED,e)));const r=ZI.Audio&n.stream_type,s=(ZI.Video|ZI.LwoVideo)&n.stream_type,o=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=s&&e.hasVideo;s&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(mT.USER_PUBLISHED,e,"audio")),s&&!c&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(mT.USER_PUBLISHED,e,"video")),(r&&!a||s&&!c||o)&&t.push(e),s&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"});}i.length>0&&(jC.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map(e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType)).join("; ")," ")),this.massSubscribe(i).catch(e=>{jC.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString());})),this.getListeners(mT.PUBLISHED_USER_LIST).length>0?RC("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(jC.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>e.uid).join(", "))),this.safeEmit(mT.PUBLISHED_USER_LIST,t)):jC.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map(e=>e.uid).join(", ")));}),this._gateway.signal.on(fI.ON_RTP_CAPABILITY_CHANGE,e=>{const{video_codec:t}=e;this._p2pChannel instanceof cF&&this._p2pChannel.updateRemoteRTPCapabilities(t.map(e=>e.toLowerCase()).filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}));});}_handleP2PEvents(){this._gateway.signal.on(fI.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect();}),this._gateway.signal.on(vv.PUBLISH,(e,t,i)=>{const{uid:n}=e;e.forEach(e=>{const{kind:r,ssrcs:s,mid:o,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,n,s[0].ssrcId,o);const c=this._users.find(e=>e.uid===n);return c&&this._p2pChannel instanceof hV?this._p2pChannel.mockSubscribe(c,r,s[0].ssrcId,o).then(()=>{t();}).catch(i):t(),this._handleMuteStream(n,r,!!a);});}),this._gateway.signal.on(vv.CALL,async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e));}catch(e){i(e);}}),this._gateway.signal.on(_I.P2P_CONNECTION,async e=>{this._p2pChannel instanceof hV&&(await this._p2pChannel.p2pConnect(e));}),this._gateway.signal.on(vv.UNPUBLISH,async(e,t,i)=>{if(this._p2pChannel instanceof hV){const{unpubMsg:n,uid:r}=e,s=this._users.find(e=>e.uid===r);if(!s)return jC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{n.forEach(async e=>{let{stream_type:t}=e;const i=t===JI.Audio?av.AUDIO:av.VIDEO;await this._p2pChannel.unsubscribe(s,i),this._handleMuteStream(r,i,!0);}),t();}catch(e){i(e);}}}),this._gateway.signal.on(vv.CONTROL,async(e,t)=>{const{action:i}=e;switch(i){case Av.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,av.VIDEO,!0);break;case Av.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,av.AUDIO,!0);break;case Av.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,av.VIDEO,!1);break;case Av.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,av.AUDIO,!1);}}),this._gateway.signal.on(vv.RESTART_ICE,async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{const{direction:i,iceParameter:n}=e;if(i!==TI.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n));}else this._p2pChannel.handleDisconnect(i),t();}catch(e){i(e);}}),this._gateway.signal.on(vv.CANDIDATE,e=>{if(this._p2pChannel instanceof hV){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i);}}),this._p2pChannel.on(hv.RequestP2PRestartICE,async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(vv.RESTART_ICE,e,i===TI.SEND_ONLY));}catch(e){i(e);}}),this._p2pChannel.on(hv.LocalCandidate,e=>{this._gateway.sendExtensionMessage(vv.CANDIDATE,JSON.stringify(e),!0);}),this._p2pChannel.on(hv.RequestP2PMuteLocal,async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(vv.CONTROL,e,!0),t();}catch(e){i(e);}}),this._p2pChannel.on(hv.RequestP2PUnmuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestP2PMuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.StateChange,(e,t)=>{t===uv.Connected&&this._p2pChannel.republish();});}_handleP2PChannelEvents(){this._p2pChannel.on(hv.RequestMuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestUnmuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i);}),this._p2pChannel.on(hv.RequestRePublishDataChannel,(e,t,i)=>{cg.all(e.map(async e=>{await this._p2pChannel.publishDataChannel([e]);const t={streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId};try{await this._gateway.publishDataChannel(this._uid,t,!0);}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e;}})).then(t).catch(i);}),this._p2pChannel.on(hv.RequestReSubscribe,async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===av.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t();}catch(e){i(e);}}),this._p2pChannel.on(hv.RequestUpload,(e,t)=>{this._gateway.upload(e,t);}),this._p2pChannel.on(hv.RequestUploadStats,e=>{this._gateway.uploadWRTCStats(e);}),this._p2pChannel.on(hv.MediaReconnectStart,e=>{this.safeEmit(mT.MEDIA_RECONNECT_START,e);}),this._p2pChannel.on(hv.MediaReconnectEnd,e=>{this.safeEmit(mT.MEDIA_RECONNECT_END,e);}),this._p2pChannel.on(hv.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT());}),this._p2pChannel.on(hv.RequestRestartICE,async e=>{if(this._p2pChannel instanceof hV)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n});}catch(e){return void t.throw(e);}const{iceParameters:s}=function(e){const t=e.iceParameters;return {iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}};}(r);await t.next({remoteIceParameters:s});}),this._p2pChannel.on(hv.RequestReconnect,async()=>{this._gateway.reconnect();}),this._p2pChannel.on(hv.RequestReconnectPC,async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:s}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),{dtlsParameters:o,iceParameters:a,candidates:c,rtpCapabilities:d,setup:l,cname:u}=Rx(r,s);await this._p2pChannel.connect(a,o,c,d,l,u),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe();}),this._p2pChannel.on(hv.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i();}),this._p2pChannel.on(hv.P2PLost,()=>{this.safeEmit(mT.P2P_LOST,this.store.uid);}),this._p2pChannel.on(hv.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig);}),this._p2pChannel.on(hv.ConnectionTypeChange,e=>{this.safeEmit(mT.IS_USING_CLOUD_PROXY,e);}),this._p2pChannel.on(hv.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50});}),this._p2pChannel.on(hv.QueryClientConnectionState,e=>{e(this.connectionState);});}getKeyMetrics(){return this.store.keyMetrics;}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{const t=[...new Set(e.inspectType)];t.forEach(e=>{var t;if(!bn(t=["supervise","moderation"]).call(t,e))throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] ").concat(e," is not a valid inspect type."));}),e.inspectType=t;}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const t=new FF(e);this._inspect=t,this.handleVideoInspectEvents(this._inspect),await t.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES);}catch(e){throw Array.isArray(e)?e[0]:e;}}async disableContentInspect(){if(!this._inspect)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0;}catch(e){throw Array.isArray(e)?e[0]:e;}}async setImageModeration(e,t){if(Yg(e,"enabled"),e){if(!t)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config is necessary"));if(zg(t.interval,"interval",1e3,1/0),t&&t.extraInfo&&t.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config.extraInfo length cannot exceed 1024 bytes"));if(t&&t.vendor&&t.vendor.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config.vendor length cannot exceed 1024 bytes"));if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,'] can not enable image moderation, not joined"'));try{if(this._moderation)return void this._moderation.updateConfig(t);const e=new gB(t);this._moderation=e,this.handleImageModerationEvents(this._moderation),await e.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES);}catch(e){throw Array.isArray(e)?e[0]:e;}}else {if(!this._moderation)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0;}catch(e){throw Array.isArray(e)?e[0]:e;}}}setP2PTransport(e){if(function(e){qg(e,"transport",["default","auto","relay","sd-rtn"]);}(e),"p2p"!==this.mode)throw new LI(Hg.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,jC.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e));}handleImageModerationEvents(e){e.on(Cv.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(mT.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===Rv.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new LI(Hg.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage();}}),e.on(Cv.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0]);});}handleVideoInspectEvents(e){e.on(mv.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(mT.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===_v.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(mT.CONTENT_INSPECT_ERROR,new LI(Hg.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage();}}),e.on(mv.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===Hg.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return jC.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(mT.CONTENT_INSPECT_RESULT,e,t);}),e.on(mv.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0]);});}getJoinChannelServiceRecords(){return jC.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords;}async setPublishAudioFilterEnabled(e){Yg(e,"enabled"),SC("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&(await this._gateway.setPublishAudioFilterEnabled(e));}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0;}}}DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"leave",null),DI([$C({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof lb))return [t];t=[t];}return t.map(e=>e?Object(e).toString():"null");}}),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],PB.prototype,"publish",null),DI([$C({argsMap:(e,t)=>(t||(t=[]),t instanceof aP?[t.getChannelId()]:(Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId())))}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"unpublish",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],PB.prototype,"subscribe",null),DI([$C({argsMap:(e,t,i)=>[t,i]}),PI("design:type",Function),PI("design:paramtypes",[Object,String]),PI("design:returntype",cg)],PB.prototype,"presubscribe",null),DI([$C({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return [null==t?void 0:t.uid,i];})}),PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],PB.prototype,"massSubscribe",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],PB.prototype,"unsubscribe",null),DI([$C({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return {uid:null==t?void 0:t.uid,mediaType:i};})}),PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],PB.prototype,"massUnsubscribe",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setLowStreamParameter",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"enableDualStream",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"disableDualStream",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Object]),PI("design:returntype",cg)],PB.prototype,"setClientRole",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setTurnServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",void 0)],PB.prototype,"setLicense",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],PB.prototype,"startProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],PB.prototype,"stopProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],PB.prototype,"setLocalAccessPointsV2",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Array,String]),PI("design:returntype",void 0)],PB.prototype,"setLocalAccessPoints",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",cg)],PB.prototype,"setRemoteDefaultVideoStreamType",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",cg)],PB.prototype,"setRemoteVideoStreamType",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",cg)],PB.prototype,"setStreamFallbackOption",null),DI([$C({argsMap:(e,t)=>[t]}),PI("design:type",Function),PI("design:paramtypes",[String,String,Uint8Array,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setEncryptionConfig",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],PB.prototype,"renewToken",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],PB.prototype,"enableAudioVolumeIndicator",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Boolean]),PI("design:returntype",cg)],PB.prototype,"startLiveStreaming",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setLiveTranscoding",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],PB.prototype,"stopLiveStreaming",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Object]),PI("design:returntype",cg)],PB.prototype,"addInjectStreamUrl",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"removeInjectStreamUrl",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[IV]),PI("design:returntype",cg)],PB.prototype,"startChannelMediaRelay",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[IV]),PI("design:returntype",cg)],PB.prototype,"updateChannelMediaRelay",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"stopChannelMediaRelay",null),DI([$C({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"sendCustomReportMessage",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",cg)],PB.prototype,"pickSVCLayer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setRTMConfig",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"enableContentInspect",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"disableContentInspect",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object]),PI("design:returntype",cg)],PB.prototype,"setImageModeration",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",void 0)],PB.prototype,"setP2PTransport",null),DI([$C({reportResult:!0}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Array)],PB.prototype,"getJoinChannelServiceRecords",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],PB.prototype,"setPublishAudioFilterEnabled",null);class LB{constructor(e,t){sh(this,"id",0),sh(this,"element",void 0),sh(this,"peerPair",void 0),sh(this,"context",void 0),sh(this,"audioPlayerElement",void 0),sh(this,"audioTrack",void 0),LB.count+=1,this.id=LB.count,this.element=e,this.context=t;}initPeers(){this.peerPair=[new RTCPeerConnection(),new RTCPeerConnection()],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t;};}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new cg(t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription);};});},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n);}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print();}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t);}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print();}if(!t){throw new LI(Hg.LOCAL_AEC_ERROR,"no dest node when local aec").print();}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i;}getElement(){return this.element;}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp();}close(){jC.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach(e=>{e.close();}),this.peerPair=void 0,this.audioPlayerElement=void 0;}}sh(LB,"count",0);const kB=window.AudioContext||window.webkitAudioContext;class MB{constructor(){sh(this,"units",[]),sh(this,"context",void 0);}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return jC.debug("the system does not need to process local aec"),-1;this.context||(this.context=new kB());let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new LB(e,this.context),this.units.push(t)),t.startEchoCancellation(),jC.debug("start processing local audio echo cancellation, id is",t.id),t.id;}_doesEnvironmentNeedAEC(){return Sg().name!==Eg.SAFARI;}}DI([$C({report:eI}),PI("design:type",Function),PI("design:paramtypes",[HTMLAudioElement]),PI("design:returntype",Number)],MB.prototype,"processExternalMediaAEC",null);const UB=new MB();function xB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function VB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xB(Object(i),!0).forEach(function(t){sh(e,t,i[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xB(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t));});}return e;}const FB=window||document;function BB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!FB)return;const i=GB._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(GB.onSecurityPolicyViolation||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;RC("CSP_DETECTED_HOSTNAME_LIST").some(e=>bn(t).call(t,e))&&(GB.onSecurityPolicyViolation&&"function"==typeof GB.onSecurityPolicyViolation&&GB.onSecurityPolicyViolation(e),GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0&&GB.safeEmit(Tv.SECURITY_POLICY_VIOLATION,e));};i&&FB.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)&&FB.addEventListener("securitypolicyviolation",n),GB._cspEventHandlerPointer=n;}SC("PROCESS_ID","process-".concat(nS(8,""),"-").concat(nS(4,""),"-").concat(nS(4,""),"-").concat(nS(4,""),"-").concat(nS(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter");}catch(e){return void jC.error("Error loading sdk config",e.message);}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();jC.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e=>{if(Object.prototype.hasOwnProperty.call(TC,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;CC[e]=n,TC[e]=n;}});}catch(t){jC.error("Error loading mutableParamsCache: ".concat(e),t.message);}}(),Array.isArray(CC.AREAS)&&CC.AREAS.length>0&&Jy(CC.AREAS,!0);const jB=(e,t,i)=>{jC.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),SC(e,t,i);},GB=function(e){const t=new dT(),i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===Tv.SECURITY_POLICY_VIOLATION&&BB(t,!0);}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return VB(VB({},i),n);}({__TRACK_LIST__:VA,VERSION:EC,BUILD:gC,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:jB,getParameter:RC,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection();t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const i=(await t.createOffer()).sdp;if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t;}(i);}catch(e){throw new LI(Hg.CREATE_OFFER_FAILED,e.toString&&e.toString()).print();}return e;},checkSystemRequirements:function(){const e=eI.reportApiInvoke(null,{name:hT.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:pT.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n);}catch(e){return jC.error("check system requirement failed: ",e),!1;}let i=!1;const n=Sg();n.name===Eg.CHROME&&Number(n.version)>=58&&(!yg()||vg())&&(i=!0),n.name===Eg.FIREFOX&&Number(n.version)>=56&&(i=!0),n.name===Eg.OPERA&&Number(n.version)>=45&&(i=!0),n.name===Eg.SAFARI&&Number(n.version)>=11&&(i=!0),(Fg()||Sg().name===Eg.QQ)&&(i=!0),jC.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r;},getDevices:function(e){return kb.enumerateDevices(!0,!0,e);},getMicrophones:function(e){return kb.getRecordingDevices(e);},getCameras:function(e){return kb.getCamerasDevices(e);},getElectronScreenSources:yb,getPlaybackDevices:function(e){return kb.getSpeakers(e);},createClient:function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=eI.reportApiInvoke(null,{name:hT.CREATE_CLIENT,options:[t],tag:pT.TRACER});try{!function(e){qg(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),qg(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&qg(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Xg(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&CT(e.turnServer),void 0!==e.httpRetryConfig&&ST(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&ST(e.websocketRetryConfig);}(t);}catch(e){throw i.onError(e),e;}return OB()||("vp9"===t.codec&&(t.codec="vp8",jC.debug("browser not support vp9, force use vp8")),SC("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),i.onSuccess(),new PB(DB(DB({forceWaitGatewayResponse:!0},t),{},{role:bn(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}));},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CAM_VIDEO_TRACK,options:[vw({},e)]}),i=rw(e),n=nS(8,"track-cam-");let r=null;const s="720p_auto"===e.encoderConfig;jC.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{r=(await Nb({video:i},n)).getVideoTracks()[0]||null;}catch(e){throw t.onError(e),e;}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(jC);}e.optimizationMode&&yw(n,r,e,LA(e.encoderConfig));const o=new Cw(r,e,i,e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return s&&o.startMonitorStats(),t.onSuccess(o.getTrackId()),jC.info("create camera video success, trackId:",n),o;},createCustomVideoTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new Rw(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,nS(8,"track-cus-"),[jA.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),jC.info("create custom video track success with config",e,"trackId",i.getTrackId()),i;},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_SCREEN_VIDEO_TRACK,options:[vw({},e),t]}),n="720p_auto"===e.encoderConfig;e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const r=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Ag()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:s}=e;(Ng(107)||Dg(107)||Pg(93))&&(i&&(qg(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(qg(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(qg(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(Ng(105)||Dg(105)||Pg(91))&&s&&(qg(s,"systemAudio",["exclude","include"]),t.systemAudio=s),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const o=e.encoderConfig?kA(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:o?o.width:void 0,maxHeight:o?o.height:void 0},o&&(o.frameRate&&("number"==typeof o.frameRate?(t.mandatory.maxFrameRate=o.frameRate,t.mandatory.minFrameRate=o.frameRate):(t.mandatory.maxFrameRate=o.frameRate.max||o.frameRate.ideal||o.frameRate.exact||void 0,t.mandatory.minFrameRate=o.frameRate.min||o.frameRate.ideal||o.frameRate.exact||void 0),t.frameRate=o.frameRate),o.width&&(t.width=o.width),o.height&&(t.height=o.height)),t;}(e),s=nS(8,"track-scr-v-");let o=null,a=null;const c=IA();if(!c.supportShareAudio&&"enable"===t){const e=new Kg(Hg.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw(jC);}jC.info("start create screen video track with config",e,"withAudio",t,"trackId",s);try{const e=await Nb({screen:r,screenAudio:"auto"===t?c.supportShareAudio:"enable"===t},s);o=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null;}catch(e){throw i.onError(e),e;}if(!o){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(jC);}if(!a&&"enable"===t){o&&o.stop();const e=new Kg(Hg.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(jC);}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){yw(s,o,e,e.encoderConfig&&kA(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax);}const d=new Rw(o,e.encoderConfig?kA(e.encoderConfig):{},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,s,[jA.SCREEN_TRACK]);if(n&&d.startMonitorStats(),!a)return i.onSuccess(d.getTrackId()),jC.info("create screen video track success","video:",d.getTrackId()),d;const l=new ew(a,void 0,nS(8,"track-scr-a-"),!1);return i.onSuccess([d.getTrackId(),l.getTrackId()]),jC.info("create screen video track success","video:",d.getTrackId(),"audio:",l.getTrackId()),[d,l];},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n="720p_auto"===t.encoderConfig,r=rw(t),s=sw(e),o=nS(8,"track-mic-"),a=nS(8,"track-cam-");let c=null,d=null;jC.info("start create camera video track(".concat(a,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await Nb({audio:s,video:r},"".concat(o,"-").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0];}catch(e){throw i.onError(e),e;}if(!c||!d){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw(jC);}t.optimizationMode&&yw(a,d,t,LA(t.encoderConfig));const l=new tw(c,e,s,o),u=new Cw(d,t,r,t.scalabiltyMode?MA(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,a);return n&&u.startMonitorStats(),i.onSuccess([l.getTrackId(),u.getTrackId()]),jC.info("create camera video track(".concat(a,") and microphone audio track(").concat(o,") success")),[l,u];},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=sw(e),n=nS(8,"track-mic-");let r=null;jC.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await Nb({audio:i},n)).getAudioTracks()[0]||null;}catch(e){throw t.onError(e),e;}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(jC);}const s=new tw(r,e,i,n);return t.onSuccess(s.getTrackId()),jC.info("create microphone audio track success, trackId:",n),s;},createCustomAudioTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new ew(e.mediaStreamTrack,e.encoderConfig?xA(e.encoderConfig):{},nS(8,"track-cus-"),!1);return jC.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i;},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const s={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},o=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_BUFFER_AUDIO_TRACK,options:[s]});if(RC("DISABLE_WEBAUDIO"))throw new Kg(Hg.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const a=nS(8,"track-buf-");jC.info("start create buffer source audio track with config",JSON.stringify(s),"trackId",a);const c=r;if(!(r instanceof AudioBuffer))try{r=await cw(r,i);}catch(e){return o.onError(e),e.throw(jC);}const d=new ow(r),l=new iw(c,d,n?xA(n):{},a);return jC.info("create buffer source audio track success, trackId:",a),o.onSuccess(l.getTrackId()),l;},setAppType:function(e){if(jC.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw jC.debug("Invalid appType"),new LI(Hg.INVALID_PARAMS,"invalid app type",e);SC("APP_TYPE",Math.floor(e));},setLogLevel:function(e){jC.setLogLevel(e);},enableLogUpload:function(){RC("USE_NEW_LOG")?SC("UPLOAD_LOG",!0):jC.enableLogUpload();},disableLogUpload:function(){RC("USE_NEW_LOG")?SC("UPLOAD_LOG",!1):jC.disableLogUpload();},createChannelMediaRelayConfiguration:function(){return new IV();},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof ew||e instanceof Nw)){const e=new LI(Hg.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw();}t&&t<1e3&&(t=1e3);const n=e instanceof ew?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let s=r,o=r;const a=Date.now();return new cg(r=>{const c=setInterval(()=>{const d=e.getVolumeLevel();s=d>s?d:s,o=d<o?d:o;const l=s-o>1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,o={duration:u,deviceLabel:n,maxVolumeLevel:s,result:t};jC.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(o))),i.onSuccess(o),r(t);}},200);});},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Rw||e instanceof Ow)){const e=new LI(Hg.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw();}t&&t<1e3&&(t=1e3);const n=e instanceof Rw?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(bg()||Ig())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([r]),s.play();const o=document.createElement("canvas");o.width=160,o.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,s=0,o=null;return new cg((a,c)=>{function d(){s>n&&r&&(r(),a(s));const t=i.getContext("2d");if(!t){const e=new LI(Hg.UNEXPECTED_ERROR,"can not get canvas 2d context.");return jC.error(e.toString()),void c(e);}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(o){for(let e=0;e<l;e+=3)if(d.data[e]!==o[e])return s+=1,void(o=d.data);o=d.data;}else o=d.data;}setTimeout(()=>{r&&(r(),a(s));},t),r=Tb(()=>{d();},30);});}(s,t,o,4),c=Date.now()-e;}catch(e){throw i.onError(e),e;}wB===Eg.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return jC.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d;},setArea:Jy,audioElementPlayCenter:Gb,resumeAudioContext:function(){Gb.autoResumeAfterInterruption(!0);},processExternalMediaAEC:function(e){UB.processExternalMediaAEC(e);},registerExtensions:function(e){const t=RC("PLUGIN_INFO")||[];e.forEach(e=>{"name"in e&&!bn(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=jC.extLog,i.reporter.hookApiInvoke=eI.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach(e=>{i.parameters[e]=RC(e);});}),jB("PLUGIN_INFO",t);},ChannelMediaRelayError:zI,ChannelMediaRelayEvent:YI,ChannelMediaRelayState:qI,RemoteStreamFallbackType:HA,RemoteStreamType:WA,ConnectionDisconnectedReason:ET,AudienceLatencyLevelType:_T,AREAS:ev});return Object.defineProperties(GB,{onAudioAutoplayFailed:{get:()=>Ub.onAudioAutoplayFailed,set:e=>{Ub.onAudioAutoplayFailed=e;}},onAutoplayFailed:{get:()=>Ub.onAutoplayFailed,set:e=>{Ub.onAutoplayFailed=e;}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>GB._onSecurityPolicyViolation,set(e){GB._onSecurityPolicyViolation=e,BB(e);}},__CLIENT_LIST__:{get:()=>RC("SHOW_GLOBAL_CLIENT_LIST")?rI:[]}}),kb.on(rb.CAMERA_DEVICE_CHANGED,e=>{jC.info("camera device changed",JSON.stringify(e)),GB.onCameraChanged&&GB.onCameraChanged(e),GB.safeEmit(Tv.CAMERA_CHANGED,e);}),kb.on(rb.RECORDING_DEVICE_CHANGED,e=>{jC.info("microphone device changed",JSON.stringify(e)),GB.onMicrophoneChanged&&GB.onMicrophoneChanged(e),GB.safeEmit(Tv.MICROPHONE_CHANGED,e);}),kb.on(rb.PLAYOUT_DEVICE_CHANGED,e=>{jC.debug("playout device changed",JSON.stringify(e)),GB.onPlaybackDeviceChanged&&GB.onPlaybackDeviceChanged(e),GB.safeEmit(Tv.PLAYBACK_DEVICE_CHANGED,e);}),Gb.onAutoplayFailed=()=>{jC.info("detect audio element autoplay failed"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed();},_b.on("autoplay-failed",()=>{jC.info("detect webaudio autoplay failed"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed(),GB.safeEmit(Tv.AUTOPLAY_FAILED);}),_b.on(vA.STATE_CHANGE,(e,t)=>{jC.info("audio context state changed: ".concat(t," => ").concat(e)),GB.onAudioContextStateChanged&&GB.onAudioContextStateChanged(e,t),GB.safeEmit(Tv.AUDIO_CONTEXT_STATE_CHANGED,e,t);}),wT.on(TT.NETWORK_STATE_CHANGE,(e,t)=>{jC.info("[network-indicator] network state changed, ".concat(t," => ").concat(e));}),window&&(window.__ARTC__=GB),GB;});})(AgoraRTC_NProduction);var AgoraRTC_NProductionExports=AgoraRTC_NProduction.exports;var AgoraRTC = /*@__PURE__*/getDefaultExportFromCjs(AgoraRTC_NProductionExports);
var Event$1 = /*#__PURE__*/function () {
function Event() {
_classCallCheck(this, Event);
this._stores = Object.create(null);
}
//订阅事件 ctx事件执行的上下文对象
_createClass(Event, [{
key: "on",
value: function on(event, handler, ctx) {
if (typeof handler !== 'function') {
throw new Error('listener must be a function');
}
(this._stores[event] = this._stores[event] || []).push({
cb: handler,
ctx: ctx
});
return this;
}
//事件类型只订阅一个事件,调用后删除
}, {
key: "once",
value: function once(event, handler, ctx) {
var that = this;
function on() {
that.off(event, on);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
handler.apply(this, args);
}
this.on(event, on, ctx);
return that;
}
//发布事件
}, {
key: "emit",
value: function emit(event) {
var store = this._stores[event];
if (store && store.length) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
for (var i = 0, len = store.length; i < len; i++) {
var _store$i$ctx;
store[i].cb.apply((_store$i$ctx = store[i].ctx) !== null && _store$i$ctx !== void 0 ? _store$i$ctx : null, args);
}
}
}
//取消订阅
}, {
key: "off",
value: function off(event, handler) {
// all 取消所有的订阅事件
if (!arguments.length) {
this._stores = {};
return;
}
// specific event
var store = this._stores[event];
if (!store) return;
// remove all handlers 取消当前事件类型对应的所有事件
if (arguments.length === 1) {
delete store[event];
return;
}
// remove specific handler 取消特定事件
for (var i = 0, len = store.length; i < len; i++) {
if (store[i].cb === handler) {
store.splice(i, 1);
break;
}
}
return;
}
}, {
key: "destroy",
value: function destroy() {
this._stores = Object.create(null);
}
}]);
return Event;
}();
var uuid = function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
};
// 客户端唯一标记
function clientUuid() {
var clientId = localStorage.getItem('__client');
if (clientId) {
return clientId;
}
clientId = 'C_' + uuid();
localStorage.setItem('__client', clientId);
return clientId;
}
function pick(obj, keys) {
return keys.reduce(function (acc, key) {
if (obj.hasOwnProperty(key)) {
acc[key] = obj[key];
}
return acc;
}, {});
}
function set(obj, path, value) {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0, -1).reduce(function (a, c, i) {
return Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {};
}, obj)[path[path.length - 1]] = value;
return obj;
}
function isObject$1(item) {
return item && _typeof(item) === 'object' && !Array.isArray(item);
}
function merge(target, source) {
var output = Object.assign({}, target);
if (isObject$1(target) && isObject$1(source)) {
Object.keys(source).forEach(function (key) {
if (isObject$1(source[key])) {
if (!(key in target)) Object.assign(output, _defineProperty({}, key, source[key]));else output[key] = merge(target[key], source[key]);
} else {
Object.assign(output, _defineProperty({}, key, source[key]));
}
});
}
return output;
}
function formatDate(timestamp) {
if (!timestamp) {
return '--';
}
var date = new Date(timestamp);
var year = date.getFullYear();
var month = String(date.getMonth() + 1).padStart(2, '0');
var day = String(date.getDate()).padStart(2, '0');
var hours = String(date.getHours()).padStart(2, '0');
var minutes = String(date.getMinutes()).padStart(2, '0');
var seconds = String(date.getSeconds()).padStart(2, '0');
var milliseconds = String(date.getMilliseconds()).padStart(3, '0');
return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds, ".").concat(milliseconds);
}
function isSupport() {
return 'getUserMedia' in navigator;
}
function isSupportProtocol() {
var _window$location = window.location,
protocol = _window$location.protocol,
hostname = _window$location.hostname;
if (protocol === 'https:' || protocol == 'file:') {
return true;
} else if (hostname === 'localhost' || hostname === '127.0.0.1') {
return true;
}
return false;
}
var http = {
get: function get(url, param) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var query;
if (param) {
query = Object.keys(param).map(function (item) {
return "".concat(item, "=").concat(param[item]);
}).join('&');
}
xhr.open('get', query ? "".concat(url, "?").concat(query) : url);
xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign'));
xhr.responseType = 'json';
xhr.send();
xhr.timeout = 15000;
xhr.onload = function () {
resolve(xhr.response);
};
xhr.ontimeout = function () {
reject({
code: '504',
text: 'timeout'
});
};
});
},
post: function post(url, params) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Uuid', sessionStorage.getItem('_duix_sessionId'));
xhr.setRequestHeader('Request-Date', new Date().getTime());
xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign'));
xhr.send(JSON.stringify(params));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseText) {
resolve(JSON.parse(xhr.responseText));
} else {
resolve();
}
} else {
reject('Error: ' + xhr.status);
}
}
};
});
},
stream: function stream(url, data) {
var xhr = new XMLHttpRequest();
xhr.open('post', url);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Uuid', sessionStorage.getItem('_duix_sessionId'));
xhr.setRequestHeader('Request-Date', new Date().getTime());
xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign'));
xhr.timeout = 15000;
xhr.send(data);
return new Promise(function (resolve, reject) {
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (err) {
console.warn(err);
reject();
};
xhr.ontimeout = function () {
console.warn('Request timed out');
reject('Request timed out');
};
});
}
};
function commonjsRequire(path) {
throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var localforage$1 = {exports: {}};
/*!
localForage -- Offline Storage, Improved
Version 1.10.0
https://localforage.github.io/localForage
(c) 2013-2017 Mozilla, Apache License 2.0
*/
(function (module, exports) {
(function (f) {
{
module.exports = f();
}
})(function () {
return function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof commonjsRequire == "function" && commonjsRequire;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f;
}
var l = n[o] = {
exports: {}
};
t[o][0].call(l.exports, function (e) {
var n = t[o][1][e];
return s(n ? n : e);
}, l, l.exports, e, t, n, r);
}
return n[o].exports;
}
var i = typeof commonjsRequire == "function" && commonjsRequire;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
}({
1: [function (_dereq_, module, exports) {
(function (global) {
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = called = ++called % 2;
};
} else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}).call(this, typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
}, {}],
2: [function (_dereq_, module, exports) {
var immediate = _dereq_(1);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED || typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
}, {
"1": 1
}],
3: [function (_dereq_, module, exports) {
(function (global) {
if (typeof global.Promise !== 'function') {
global.Promise = _dereq_(2);
}
}).call(this, typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
}, {
"2": 2
}],
4: [function (_dereq_, module, exports) {
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!idb || !idb.open) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
// Safari <10.1 does not meet our requirements for IDB support
// (see: https://github.com/pouchdb/pouchdb/issues/5572).
// Safari 10.1 shipped with fetch, we can use that to detect it.
// Note: this creates issues with `window.fetch` polyfills and
// overrides; see:
// https://github.com/localForage/localForage/issues/856
return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
_dereq_(3);
}
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === 'function') {
promise.then(callback);
}
if (typeof errorCallback === 'function') {
promise["catch"](errorCallback);
}
}
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
// Transaction Modes
var READ_ONLY = 'readonly';
var READ_WRITE = 'readwrite';
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise$1.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
var db = openreq.result;
db.onversionchange = function (e) {
// Triggered when the database is modified (e.g. adding an objectStore) or
// deleted (even when initiated by other sessions in different tabs).
// Closing the connection here prevents those operations from being blocked.
// If the database is accessed again later by this instance, the connection
// will be reopened or the database recreated as needed.
e.target.close();
};
resolve(db);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return createBlob([arrayBuff], {
type: encodedBlob.type
});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
})["catch"](function (err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
return Promise$1.resolve().then(function () {
if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
}).then(function () {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})["catch"](callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise$1.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback returns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor["continue"]();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (toString.call(value) === '[object Blob]') {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store["delete"](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openKeyCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openKeyCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(function (db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
var dropDBPromise = new Promise$1(function (resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = function () {
var db = req.result;
if (db) {
db.close();
}
reject(req.error);
};
req.onblocked = function () {
// Closing all open connections in onversionchange handler should prevent this situation, but if
// we do get here, it just means the request remains pending - eventually it will succeed or error
console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
};
req.onsuccess = function () {
var db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise.then(function (db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
} else {
promise = dbPromise.then(function (db) {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
var dropObjectPromise = new Promise$1(function (resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function (err) {
var db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = function () {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = function () {
var db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise.then(function (db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
}
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
_support: isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance
};
function isWebSQLValid() {
return typeof openDatabase === 'function';
}
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueType = '';
if (value) {
valueType = toString$1.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return createBlob([buffer], {
type: blobType
});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage$1(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise$1(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(t, dbInfo, function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(t, dbInfo, function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
return;
}
reject(sqlError);
}
});
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new Promise$1(function (resolve, reject) {
db.transaction(function (t) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db: db,
storeNames: storeNames
});
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
reject(sqlError);
});
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, '', '', 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db: db,
storeNames: [options.storeName]
});
}
}).then(function (operationInfo) {
return new Promise$1(function (resolve, reject) {
operationInfo.db.transaction(function (t) {
function dropTable(storeName) {
return new Promise$1(function (resolve, reject) {
t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
Promise$1.all(operations).then(function () {
resolve();
})["catch"](function (e) {
reject(e);
});
}, function (sqlError) {
reject(sqlError);
});
});
});
}
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1
};
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem;
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return Promise$1.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length$2(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise$1(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
if (!options.storeName) {
resolve(options.name + '/');
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2
};
var sameValue = function sameValue(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper
};
var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
var OptionalDriverMethods = ['dropInstance'];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) {
if (arg.hasOwnProperty(_key)) {
if (isArray(arg[_key])) {
arguments[0][_key] = arg[_key].slice();
} else {
arguments[0][_key] = arg[_key];
}
}
}
}
}
return arguments[0];
}
var LocalForage = function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function () {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
if (i === 'version' && typeof options[i] !== 'number') {
return new Error('Database version must be a number.');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise$1(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
var isRequired = !includes(OptionalDriverMethods, driverMethodName);
if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
reject(complianceError);
return;
}
}
var configureMissingMethods = function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
return function () {
var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) {
console.info('Redefining LocalForage driver: ' + driverName);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
return Promise$1.resolve();
}) : Promise$1.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})["catch"](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
}();
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localforage_js = new LocalForage();
module.exports = localforage_js;
}, {
"3": 3
}]
}, {}, [4])(4);
});
})(localforage$1);
var localforageExports = localforage$1.exports;
var localforage = /*@__PURE__*/getDefaultExportFromCjs(localforageExports);
var AgoraAppId = '1d6e70351c9c4359852dcf8fa79f3cae'; // '95875e3e1851444dafbb021574a61ba3'
var API = {
checkSig: '{DOMAIN}/duix-openapi-v2/sdk/checkSig?sig=',
queryConversationMaterialById: '{DOMAIN}/duix-openapi-v2/v1/queryConversationMaterialById',
getByQuestion: '{DOMAIN}/duix-openapi-v2/answer/getByQuestion',
getAnswerStream: '{DOMAIN}/duix-openapi-v2/answer/getAnswerStream',
// createSession: '{DOMAIN}/duix-openapi-v2/sdk/createSession',
ttsSynthesis: '{DOMAIN}/duix-openapi-v2/v1/ttsSynthesis',
saveLog: '{DOMAIN}/duix-openapi-v2/sdk/log/saveLogToFile',
saveEventTime: 'https://14.103.170.130/duix-openapi-v2/sdk/saveEventTime',
queryConversationDetail: '{DOMAIN}/duix-openapi-v2/sdk/getConversationById',
createSession: 'https://14.103.170.130/duix-openapi-v2/sdk/createSessionV2',
getSign: '{DOMAIN}/duix-openapi-v2/sdk/getApplicationSig',
queryConversationMaterial: '{DOMAIN}/duix-openapi-v2/sdk/queryConversationMaterial'
};
var ErrorMessage = {
4001: 'Start Fail.',
4002: 'Local im disconnected.',
4003: 'Server im unavailable.',
4005: 'Signature verification failed.',
4006: 'Signature verification exception.',
4007: 'The server actively closes the session.',
4008: 'Failed to get media stream.',
4009: 'Server error.',
// rtc相关
3001: 'RTC connect Fail'
};
var DefaultConfig = {
domain: 'https://duix.guiji.ai'
};
/**
* 会话状态:
* connecting: 正在开启;
* connected: 已开启;
* closing: 正在关闭;
* closed: 已关闭
*/
var SessionState = {
CONNECTING: 0,
CONNECTED: 1,
CLOSING: 2,
CLOSED: 3
};
/**
* 实时识别状态:
* opening: 正在开启
* opened: 已开启;
* closing: 正在关闭;
* closed: 已关闭
*/
var AsrState = {
OPENING: 0,
OPENED: 1,
CLOSING: 2,
CLOSED: 3
};
/**
* 录音状态:
* opening: 正在开启
* opened: 已开启
* closing: 正在关闭
* closed: 已关闭
*/
var RecordState = {
OPENING: 0,
OPENED: 1,
CLOSING: 2,
CLOSED: 3
};
var SpeakState = {
SPEAKING: 0,
SLIENT: 1
};
var _this = undefined;
var style = 'background:green;color:#fff;padding:0 2px;';
localforage.config({
version: 1.0,
storeName: 'duixlog'
});
var LEVEL = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3
};
var Logger = /*#__PURE__*/function () {
function Logger(catalogue) {
_classCallCheck(this, Logger);
this.option = {
level: 'info'
};
this.option.catalogue = catalogue;
this.logger = console;
}
_createClass(Logger, [{
key: "debug",
value: function debug() {
if (LEVEL[this.option.level.toUpperCase()] <= LEVEL.DEBUG) {
var _this$logger;
(_this$logger = this.logger).debug.apply(_this$logger, ['%cDUIX', style].concat(Array.prototype.slice.call(arguments)));
this._storage.apply(this, arguments);
}
}
}, {
key: "info",
value: function info() {
if (LEVEL[this.option.level.toUpperCase()] <= LEVEL.INFO) {
var _this$logger2;
(_this$logger2 = this.logger).info.apply(_this$logger2, ['%cDUIX', style].concat(Array.prototype.slice.call(arguments)));
this._storage.apply(this, arguments);
}
}
}, {
key: "warn",
value: function warn() {
if (LEVEL[this.option.level.toUpperCase()] <= LEVEL.WARN) {
var _this$logger3;
(_this$logger3 = this.logger).warn.apply(_this$logger3, ['%cDUIX', style].concat(Array.prototype.slice.call(arguments)));
this._storage.apply(this, arguments);
}
}
}, {
key: "error",
value: function error() {
if (LEVEL[this.option.level.toUpperCase()] <= LEVEL.ERROR) {
var _this$logger4;
(_this$logger4 = this.logger).error.apply(_this$logger4, ['%cDUIX', style].concat(Array.prototype.slice.call(arguments)));
this._storage.apply(this, arguments);
}
}
}, {
key: "_storage",
value: function _storage() {
// const logs = Array.from(arguments).map((item) => {
// if (typeof item === 'string') return item
// return JSON.stringify(item)
// })
// const sessionId = sessionStorage.getItem('_duix_sessionId')
// localforage.setItem(uuid(), { timestamp: new Date().getTime(), uuid: sessionId, text: logs.join(' ') })
}
}]);
return Logger;
}();
Logger.start = function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var domain = options.domain,
interval = options.interval;
Logger.domain = domain || DefaultConfig.domain;
Logger.interval = interval;
// setInterval(() => Logger.report(), Logger.interval)
};
Logger.report = function () {
try {
var url = API.saveLog.replace('{DOMAIN}', Logger.domain);
var clientId = clientUuid().substring(0, 10);
localforage.keys().then(function (keys) {
Promise.all(keys.map(function (key) {
return localforage.getItem(key);
})).then(function (values) {
var list = values.filter(function (item) {
return !!item;
});
list.sort(function (a, b) {
return a.timestamp - b.timestamp;
});
if (list.length > 0) {
http.post(url, list.map(function (log) {
return "\u3010".concat(clientId, "\u3011\u3010").concat(formatDate(log.timestamp), "\u3011\u3010").concat(log.uuid, "\u3011\u3010").concat(log.text, "\u3011");
}));
keys.map(function (k) {
return localforage.removeItem(k);
});
}
});
});
} catch (e) {
_this.warn('Logger report failed.');
}
};
/**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
var EPSILON = 0.000001;
var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
if (!Math.hypot) Math.hypot = function () {
var y = 0,
i = arguments.length;
while (i--) {
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
};
/**
* 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.
* @module mat4
*/
/**
* Creates a new identity mat4
*
* @returns {mat4} a new 4x4 matrix
*/
function create$3() {
var out = new ARRAY_TYPE(16);
if (ARRAY_TYPE != Float32Array) {
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
}
out[0] = 1;
out[5] = 1;
out[10] = 1;
out[15] = 1;
return out;
}
/**
* Set a mat4 to the identity matrix
*
* @param {mat4} out the receiving matrix
* @returns {mat4} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Generates a orthogonal projection matrix with the given bounds.
* The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
* which matches WebGL/OpenGL's clip volume.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function orthoNO(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right);
var bt = 1 / (bottom - top);
var nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
}
/**
* Alias for {@link mat4.orthoNO}
* @function
*/
var ortho = orthoNO;
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis.
* If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {ReadonlyVec3} eye Position of the viewer
* @param {ReadonlyVec3} center Point the viewer is looking at
* @param {ReadonlyVec3} up vec3 pointing up
* @returns {mat4} out
*/
function lookAt(out, eye, center, up) {
var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
var eyex = eye[0];
var eyey = eye[1];
var eyez = eye[2];
var upx = up[0];
var upy = up[1];
var upz = up[2];
var centerx = center[0];
var centery = center[1];
var centerz = center[2];
if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
return identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.hypot(z0, z1, z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.hypot(x0, x1, x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.hypot(y0, y1, y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
}
/**
* 3 Dimensional Vector
* @module vec3
*/
/**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/
function create$2() {
var out = new ARRAY_TYPE(3);
if (ARRAY_TYPE != Float32Array) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
}
return out;
}
/**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/
function fromValues$2(x, y, z) {
var out = new ARRAY_TYPE(3);
out[0] = x;
out[1] = y;
out[2] = z;
return out;
}
/**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
(function () {
var vec = create$2();
return function (a, stride, offset, count, fn, arg) {
var i, l;
if (!stride) {
stride = 3;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];
vec[1] = a[i + 1];
vec[2] = a[i + 2];
fn(vec, vec, arg);
a[i] = vec[0];
a[i + 1] = vec[1];
a[i + 2] = vec[2];
}
return a;
};
})();
/**
* 4 Dimensional Vector
* @module vec4
*/
/**
* Creates a new, empty vec4
*
* @returns {vec4} a new 4D vector
*/
function create$1() {
var out = new ARRAY_TYPE(4);
if (ARRAY_TYPE != Float32Array) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
}
return out;
}
/**
* Creates a new vec4 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} a new 4D vector
*/
function fromValues$1(x, y, z, w) {
var out = new ARRAY_TYPE(4);
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
}
/**
* Calculates the dot product of two vec4's
*
* @param {ReadonlyVec4} a the first operand
* @param {ReadonlyVec4} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
/**
* Perform some operation over an array of vec4s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
(function () {
var vec = create$1();
return function (a, stride, offset, count, fn, arg) {
var i, l;
if (!stride) {
stride = 4;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];
vec[1] = a[i + 1];
vec[2] = a[i + 2];
vec[3] = a[i + 3];
fn(vec, vec, arg);
a[i] = vec[0];
a[i + 1] = vec[1];
a[i + 2] = vec[2];
a[i + 3] = vec[3];
}
return a;
};
})();
/**
* 2 Dimensional Vector
* @module vec2
*/
/**
* Creates a new, empty vec2
*
* @returns {vec2} a new 2D vector
*/
function create() {
var out = new ARRAY_TYPE(2);
if (ARRAY_TYPE != Float32Array) {
out[0] = 0;
out[1] = 0;
}
return out;
}
/**
* Creates a new vec2 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} a new 2D vector
*/
function fromValues(x, y) {
var out = new ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
}
/**
* Perform some operation over an array of vec2s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
(function () {
var vec = create();
return function (a, stride, offset, count, fn, arg) {
var i, l;
if (!stride) {
stride = 2;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];
vec[1] = a[i + 1];
fn(vec, vec, arg);
a[i] = vec[0];
a[i + 1] = vec[1];
}
return a;
};
})();
var vsSource$1 = "\nattribute vec4 aVertexPosition;\nattribute vec2 aTexturePosition;\nuniform mat4 uModelMatrix;\nuniform mat4 uViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying lowp vec2 vTexturePosition;\nvoid main(void) {\n gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * aVertexPosition;\n vTexturePosition = aTexturePosition;\n}\n";
// Fragment shader program
var fsSource$1 = "\nprecision mediump float;\nvarying lowp vec2 vTexturePosition;\nuniform sampler2D uTexture; \nvoid main(void) {\n\n vec4 color = texture2D(uTexture, vTexturePosition);\n vec4 alphacolor = texture2D(uTexture, vTexturePosition + vec2(0.5, 0));\n\n color.a = alphacolor.r;\n\n gl_FragColor = color;\n\n}\n";
var RectMaskRender = /*#__PURE__*/function () {
function RectMaskRender(gl, width, height) {
_classCallCheck(this, RectMaskRender);
_defineProperty(this, "gl", undefined);
_defineProperty(this, "width", 0);
_defineProperty(this, "height", 0);
_defineProperty(this, "programInfo", undefined);
_defineProperty(this, "buffers", undefined);
this.width = width;
this.height = height;
this.gl = gl;
this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, 1);
var _this$initShaderProgr = this.initShaderProgram(vsSource$1, fsSource$1),
shaderProgram = _this$initShaderProgr.shaderProgram,
vertexShader = _this$initShaderProgr.vertexShader,
fragmentShader = _this$initShaderProgr.fragmentShader;
this.programInfo = {
program: shaderProgram,
vshader: vertexShader,
fshader: fragmentShader,
attribLocations: {
vertexPosition: this.gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
texturePosition: this.gl.getAttribLocation(shaderProgram, 'aTexturePosition')
},
uniformLocations: {
projectionMatrix: this.gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelMatrix: this.gl.getUniformLocation(shaderProgram, 'uModelMatrix'),
viewMatrix: this.gl.getUniformLocation(shaderProgram, 'uViewMatrix'),
texture: this.gl.getUniformLocation(shaderProgram, 'uTexture')
}
};
this.buffers = this.initBuffers();
var texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.NEAREST);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.NEAREST);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
this.texture = texture;
}
_createClass(RectMaskRender, [{
key: "updateTexture",
value: function updateTexture(rgbabuf) {
var textunit = 3;
this.gl.activeTexture(this.gl.TEXTURE0 + textunit);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, rgbabuf);
this.drawNow();
}
}, {
key: "getRGBA",
value: function getRGBA() {
var pixels = new Uint8Array(this.width * this.height * 4);
this.gl.readPixels(0, 0, this.width, this.height, this.gl.RGBA, this.gl.UNSIGNED_BYTE, pixels);
return pixels;
}
}, {
key: "destroy",
value: function destroy() {
if (this.buffers.position) {
this.gl.deleteBuffer(this.buffers.position);
}
if (this.buffers.texposition) {
this.gl.deleteBuffer(this.buffers.texposition);
}
if (this.buffers.indices) {
this.gl.deleteBuffer(this.buffers.indices);
}
if (this.texture) {
this.gl.deleteTexture(this.texture);
}
if (this.programInfo.program) {
this.gl.deleteProgram(this.programInfo.program);
}
if (this.programInfo.vshader) {
this.gl.deleteShader(this.programInfo.vshader);
}
if (this.programInfo.fshader) {
this.gl.deleteShader(this.programInfo.fshader);
}
}
}, {
key: "drawNow",
value: function drawNow() {
this.gl.viewport(0, 0, this.width, this.height);
this.gl.clearColor(0.0, 0.0, 0.0, 0.0); // Clear to black, fully opaque
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
var zNear = 0.1;
var zFar = 100.0;
var projectionMatrix = create$3();
ortho(projectionMatrix, -1, 1, -1, 1, zNear, zFar);
var modelMatrix = create$3();
identity(modelMatrix);
var viewMatrix = create$3();
lookAt(viewMatrix, fromValues$2(0, 0, 0), fromValues$2(0, 0, -1), fromValues$2(0, 1, 0));
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.position);
this.gl.vertexAttribPointer(this.programInfo.attribLocations.vertexPosition, 3, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.texposition);
this.gl.vertexAttribPointer(this.programInfo.attribLocations.texturePosition, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.texturePosition);
var textunit = 2;
this.gl.activeTexture(this.gl.TEXTURE0 + textunit);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.buffers.indices);
this.gl.useProgram(this.programInfo.program);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.projectionMatrix, false, projectionMatrix);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.modelMatrix, false, modelMatrix);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.viewMatrix, false, viewMatrix);
this.gl.uniform1i(this.programInfo.uniformLocations.texture, textunit);
this.gl.drawElements(this.gl.TRIANGLES, 6, this.gl.UNSIGNED_SHORT, 0);
}
}, {
key: "initBuffers",
value: function initBuffers() {
var _texturePos;
var positionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
var positions = [
// Front face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0];
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);
var facePos = [[0.0, 1.0], [0.5, 1.0], [0.5, 0.0], [0.0, 0.0]];
// Convert the array of colors into a table for all the vertices.
var texturePos = [];
texturePos = (_texturePos = texturePos).concat.apply(_texturePos, facePos);
var texpositionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, texpositionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(texturePos), this.gl.STATIC_DRAW);
// Build the element array buffer; this specifies the indices
// into the vertex arrays for each face's vertices.
var indexBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
var indices = [0, 1, 2, 0, 2, 3];
// Now send the element array to GL
this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this.gl.STATIC_DRAW);
return {
position: positionBuffer,
texposition: texpositionBuffer,
indices: indexBuffer
};
}
}, {
key: "initShaderProgram",
value: function initShaderProgram(vsSource, fsSource) {
var vertexShader = this.loadShader(this.gl.VERTEX_SHADER, vsSource);
var fragmentShader = this.loadShader(this.gl.FRAGMENT_SHADER, fsSource);
var shaderProgram = this.gl.createProgram();
this.gl.attachShader(shaderProgram, vertexShader);
this.gl.attachShader(shaderProgram, fragmentShader);
this.gl.linkProgram(shaderProgram);
if (!this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS)) {
console.error('Unable to initialize the shader program: ' + this.gl.getProgramInfoLog(shaderProgram));
return;
}
return {
shaderProgram: shaderProgram,
vertexShader: vertexShader,
fragmentShader: fragmentShader
};
}
}, {
key: "loadShader",
value: function loadShader(type, source) {
var shader = this.gl.createShader(type);
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
console.error('An error occurred compiling the shaders: ' + this.gl.getShaderInfoLog(shader));
this.gl.deleteShader(shader);
return;
}
return shader;
}
}]);
return RectMaskRender;
}();
var vsSource = "\nattribute vec4 aVertexPosition;\nattribute vec2 aTexturePosition;\nuniform mat4 uModelMatrix;\nuniform mat4 uViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying highp vec2 vTexturePosition;\nvoid main(void) {\n gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * aVertexPosition;\n vTexturePosition = aTexturePosition;\n}\n";
// Fragment shader program
var fsSource = "\nprecision highp float;\nvarying highp vec2 vTexturePosition;\nuniform sampler2D uTexture; \n\n\nuniform float opacity; //\u4E0D\u900F\u660E [0.0 , 1.0] \u9ED8\u8BA4 1.0\nuniform float contrast; //\u5BF9\u6BD4\u5EA6 [-1.0, 1.0] \u9ED8\u8BA4 0\nuniform float brightness; //\u4EAE\u5EA6 [-1.0, 1.0] \u9ED8\u8BA4 0\nuniform float gamma; //gamma [-1.0, 1.0] \u9ED8\u8BA4 0\n\n\nuniform float similarity; //\u76F8\u4F3C\u5EA6 [0.0 , 1.0] \u9ED8\u8BA4 0.4\nuniform float smoothness; //\u5E73\u6ED1\u5EA6 [0.0 , 1.0] \u9ED8\u8BA4 0.08\nuniform float spill; //\u4E3B\u8272\u6CC4\u9732\u51CF\u5C11 [0.0 , 1.0] \u9ED8\u8BA4 0.1\nuniform vec2 chroma_key; //\u62A0\u56FE\u989C\u8272 RGB->YCbCr,\u8FD9\u91CC\u53EA\u8981 Cb\u548CCr \u4E24\u4E2A\u989C\u8272\u5206\u91CF\nuniform vec2 pixel_size; //\u4E00\u4E2A\u50CF\u7D20\u5728\u7EB9\u7406\u7A7A\u95F4\u7684\u5927\u5C0F (1.0/width, 1.0/height)\n\nvec4 cb_v4 = vec4( -0.100644, -0.338572, 0.439216, 0.501961);\nvec4 cr_v4 = vec4( 0.439216, -0.398942, -0.040274, 0.501961);\n\n\nvec4 CalcColor(vec4 rgba)\n{\n\treturn vec4(pow(rgba.rgb, vec3(gamma, gamma, gamma)) * contrast + brightness, rgba.a);\n}\n\nfloat GetChromaDist(vec3 rgb)\n{\n\tfloat cb = dot(rgb.rgb, cb_v4.xyz) + cb_v4.w;\n\tfloat cr = dot(rgb.rgb, cr_v4.xyz) + cr_v4.w;\n\treturn distance(chroma_key, vec2(cb, cr));\n}\n\n\nvec3 SampleTexture(vec2 uv)\n{\n\tvec3 rgb = texture2D(uTexture, uv).rgb;\n return rgb;\n}\n\nfloat GetBoxFilteredChromaDist(vec3 rgb, vec2 texCoord)\n{\n\tvec2 h_pixel_size = pixel_size / 2.0;\n\tvec2 point_0 = vec2(pixel_size.x, h_pixel_size.y);\n\tvec2 point_1 = vec2(h_pixel_size.x, -pixel_size.y);\n\tfloat distVal = GetChromaDist(SampleTexture(texCoord-point_0));\n\tdistVal += GetChromaDist(SampleTexture(texCoord+point_0));\n\tdistVal += GetChromaDist(SampleTexture(texCoord-point_1));\n\tdistVal += GetChromaDist(SampleTexture(texCoord+point_1));\n\tdistVal *= 2.0;\n distVal += GetChromaDist(rgb);\n\treturn distVal / 9.0;\n}\n\nvec4 ProcessChromaKey(vec4 rgba, vec2 uv)\n{\n\tfloat chromaDist = GetBoxFilteredChromaDist(rgba.rgb, uv);\n\tfloat baseMask = chromaDist - similarity;\n\tfloat fullMask = pow(clamp(baseMask / smoothness, 0.0, 1.0), 1.5);\n\tfloat spillVal = pow(clamp(baseMask / spill, 0.0, 1.0), 1.5);\n\n\trgba.a *= opacity;\n\trgba.a *= fullMask;\n\n\tfloat desat = dot(rgba.rgb, vec3(0.2126, 0.7152, 0.0722));\n\trgba.rgb = mix(vec3(desat, desat, desat), rgba.rgb, spillVal);\n\n\treturn CalcColor(rgba);\n}\n\nvec4 PSChromaKeyRGBA(vec2 uv) \n{\n\tvec4 rgba = texture2D(uTexture, uv);\n\trgba.rgb = max(vec3(0.0, 0.0, 0.0), rgba.rgb / rgba.a);\n\trgba = ProcessChromaKey(rgba, uv);\n //rgba.rgb *= rgba.a;\n\treturn rgba;\n}\n\n\nvoid main(void) {\n\n gl_FragColor = PSChromaKeyRGBA(vTexturePosition);\n\n}\n";
var RectRender = /*#__PURE__*/function () {
function RectRender(gl, width, height) {
_classCallCheck(this, RectRender);
_defineProperty(this, "gl", undefined);
_defineProperty(this, "width", 0);
_defineProperty(this, "height", 0);
_defineProperty(this, "programInfo", undefined);
_defineProperty(this, "buffers", undefined);
_defineProperty(this, "settings", undefined);
this.width = width;
this.height = height;
this.gl = gl;
this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, 1);
var _this$initShaderProgr = this.initShaderProgram(vsSource, fsSource),
shaderProgram = _this$initShaderProgr.shaderProgram,
vertexShader = _this$initShaderProgr.vertexShader,
fragmentShader = _this$initShaderProgr.fragmentShader;
this.programInfo = {
program: shaderProgram,
vshader: vertexShader,
fshader: fragmentShader,
attribLocations: {
vertexPosition: this.gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
texturePosition: this.gl.getAttribLocation(shaderProgram, 'aTexturePosition')
},
uniformLocations: {
projectionMatrix: this.gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelMatrix: this.gl.getUniformLocation(shaderProgram, 'uModelMatrix'),
viewMatrix: this.gl.getUniformLocation(shaderProgram, 'uViewMatrix'),
texture: this.gl.getUniformLocation(shaderProgram, 'uTexture'),
opacity: this.gl.getUniformLocation(shaderProgram, 'opacity'),
contrast: this.gl.getUniformLocation(shaderProgram, 'contrast'),
brightness: this.gl.getUniformLocation(shaderProgram, 'brightness'),
gamma: this.gl.getUniformLocation(shaderProgram, 'gamma'),
similarity: this.gl.getUniformLocation(shaderProgram, 'similarity'),
smoothness: this.gl.getUniformLocation(shaderProgram, 'smoothness'),
spill: this.gl.getUniformLocation(shaderProgram, 'spill'),
chroma_key: this.gl.getUniformLocation(shaderProgram, 'chroma_key'),
pixel_size: this.gl.getUniformLocation(shaderProgram, 'pixel_size')
}
};
this.buffers = this.initBuffers();
var texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.NEAREST);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.NEAREST);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
this.texture = texture;
this.settings = {};
this.settings.opacity = 1.0;
this.settings.contrast = 1.0;
this.settings.brightness = 0.;
this.settings.gamma = 1.0;
this.settings.similarity = 0.4;
this.settings.smoothness = 0.08;
this.settings.spill = 0.1;
var chromeColor = fromValues$1(0., 1., 0., 1.0); //这里默认是绿色,可以调整其他颜色
var cb_v4 = fromValues$1(-0.100644, -0.338572, 0.439216, 0.501961);
var cr_v4 = fromValues$1(0.439216, -0.398942, -0.040274, 0.501961);
this.settings.chroma_key = fromValues(dot(chromeColor, cb_v4), dot(chromeColor, cr_v4));
this.settings.pixel_size = fromValues(1.0 / width, 1.0 / height);
}
_createClass(RectRender, [{
key: "updateTexture",
value: function updateTexture(rgbabuf) {
var textunit = 3;
this.gl.activeTexture(this.gl.TEXTURE0 + textunit);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, rgbabuf);
this.drawNow();
}
}, {
key: "getRGBA",
value: function getRGBA() {
var pixels = new Uint8Array(this.width * this.height * 4);
this.gl.readPixels(0, 0, this.width, this.height, this.gl.RGBA, this.gl.UNSIGNED_BYTE, pixels);
return pixels;
}
}, {
key: "destroy",
value: function destroy() {
if (this.buffers.position) {
this.gl.deleteBuffer(this.buffers.position);
}
if (this.buffers.texposition) {
this.gl.deleteBuffer(this.buffers.texposition);
}
if (this.buffers.indices) {
this.gl.deleteBuffer(this.buffers.indices);
}
if (this.texture) {
this.gl.deleteTexture(this.texture);
}
if (this.programInfo.program) {
this.gl.deleteProgram(this.programInfo.program);
}
if (this.programInfo.vshader) {
this.gl.deleteShader(this.programInfo.vshader);
}
if (this.programInfo.fshader) {
this.gl.deleteShader(this.programInfo.fshader);
}
}
}, {
key: "initBuffers",
value: function initBuffers() {
var _texturePos;
var positionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
var positions = [
// Front face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0];
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);
var facePos = [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
// Convert the array of colors into a table for all the vertices.
var texturePos = [];
texturePos = (_texturePos = texturePos).concat.apply(_texturePos, facePos);
var texpositionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, texpositionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(texturePos), this.gl.STATIC_DRAW);
// Build the element array buffer; this specifies the indices
// into the vertex arrays for each face's vertices.
var indexBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
var indices = [0, 1, 2, 0, 2, 3];
// Now send the element array to GL
this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this.gl.STATIC_DRAW);
return {
position: positionBuffer,
texposition: texpositionBuffer,
indices: indexBuffer
};
}
}, {
key: "drawNow",
value: function drawNow() {
this.gl.viewport(0, 0, this.width, this.height);
this.gl.clearColor(0.0, 0.0, 0.0, 0.0); // Clear to black, fully opaque
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
var zNear = 0.1;
var zFar = 100.0;
var projectionMatrix = create$3();
ortho(projectionMatrix, -1, 1, -1, 1, zNear, zFar);
var modelMatrix = create$3();
identity(modelMatrix);
var viewMatrix = create$3();
lookAt(viewMatrix, fromValues$2(0, 0, 0), fromValues$2(0, 0, -1), fromValues$2(0, 1, 0));
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.position);
this.gl.vertexAttribPointer(this.programInfo.attribLocations.vertexPosition, 3, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.texposition);
this.gl.vertexAttribPointer(this.programInfo.attribLocations.texturePosition, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.texturePosition);
var textunit = 2;
this.gl.activeTexture(this.gl.TEXTURE0 + textunit);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.buffers.indices);
this.gl.useProgram(this.programInfo.program);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.projectionMatrix, false, projectionMatrix);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.modelMatrix, false, modelMatrix);
this.gl.uniformMatrix4fv(this.programInfo.uniformLocations.viewMatrix, false, viewMatrix);
this.gl.uniform1i(this.programInfo.uniformLocations.texture, textunit);
this.gl.uniform1f(this.programInfo.uniformLocations.opacity, this.settings.opacity);
this.gl.uniform1f(this.programInfo.uniformLocations.contrast, this.settings.contrast);
this.gl.uniform1f(this.programInfo.uniformLocations.brightness, this.settings.brightness);
this.gl.uniform1f(this.programInfo.uniformLocations.gamma, this.settings.gamma);
this.gl.uniform1f(this.programInfo.uniformLocations.similarity, this.settings.similarity);
this.gl.uniform1f(this.programInfo.uniformLocations.smoothness, this.settings.smoothness);
this.gl.uniform1f(this.programInfo.uniformLocations.spill, this.settings.spill);
this.gl.uniform2fv(this.programInfo.uniformLocations.chroma_key, this.settings.chroma_key);
this.gl.uniform2fv(this.programInfo.uniformLocations.pixel_size, this.settings.pixel_size);
this.gl.drawElements(this.gl.TRIANGLES, 6, this.gl.UNSIGNED_SHORT, 0);
}
}, {
key: "initShaderProgram",
value: function initShaderProgram(vsSource, fsSource) {
var vertexShader = this.loadShader(this.gl.VERTEX_SHADER, vsSource);
var fragmentShader = this.loadShader(this.gl.FRAGMENT_SHADER, fsSource);
var shaderProgram = this.gl.createProgram();
this.gl.attachShader(shaderProgram, vertexShader);
this.gl.attachShader(shaderProgram, fragmentShader);
this.gl.linkProgram(shaderProgram);
if (!this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS)) {
console.error('Unable to initialize the shader program: ' + this.gl.getProgramInfoLog(shaderProgram));
return;
}
return {
shaderProgram: shaderProgram,
vertexShader: vertexShader,
fragmentShader: fragmentShader
};
}
}, {
key: "loadShader",
value: function loadShader(type, source) {
var shader = this.gl.createShader(type);
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
console.error('An error occurred compiling the shaders: ' + this.gl.getShaderInfoLog(shader));
this.gl.deleteShader(shader);
return;
}
return shader;
}
}]);
return RectRender;
}();
var alphacanvas = document.createElement('canvas'); // 最终展示的画布
var alphacanvasGL = createContextGL(alphacanvas);
var render = null;
var video = null;
var fps = 25;
var lastTime = 0;
/**
*
* @param {Element} v 需要扣背景的video标签
* @param {number} f fps默认25
*/
function wipe(v) {
var f = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 25;
video = v;
fps = f;
video.parentElement.appendChild(alphacanvas);
video.parentElement.style.fontSize = 0;
video.parentElement.style.positon = 'relative';
rollWipe();
}
/**
*
* @param {Element} v 需要扣背景的video标签
* @param {number} f fps默认25
*/
function wipeGreen(v) {
var f = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 25;
video = v;
fps = f;
video.parentElement.appendChild(alphacanvas);
video.parentElement.style.fontSize = 0;
video.parentElement.style.positon = 'relative';
rollWipeGreen();
}
/**
* 停止扣背景,释放资源
*/
function stopWipe() {
if (render) {
render.destroy();
render = null;
}
}
function createContextGL(canvas) {
var gl = null;
var validContextNames = ['webgl', 'experimental-webgl', 'moz-webgl', 'webkit-3d'];
var nameIndex = 0;
while (!gl && nameIndex < validContextNames.length) {
var contextName = validContextNames[nameIndex];
try {
var contextOptions = {
preserveDrawingBuffer: true,
antialias: true
};
gl = canvas.getContext(contextName, contextOptions);
} catch (e) {
gl = null;
}
if (!gl || typeof gl.getParameter !== 'function') {
gl = null;
}
++nameIndex;
}
return gl;
}
function rollWipe(timestamp) {
if (!timestamp) {
lastTime = timestamp = performance.now();
}
var frameTime = 1000 / fps;
if (timestamp - lastTime >= frameTime && 0 !== video.videoWidth) {
if (!render) {
render = new RectMaskRender(alphacanvasGL, video.videoWidth / 2, video.videoHeight);
alphacanvas.width = video.videoWidth / 2;
alphacanvas.height = video.videoHeight;
Object.assign(alphacanvas.style, {
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
});
}
render.updateTexture(video, video.videoWidth, video.videoHeight);
lastTime = timestamp;
}
requestAnimationFrame(rollWipe);
}
function rollWipeGreen(timestamp) {
if (!timestamp) {
lastTime = timestamp = performance.now();
}
var frameTime = 1000 / fps;
if (timestamp - lastTime >= frameTime && 0 !== video.videoWidth) {
if (!render) {
render = new RectRender(alphacanvasGL, video.videoWidth, video.videoHeight);
alphacanvas.width = video.videoWidth;
alphacanvas.height = video.videoHeight;
Object.assign(alphacanvas.style, {
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
});
}
render.updateTexture(video, video.videoWidth, video.videoHeight);
lastTime = timestamp;
}
requestAnimationFrame(rollWipeGreen);
}
var logger$4 = new Logger('webrtc');
var AgoraRtc = /*#__PURE__*/function (_Event) {
_inherits(AgoraRtc, _Event);
var _super = _createSuper(AgoraRtc);
function AgoraRtc() {
var _this;
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, AgoraRtc);
_this = _super.call(this);
_this.containerLable = null;
_this.dhVideo = null;
_this.client = AgoraRTC.createClient({
mode: "live",
codec: "vp8"
});
_this.localAudioTrack = null;
_this.remoteAudioTrack = null;
_this.remoteVideoTrack = null;
_this.sessionType = 'answer'; //'answer' 应答模式
_this.peeConfig = null;
_this.muted = false; //是否静音播放视频,默认不静音
_this.enhanceOpus = false; //是否开启立体声
_this.vpxMaxBitrate = 0; // 码率增强
_this.openAsr = false; // 是否立即开启ASR识别
_this.peerConnection = null;
_this.audioCtx = null;
_this.mediaStreamDest = null; //AudioNode结束节点
_this.mediaStreamSource = null; //通过createMediaStreamSource()创建的AudioNode节点
_this.mediaStreamConstraints = config.mediaStreamConstraints || {
audio: {
autoGainControl: false
}
};
_this.localMediaStream = null; //本地(采集设备)媒体流
_this.localStream = null; //AudioNode结束节点输出流可添加到RTCPeerConnection传输到远端
_this.remoteStream = null; //rtc远端媒体流
_this.reportTimer = null; //上报report事件定时器
_this.trackLength = 0;
// 摄像头
_this.camera = null;
_this.isStreamSwitch = false;
_this.isSupportVideoAgent = false;
_this.videoAgentContainer = null;
_this.cameraStream = null;
//音频
_this.dhAudio = null;
_this.useAudioAgent = false;
//展示媒体流容器
_this.setsContainerLable(config.containerLable);
return _this;
}
//开始连接创建RTCPeerConnection实例
_createClass(AgoraRtc, [{
key: "open",
value: function () {
var _open = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _options$enhanceOpus,
_this2 = this;
var options,
_this$localAudioTrack,
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
options = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
this.sessionType = options.sessionType; //呼叫或应答
this.peeConfig = options.peeConfig;
this.muted = !!options.muted;
this.enhanceOpus = (_options$enhanceOpus = options.enhanceOpus) !== null && _options$enhanceOpus !== void 0 ? _options$enhanceOpus : this.enhanceOpus;
this.vpxMaxBitrate = options.vpxMaxBitrate;
this.openAsr = options.openAsr;
this.transparent = options.transparent;
this.wipeGreen = options.wipeGreen;
this.useVideoAgent = options.useVideoAgent;
this.videoAgentContainer = options.videoAgentContainer;
this.isSupportVideoAgent = options.isSupportVideoAgent;
this.useAudioAgent = options.useAudioAgent;
if (this.useAudioAgent) {
this.createDHAudio();
} else {
this.createDHVideo(options.transparent || options.wipeGreen);
}
this.client.on('user-published', /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(user, mediaType) {
var _this2$remoteAudioTra, _this2$remoteVideoTra, _this2$remoteAudioTra2;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
console.info('user-published', user, mediaType);
_context.next = 3;
return _this2.client.subscribe(user, mediaType);
case 3:
if (mediaType === "video") {
_this2.remoteVideoTrack = user.videoTrack;
}
if (mediaType === "audio") {
_this2.remoteAudioTrack = user.audioTrack;
}
if (_this2.useAudioAgent && _this2.remoteAudioTrack) {
_this2.remoteStream = new MediaStream([(_this2$remoteAudioTra = _this2.remoteAudioTrack) === null || _this2$remoteAudioTra === void 0 ? void 0 : _this2$remoteAudioTra._originMediaStreamTrack]);
_this2.dhAudio.srcObject = _this2.remoteStream;
_this2.playRemoteStream();
} else if (_this2.remoteAudioTrack && _this2.remoteVideoTrack) {
_this2.remoteStream = new MediaStream([(_this2$remoteVideoTra = _this2.remoteVideoTrack) === null || _this2$remoteVideoTra === void 0 ? void 0 : _this2$remoteVideoTra._originMediaStreamTrack, (_this2$remoteAudioTra2 = _this2.remoteAudioTrack) === null || _this2$remoteAudioTra2 === void 0 ? void 0 : _this2$remoteAudioTra2._originMediaStreamTrack]);
_this2.dhVideo.srcObject = _this2.remoteStream;
_this2.playRemoteStream();
}
_this2.client.on("user-unpublished", function (user) {
console.info('user-unpublished', user);
_this2.remoteVideoTrack = null;
_this2.remoteAudioTrack = null;
});
case 7:
case "end":
return _context.stop();
}
}, _callee);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}());
this.client.setClientRole("host");
_context2.next = 18;
return this.client.join(AgoraAppId, options.channelId, options.token, options.localUid);
case 18:
if (!this.openAsr) {
_context2.next = 25;
break;
}
_context2.next = 21;
return AgoraRTC.createMicrophoneAudioTrack();
case 21:
this.localAudioTrack = _context2.sent;
this.localMediaStream = new MediaStream([(_this$localAudioTrack = this.localAudioTrack) === null || _this$localAudioTrack === void 0 ? void 0 : _this$localAudioTrack._originMediaStreamTrack]);
_context2.next = 25;
return this.client.publish([this.localAudioTrack]);
case 25:
if (this.useVideoAgent && this.isSupportVideoAgent) {
this.createCamera();
}
case 26:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function open() {
return _open.apply(this, arguments);
}
return open;
}() //关闭连接
}, {
key: "close",
value: function close() {
var _this$remoteAudioTrac, _this$remoteVideoTrac;
this.trackLength = 0;
this.destroyCamera();
if (this.client) {
this.client.leave();
}
this.closeLocalMediaStream();
if (this.remoteStream) {
this.remoteStream.getTracks().forEach(function (track) {
track.stop();
});
this.remoteStream = null;
}
if (this.localMediaStream) {
this.localMediaStream.getTracks().forEach(function (track) {
track.stop();
});
this.localMediaStream = null;
}
(_this$remoteAudioTrac = this.remoteAudioTrack) === null || _this$remoteAudioTrac === void 0 ? void 0 : _this$remoteAudioTrac.close();
(_this$remoteVideoTrac = this.remoteVideoTrack) === null || _this$remoteVideoTrac === void 0 ? void 0 : _this$remoteVideoTrac.close();
this.remoteAudioTrack = null;
this.remoteVideoTrack = null;
this.dhAudio = null;
this.dhVideo = null;
stopWipe();
}
//设置容器
}, {
key: "setsContainerLable",
value: function setsContainerLable(containerLable) {
if (containerLable) {
containerLable = typeof containerLable === 'string' ? document.querySelector(containerLable) : containerLable instanceof HTMLElement ? containerLable : null;
}
if (!containerLable) {
throw new Error('containerLable is null');
}
this.containerLable = containerLable;
}
}, {
key: "mediaStreamConnect",
value: function mediaStreamConnect() {}
}, {
key: "setRemoteDescription",
value: function setRemoteDescription() {}
}, {
key: "addIceCandidate",
value: function addIceCandidate() {}
}, {
key: "mediaStreamReconnect",
value: function () {
var _mediaStreamReconnect = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var _this$client;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return AgoraRTC.createMicrophoneAudioTrack();
case 2:
this.localAudioTrack = _context3.sent;
(_this$client = this.client) === null || _this$client === void 0 ? void 0 : _this$client.publish([this.localAudioTrack]);
return _context3.abrupt("return", true);
case 5:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function mediaStreamReconnect() {
return _mediaStreamReconnect.apply(this, arguments);
}
return mediaStreamReconnect;
}()
}, {
key: "peerAddTrack",
value: function peerAddTrack() {}
//关闭本地媒体设备流
}, {
key: "closeLocalMediaStream",
value: function closeLocalMediaStream() {}
/**
* 创建视频标签
* @param {boolean} isTransparent 是否透明背景
* @returns
*/
}, {
key: "createDHVideo",
value: function createDHVideo(isTransparent) {
var _this3 = this;
if (this.dhVideo) return;
this.dhVideo = document.createElement('video');
this.dhVideo.autoplay = true; //远端流自动播放
this.dhVideo.muted = this.muted; //是否静音
this.dhVideo.addEventListener('playing', function () {
var _this3$dhVideo$style, _this3$dhVideo$style2;
logger$4.info('dhvideo playing', (_this3$dhVideo$style = _this3.dhVideo.style) === null || _this3$dhVideo$style === void 0 ? void 0 : _this3$dhVideo$style.visibility);
if (((_this3$dhVideo$style2 = _this3.dhVideo.style) === null || _this3$dhVideo$style2 === void 0 ? void 0 : _this3$dhVideo$style2.visibility) !== 'visible') {
_this3.showDHVideo();
_this3.emit(AgoraRtc.EventType.SHOW);
}
});
if (isTransparent) {
Object.assign(this.dhVideo.style, {
width: '1px',
height: '1px',
zIndex: -1,
position: 'absolute',
top: '50%',
left: '50%'
});
} else {
Object.assign(this.dhVideo.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
objectFit: 'cover'
});
}
Object.assign(this.dhVideo.style, {
visibility: 'hidden'
});
this.dhVideo.setAttribute('playsinline', true);
this.dhVideo.setAttribute('preload', 'auto');
Object.assign(this.containerLable.style, {
position: 'relative'
});
this.containerLable.appendChild(this.dhVideo);
}
}, {
key: "showDHVideo",
value: function showDHVideo() {
Object.assign(this.dhVideo.style, {
visibility: 'visible'
});
if (this.wipeGreen) {
// 优先使用扣绿幕方案,节省服端资源
wipeGreen(this.dhVideo);
} else if (this.transparent) {
wipe(this.dhVideo);
}
}
}, {
key: "hideDHVideo",
value: function hideDHVideo() {
if (this.dhVideo) {
Object.assign(this.dhVideo.style, {
visibility: 'hidden'
});
}
}
}, {
key: "removeVideoLabel",
value: function removeVideoLabel() {
if (this.containerLable && this.dhVideo) {
this.containerLable.removeChild(this.dhVideo);
this.dhVideo = null;
}
}
/**
* 设置远端媒体流静音状态
* @param {Boolean} muted true: 静音, false: 取消静音
*/
}, {
key: "setVideoMuted",
value: function setVideoMuted(muted) {
if (!this.dhVideo) return;
if (this.dhVideo.muted !== muted) {
this.dhVideo.muted = muted;
}
}
//发送SDP
}, {
key: "sendSdp",
value: function sendSdp(localDescription) {}
}, {
key: "playRemoteStream",
value: function playRemoteStream() {
var _this4 = this;
setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
var _this4$dhVideo$style;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
if (!_this4.useAudioAgent) {
_context4.next = 5;
break;
}
_context4.next = 3;
return _this4.dhAudio.play();
case 3:
_this4.emit(AgoraRtc.EventType.SHOW);
return _context4.abrupt("return");
case 5:
if (!(((_this4$dhVideo$style = _this4.dhVideo.style) === null || _this4$dhVideo$style === void 0 ? void 0 : _this4$dhVideo$style.visibility) !== 'visible')) {
_context4.next = 14;
break;
}
_context4.prev = 6;
_context4.next = 9;
return _this4.dhVideo.play();
case 9:
_context4.next = 14;
break;
case 11:
_context4.prev = 11;
_context4.t0 = _context4["catch"](6);
_this4.emit(AgoraRtc.EventType.NEEDUSERINTERACT);
case 14:
case "end":
return _context4.stop();
}
}, _callee4, null, [[6, 11]]);
})), 250);
}
}, {
key: "destroy",
value: function destroy() {
this.close();
_get(_getPrototypeOf(AgoraRtc.prototype), "destroy", this).call(this);
}
}, {
key: "createDHAudio",
value: function createDHAudio() {
if (this.dhAudio) return;
this.dhAudio = document.createElement('audio');
this.dhAudio.autoplay = true; //远端流自动播放
// Object.assign(this.dhAudio.style, {
// display: 'none',
// })
this.containerLable.appendChild(this.dhAudio);
}
}, {
key: "enableAudioContext",
value: function enableAudioContext() {
try {
var _this$localAudioTrack2;
(_this$localAudioTrack2 = this.localAudioTrack) === null || _this$localAudioTrack2 === void 0 ? void 0 : _this$localAudioTrack2.setMuted(false);
} catch (e) {}
}
}, {
key: "disableAudioContext",
value: function disableAudioContext() {
try {
var _this$localAudioTrack3;
(_this$localAudioTrack3 = this.localAudioTrack) === null || _this$localAudioTrack3 === void 0 ? void 0 : _this$localAudioTrack3.setMuted(true);
} catch (e) {}
}
}, {
key: "switchstreamBetweenDigitalAndCamera",
value: function switchstreamBetweenDigitalAndCamera() {
if (this.isSupportVideoAgent && this.camera && this.dhVideo) {
var tracks = this.peerConnection.getReceivers().map(function (receiver) {
return receiver.track;
});
if (this.isStreamSwitch) {
this.dhVideo.srcObject = this.remoteStream = new MediaStream([tracks[0], tracks[1]]);
this.camera.srcObject = this.cameraStream;
this.isStreamSwitch = false;
} else {
this.dhVideo.srcObject = this.cameraStream;
this.camera.srcObject = this.remoteStream = new MediaStream([tracks[0], tracks[1]]);
this.isStreamSwitch = true;
}
}
}
}, {
key: "createCamera",
value: function createCamera() {
var _this5 = this;
if (this.camera) return;
navigator.mediaDevices.getUserMedia({
video: {
facingMode: "user"
}
}).then(function (stream) {
_this5.cameraStream = stream;
var camera = _this5.camera = document.createElement('video');
camera.setAttribute('playsinline', true);
camera.setAttribute('autoplay', true);
camera.muted = true;
camera.srcObject = stream;
if (_this5.videoAgentContainer) {
Object.assign(camera.style, {
width: '100%',
height: '100%',
zIndex: 10,
position: 'absolute',
top: '0',
right: '0',
objectFit: 'cover',
transform: 'rotateY(180deg)'
});
var dom = document.querySelector(_this5.videoAgentContainer);
if (dom) {
dom.appendChild(camera);
}
} else {
Object.assign(camera.style, {
width: '25%',
height: '25%',
zIndex: 10,
position: 'absolute',
top: '0',
right: '0',
objectFit: 'cover',
transform: 'rotateY(180deg)'
});
_this5.containerLable.appendChild(camera);
}
_this5.showCamera();
});
}
}, {
key: "destroyCamera",
value: function destroyCamera() {
if (!this.camera) return;
this.cameraStream.getTracks().forEach(function (track) {
track.stop();
});
if (this.videoAgentContainer) {
var _document$querySelect;
(_document$querySelect = document.querySelector(this.videoAgentContainer)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.removeChild(this.camera);
} else {
var _this$containerLable;
(_this$containerLable = this.containerLable) === null || _this$containerLable === void 0 ? void 0 : _this$containerLable.removeChild(this.camera);
}
this.camera.srcObject = null;
this.camera = null;
this.cameraStream = null;
this.emit(AgoraRtc.EventType.CAMERACHANGE, {
status: 'hidden'
});
}
}, {
key: "switchCameraMode",
value: function () {
var _switchCameraMode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
var _videoTrack$getSettin,
_videoTrack$getSettin2,
_this6 = this;
var videoTrack, newFacingMode;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
videoTrack = this.cameraStream.getVideoTracks()[0];
if (videoTrack !== null && videoTrack !== void 0 && (_videoTrack$getSettin = videoTrack.getSettings()) !== null && _videoTrack$getSettin !== void 0 && _videoTrack$getSettin.facingMode) {
_context6.next = 4;
break;
}
logger$4.error("Currently there is no switching device");
return _context6.abrupt("return");
case 4:
newFacingMode = (videoTrack === null || videoTrack === void 0 || (_videoTrack$getSettin2 = videoTrack.getSettings()) === null || _videoTrack$getSettin2 === void 0 ? void 0 : _videoTrack$getSettin2.facingMode) === "user" ? "environment" : "user";
if (this.cameraStream) {
this.cameraStream.getTracks().forEach(function (track) {
return track.stop();
});
}
navigator.mediaDevices.getUserMedia({
video: {
facingMode: newFacingMode
}
}).then( /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(stream) {
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_this6.cameraStream = stream;
_this6.camera.srcObject = stream;
Object.assign(_this6.camera.style, {
transform: newFacingMode === 'environment' ? 'rotateY(0deg)' : 'rotateY(180deg)'
});
_this6.emit(AgoraRtc.EventType.CAMERACHANGE, {
mode: newFacingMode,
status: 'show'
});
case 4:
case "end":
return _context5.stop();
}
}, _callee5);
}));
return function (_x3) {
return _ref3.apply(this, arguments);
};
}())["catch"](function (error) {
var name = error.name,
message = error.message;
logger$4.error("getUserMedia failed. ".concat(name, ": ").concat(message));
});
case 7:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function switchCameraMode() {
return _switchCameraMode.apply(this, arguments);
}
return switchCameraMode;
}()
}, {
key: "playCamera",
value: function playCamera() {
if (this.camera) {
var _this$camera;
(_this$camera = this.camera) === null || _this$camera === void 0 ? void 0 : _this$camera.play();
}
}
}, {
key: "showCamera",
value: function showCamera() {
if (this.camera) {
Object.assign(this.camera.style, {
visibility: 'visible'
});
this.emit(AgoraRtc.EventType.CAMERACHANGE, {
status: 'show'
});
}
}
}, {
key: "hideCamera",
value: function hideCamera() {
if (this.camera) {
Object.assign(this.camera.style, {
visibility: 'hidden'
});
this.emit(AgoraRtc.EventType.CAMERACHANGE, {
status: 'hidden'
});
}
}
}]);
return AgoraRtc;
}(Event$1);
//自定义事件
_defineProperty(AgoraRtc, "EventType", {
STATUS: 'STATUS',
//状态更新
SENDSDP: 'SENDSDP',
//发送 answer SDP
SENDCANDIDATE: 'SENDCANDIDATE',
//发送candidate
REPORT: 'REPORT',
//报告网络信息
SHOW: 'SHOW',
//RTC流可显示
NEEDUSERINTERACT: 'NEEDUSERINTERACT',
//需要用户交互目前用来处理ioswebview内必须由用户出发play的问题
ASRSTART: 'ASRSTART',
ASRSTOP: 'ASRSTOP',
ASRDATA: 'ASRDATA',
SPEAKSTART: 'SPEAKSTART',
SPEAKSTOP: 'SPEAKSTOP',
SPEAKSECTION: 'SPEAKSECTION',
TTSSPEAKSTART: 'TTSSPEAKSTART',
TTSSPEAKSTOP: 'TTSSPEAKSTOP',
TTSSPEAKSECTION: 'TTSSPEAKSECTION',
CAMERACHANGE: 'CAMERACHANGE',
RESTARTICE: 'RESTARTICE'
});
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
let logDisabled_ = true;
let deprecationWarnings_ = true;
/**
* Extract browser version out of the provided user agent string.
*
* @param {!string} uastring userAgent string.
* @param {!string} expr Regular expression used as match criteria.
* @param {!number} pos position in the version string to be returned.
* @return {!number} browser version.
*/
function extractVersion(uastring, expr, pos) {
const match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
}
// Wraps the peerconnection event eventNameToWrap in a function
// which returns the modified event object (or false to prevent
// the event).
function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
if (!window.RTCPeerConnection) {
return;
}
const proto = window.RTCPeerConnection.prototype;
const nativeAddEventListener = proto.addEventListener;
proto.addEventListener = function (nativeEventName, cb) {
if (nativeEventName !== eventNameToWrap) {
return nativeAddEventListener.apply(this, arguments);
}
const wrappedCallback = e => {
const modifiedEvent = wrapper(e);
if (modifiedEvent) {
if (cb.handleEvent) {
cb.handleEvent(modifiedEvent);
} else {
cb(modifiedEvent);
}
}
};
this._eventMap = this._eventMap || {};
if (!this._eventMap[eventNameToWrap]) {
this._eventMap[eventNameToWrap] = new Map();
}
this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback]);
};
const nativeRemoveEventListener = proto.removeEventListener;
proto.removeEventListener = function (nativeEventName, cb) {
if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[eventNameToWrap]) {
return nativeRemoveEventListener.apply(this, arguments);
}
if (!this._eventMap[eventNameToWrap].has(cb)) {
return nativeRemoveEventListener.apply(this, arguments);
}
const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
this._eventMap[eventNameToWrap].delete(cb);
if (this._eventMap[eventNameToWrap].size === 0) {
delete this._eventMap[eventNameToWrap];
}
if (Object.keys(this._eventMap).length === 0) {
delete this._eventMap;
}
return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb]);
};
Object.defineProperty(proto, 'on' + eventNameToWrap, {
get() {
return this['_on' + eventNameToWrap];
},
set(cb) {
if (this['_on' + eventNameToWrap]) {
this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]);
delete this['_on' + eventNameToWrap];
}
if (cb) {
this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb);
}
},
enumerable: true,
configurable: true
});
}
function disableLog(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool + '. Please use a boolean.');
}
logDisabled_ = bool;
return bool ? 'adapter.js logging disabled' : 'adapter.js logging enabled';
}
/**
* Disable or enable deprecation warnings
* @param {!boolean} bool set to true to disable warnings.
*/
function disableWarnings(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool + '. Please use a boolean.');
}
deprecationWarnings_ = !bool;
return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
}
function log() {
if (typeof window === 'object') {
if (logDisabled_) {
return;
}
if (typeof console !== 'undefined' && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
}
}
/**
* Shows a deprecation warning suggesting the modern and spec-compatible API.
*/
function deprecated(oldMethod, newMethod) {
if (!deprecationWarnings_) {
return;
}
console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.');
}
/**
* Browser detector.
*
* @return {object} result containing browser and version
* properties.
*/
function detectBrowser(window) {
// Returned result object.
const result = {
browser: null,
version: null
};
// Fail early if it's not a browser
if (typeof window === 'undefined' || !window.navigator || !window.navigator.userAgent) {
result.browser = 'Not a browser.';
return result;
}
const {
navigator
} = window;
if (navigator.mozGetUserMedia) {
// Firefox.
result.browser = 'firefox';
result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1);
} else if (navigator.webkitGetUserMedia || window.isSecureContext === false && window.webkitRTCPeerConnection) {
// Chrome, Chromium, Webview, Opera.
// Version matches Chrome/WebRTC version.
// Chrome 74 removed webkitGetUserMedia on http as well so we need the
// more complicated fallback to webkitRTCPeerConnection.
result.browser = 'chrome';
result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
} else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
// Safari.
result.browser = 'safari';
result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
result.supportsUnifiedPlan = window.RTCRtpTransceiver && 'currentDirection' in window.RTCRtpTransceiver.prototype;
} else {
// Default fallthrough: not supported.
result.browser = 'Not a supported browser.';
return result;
}
return result;
}
/**
* Checks if something is an object.
*
* @param {*} val The something you want to check.
* @return true if val is an object, false otherwise.
*/
function isObject(val) {
return Object.prototype.toString.call(val) === '[object Object]';
}
/**
* Remove all empty objects and undefined values
* from a nested object -- an enhanced and vanilla version
* of Lodash's `compact`.
*/
function compactObject(data) {
if (!isObject(data)) {
return data;
}
return Object.keys(data).reduce(function (accumulator, key) {
const isObj = isObject(data[key]);
const value = isObj ? compactObject(data[key]) : data[key];
const isEmptyObject = isObj && !Object.keys(value).length;
if (value === undefined || isEmptyObject) {
return accumulator;
}
return Object.assign(accumulator, {
[key]: value
});
}, {});
}
/* iterates the stats graph recursively. */
function walkStats(stats, base, resultSet) {
if (!base || resultSet.has(base.id)) {
return;
}
resultSet.set(base.id, base);
Object.keys(base).forEach(name => {
if (name.endsWith('Id')) {
walkStats(stats, stats.get(base[name]), resultSet);
} else if (name.endsWith('Ids')) {
base[name].forEach(id => {
walkStats(stats, stats.get(id), resultSet);
});
}
});
}
/* filter getStats for a sender/receiver track. */
function filterStats(result, track, outbound) {
const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
const filteredResult = new Map();
if (track === null) {
return filteredResult;
}
const trackStats = [];
result.forEach(value => {
if (value.type === 'track' && value.trackIdentifier === track.id) {
trackStats.push(value);
}
});
trackStats.forEach(trackStat => {
result.forEach(stats => {
if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
walkStats(result, stats, filteredResult);
}
});
});
return filteredResult;
}
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
const logging = log;
function shimGetUserMedia$2(window, browserDetails) {
const navigator = window && window.navigator;
if (!navigator.mediaDevices) {
return;
}
const constraintsToChrome_ = function (c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
const cc = {};
Object.keys(c).forEach(key => {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
const r = typeof c[key] === 'object' ? c[key] : {
ideal: c[key]
};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
const oldname_ = function (prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return name === 'deviceId' ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
let oc = {};
if (typeof r.ideal === 'number') {
oc[oldname_('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname_('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname_('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_('', key)] = r.exact;
} else {
['min', 'max'].forEach(mix => {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
const shimConstraints_ = function (constraints, func) {
if (browserDetails.version >= 61) {
return func(constraints);
}
constraints = JSON.parse(JSON.stringify(constraints));
if (constraints && typeof constraints.audio === 'object') {
const remap = function (obj, a, b) {
if (a in obj && !(b in obj)) {
obj[b] = obj[a];
delete obj[a];
}
};
constraints = JSON.parse(JSON.stringify(constraints));
remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
constraints.audio = constraintsToChrome_(constraints.audio);
}
if (constraints && typeof constraints.video === 'object') {
// Shim facingMode for mobile & surface pro.
let face = constraints.video.facingMode;
face = face && (typeof face === 'object' ? face : {
ideal: face
});
const getSupportedFacingModeLies = browserDetails.version < 66;
if (face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment') && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) {
delete constraints.video.facingMode;
let matches;
if (face.exact === 'environment' || face.ideal === 'environment') {
matches = ['back', 'rear'];
} else if (face.exact === 'user' || face.ideal === 'user') {
matches = ['front'];
}
if (matches) {
// Look for matches in label, or use last cam for back (typical).
return navigator.mediaDevices.enumerateDevices().then(devices => {
devices = devices.filter(d => d.kind === 'videoinput');
let dev = devices.find(d => matches.some(match => d.label.toLowerCase().includes(match)));
if (!dev && devices.length && matches.includes('back')) {
dev = devices[devices.length - 1]; // more likely the back cam
}
if (dev) {
constraints.video.deviceId = face.exact ? {
exact: dev.deviceId
} : {
ideal: dev.deviceId
};
}
constraints.video = constraintsToChrome_(constraints.video);
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
});
}
}
constraints.video = constraintsToChrome_(constraints.video);
}
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
};
const shimError_ = function (e) {
if (browserDetails.version >= 64) {
return e;
}
return {
name: {
PermissionDeniedError: 'NotAllowedError',
PermissionDismissedError: 'NotAllowedError',
InvalidStateError: 'NotAllowedError',
DevicesNotFoundError: 'NotFoundError',
ConstraintNotSatisfiedError: 'OverconstrainedError',
TrackStartError: 'NotReadableError',
MediaDeviceFailedDueToShutdown: 'NotAllowedError',
MediaDeviceKillSwitchOn: 'NotAllowedError',
TabCaptureError: 'AbortError',
ScreenCaptureError: 'AbortError',
DeviceCaptureError: 'AbortError'
}[e.name] || e.name,
message: e.message,
constraint: e.constraint || e.constraintName,
toString() {
return this.name + (this.message && ': ') + this.message;
}
};
};
const getUserMedia_ = function (constraints, onSuccess, onError) {
shimConstraints_(constraints, c => {
navigator.webkitGetUserMedia(c, onSuccess, e => {
if (onError) {
onError(shimError_(e));
}
});
});
};
navigator.getUserMedia = getUserMedia_.bind(navigator);
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
if (navigator.mediaDevices.getUserMedia) {
const origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function (cs) {
return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {
if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(track => {
track.stop();
});
throw new DOMException('', 'NotFoundError');
}
return stream;
}, e => Promise.reject(shimError_(e))));
};
}
}
/*
* Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimGetDisplayMedia$1(window, getSourceId) {
if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
return;
}
if (!window.navigator.mediaDevices) {
return;
}
// getSourceId is a function that returns a promise resolving with
// the sourceId of the screen/window/tab to be shared.
if (typeof getSourceId !== 'function') {
console.error('shimGetDisplayMedia: getSourceId argument is not ' + 'a function');
return;
}
window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
return getSourceId(constraints).then(sourceId => {
const widthSpecified = constraints.video && constraints.video.width;
const heightSpecified = constraints.video && constraints.video.height;
const frameRateSpecified = constraints.video && constraints.video.frameRate;
constraints.video = {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: sourceId,
maxFrameRate: frameRateSpecified || 3
}
};
if (widthSpecified) {
constraints.video.mandatory.maxWidth = widthSpecified;
}
if (heightSpecified) {
constraints.video.mandatory.maxHeight = heightSpecified;
}
return window.navigator.mediaDevices.getUserMedia(constraints);
});
};
}
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimMediaStream(window) {
window.MediaStream = window.MediaStream || window.webkitMediaStream;
}
function shimOnTrack$1(window) {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get() {
return this._ontrack;
},
set(f) {
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
}
this.addEventListener('track', this._ontrack = f);
},
enumerable: true,
configurable: true
});
const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
if (!this._ontrackpoly) {
this._ontrackpoly = e => {
// onaddstream does not fire when a track is added to an existing
// stream. But stream.onaddtrack is implemented so we use that.
e.stream.addEventListener('addtrack', te => {
let receiver;
if (window.RTCPeerConnection.prototype.getReceivers) {
receiver = this.getReceivers().find(r => r.track && r.track.id === te.track.id);
} else {
receiver = {
track: te.track
};
}
const event = new Event('track');
event.track = te.track;
event.receiver = receiver;
event.transceiver = {
receiver
};
event.streams = [e.stream];
this.dispatchEvent(event);
});
e.stream.getTracks().forEach(track => {
let receiver;
if (window.RTCPeerConnection.prototype.getReceivers) {
receiver = this.getReceivers().find(r => r.track && r.track.id === track.id);
} else {
receiver = {
track
};
}
const event = new Event('track');
event.track = track;
event.receiver = receiver;
event.transceiver = {
receiver
};
event.streams = [e.stream];
this.dispatchEvent(event);
});
};
this.addEventListener('addstream', this._ontrackpoly);
}
return origSetRemoteDescription.apply(this, arguments);
};
} else {
// even if RTCRtpTransceiver is in window, it is only used and
// emitted in unified-plan. Unfortunately this means we need
// to unconditionally wrap the event.
wrapPeerConnectionEvent(window, 'track', e => {
if (!e.transceiver) {
Object.defineProperty(e, 'transceiver', {
value: {
receiver: e.receiver
}
});
}
return e;
});
}
}
function shimGetSendersWithDtmf(window) {
// Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
if (typeof window === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) {
const shimSenderWithDtmf = function (pc, track) {
return {
track,
get dtmf() {
if (this._dtmf === undefined) {
if (track.kind === 'audio') {
this._dtmf = pc.createDTMFSender(track);
} else {
this._dtmf = null;
}
}
return this._dtmf;
},
_pc: pc
};
};
// augment addTrack when getSenders is not available.
if (!window.RTCPeerConnection.prototype.getSenders) {
window.RTCPeerConnection.prototype.getSenders = function getSenders() {
this._senders = this._senders || [];
return this._senders.slice(); // return a copy of the internal state.
};
const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
let sender = origAddTrack.apply(this, arguments);
if (!sender) {
sender = shimSenderWithDtmf(this, track);
this._senders.push(sender);
}
return sender;
};
const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
origRemoveTrack.apply(this, arguments);
const idx = this._senders.indexOf(sender);
if (idx !== -1) {
this._senders.splice(idx, 1);
}
};
}
const origAddStream = window.RTCPeerConnection.prototype.addStream;
window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
this._senders = this._senders || [];
origAddStream.apply(this, [stream]);
stream.getTracks().forEach(track => {
this._senders.push(shimSenderWithDtmf(this, track));
});
};
const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
this._senders = this._senders || [];
origRemoveStream.apply(this, [stream]);
stream.getTracks().forEach(track => {
const sender = this._senders.find(s => s.track === track);
if (sender) {
// remove sender
this._senders.splice(this._senders.indexOf(sender), 1);
}
});
};
} else if (typeof window === 'object' && window.RTCPeerConnection && 'getSenders' in window.RTCPeerConnection.prototype && 'createDTMFSender' in window.RTCPeerConnection.prototype && window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
window.RTCPeerConnection.prototype.getSenders = function getSenders() {
const senders = origGetSenders.apply(this, []);
senders.forEach(sender => sender._pc = this);
return senders;
};
Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
get() {
if (this._dtmf === undefined) {
if (this.track.kind === 'audio') {
this._dtmf = this._pc.createDTMFSender(this.track);
} else {
this._dtmf = null;
}
}
return this._dtmf;
}
});
}
}
function shimGetStats(window) {
if (!window.RTCPeerConnection) {
return;
}
const origGetStats = window.RTCPeerConnection.prototype.getStats;
window.RTCPeerConnection.prototype.getStats = function getStats() {
const [selector, onSucc, onErr] = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats.apply(this, arguments);
}
// When spec-style getStats is supported, return those when called with
// either no arguments or the selector argument is null.
if (origGetStats.length === 0 && (arguments.length === 0 || typeof selector !== 'function')) {
return origGetStats.apply(this, []);
}
const fixChromeStats_ = function (response) {
const standardReport = {};
const reports = response.result();
reports.forEach(report => {
const standardStats = {
id: report.id,
timestamp: report.timestamp,
type: {
localcandidate: 'local-candidate',
remotecandidate: 'remote-candidate'
}[report.type] || report.type
};
report.names().forEach(name => {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
// shim getStats with maplike support
const makeMapStats = function (stats) {
return new Map(Object.keys(stats).map(key => [key, stats[key]]));
};
if (arguments.length >= 2) {
const successCallbackWrapper_ = function (response) {
onSucc(makeMapStats(fixChromeStats_(response)));
};
return origGetStats.apply(this, [successCallbackWrapper_, selector]);
}
// promise-support
return new Promise((resolve, reject) => {
origGetStats.apply(this, [function (response) {
resolve(makeMapStats(fixChromeStats_(response)));
}, reject]);
}).then(onSucc, onErr);
};
}
function shimSenderReceiverGetStats(window) {
if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) {
return;
}
// shim sender stats.
if (!('getStats' in window.RTCRtpSender.prototype)) {
const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
if (origGetSenders) {
window.RTCPeerConnection.prototype.getSenders = function getSenders() {
const senders = origGetSenders.apply(this, []);
senders.forEach(sender => sender._pc = this);
return senders;
};
}
const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
if (origAddTrack) {
window.RTCPeerConnection.prototype.addTrack = function addTrack() {
const sender = origAddTrack.apply(this, arguments);
sender._pc = this;
return sender;
};
}
window.RTCRtpSender.prototype.getStats = function getStats() {
const sender = this;
return this._pc.getStats().then(result =>
/* Note: this will include stats of all senders that
* send a track with the same id as sender.track as
* it is not possible to identify the RTCRtpSender.
*/
filterStats(result, sender.track, true));
};
}
// shim receiver stats.
if (!('getStats' in window.RTCRtpReceiver.prototype)) {
const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
if (origGetReceivers) {
window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
const receivers = origGetReceivers.apply(this, []);
receivers.forEach(receiver => receiver._pc = this);
return receivers;
};
}
wrapPeerConnectionEvent(window, 'track', e => {
e.receiver._pc = e.srcElement;
return e;
});
window.RTCRtpReceiver.prototype.getStats = function getStats() {
const receiver = this;
return this._pc.getStats().then(result => filterStats(result, receiver.track, false));
};
}
if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) {
return;
}
// shim RTCPeerConnection.getStats(track).
const origGetStats = window.RTCPeerConnection.prototype.getStats;
window.RTCPeerConnection.prototype.getStats = function getStats() {
if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) {
const track = arguments[0];
let sender;
let receiver;
let err;
this.getSenders().forEach(s => {
if (s.track === track) {
if (sender) {
err = true;
} else {
sender = s;
}
}
});
this.getReceivers().forEach(r => {
if (r.track === track) {
if (receiver) {
err = true;
} else {
receiver = r;
}
}
return r.track === track;
});
if (err || sender && receiver) {
return Promise.reject(new DOMException('There are more than one sender or receiver for the track.', 'InvalidAccessError'));
} else if (sender) {
return sender.getStats();
} else if (receiver) {
return receiver.getStats();
}
return Promise.reject(new DOMException('There is no sender or receiver for the track.', 'InvalidAccessError'));
}
return origGetStats.apply(this, arguments);
};
}
function shimAddTrackRemoveTrackWithNative(window) {
// shim addTrack/removeTrack with native variants in order to make
// the interactions with legacy getLocalStreams behave as in other browsers.
// Keeps a mapping stream.id => [stream, rtpsenders...]
window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
return Object.keys(this._shimmedLocalStreams).map(streamId => this._shimmedLocalStreams[streamId][0]);
};
const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
if (!stream) {
return origAddTrack.apply(this, arguments);
}
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
const sender = origAddTrack.apply(this, arguments);
if (!this._shimmedLocalStreams[stream.id]) {
this._shimmedLocalStreams[stream.id] = [stream, sender];
} else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
this._shimmedLocalStreams[stream.id].push(sender);
}
return sender;
};
const origAddStream = window.RTCPeerConnection.prototype.addStream;
window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
stream.getTracks().forEach(track => {
const alreadyExists = this.getSenders().find(s => s.track === track);
if (alreadyExists) {
throw new DOMException('Track already exists.', 'InvalidAccessError');
}
});
const existingSenders = this.getSenders();
origAddStream.apply(this, arguments);
const newSenders = this.getSenders().filter(newSender => existingSenders.indexOf(newSender) === -1);
this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
};
const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
delete this._shimmedLocalStreams[stream.id];
return origRemoveStream.apply(this, arguments);
};
const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
this._shimmedLocalStreams = this._shimmedLocalStreams || {};
if (sender) {
Object.keys(this._shimmedLocalStreams).forEach(streamId => {
const idx = this._shimmedLocalStreams[streamId].indexOf(sender);
if (idx !== -1) {
this._shimmedLocalStreams[streamId].splice(idx, 1);
}
if (this._shimmedLocalStreams[streamId].length === 1) {
delete this._shimmedLocalStreams[streamId];
}
});
}
return origRemoveTrack.apply(this, arguments);
};
}
function shimAddTrackRemoveTrack(window, browserDetails) {
if (!window.RTCPeerConnection) {
return;
}
// shim addTrack and removeTrack.
if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) {
return shimAddTrackRemoveTrackWithNative(window);
}
// also shim pc.getLocalStreams when addTrack is shimmed
// to return the original streams.
const origGetLocalStreams = window.RTCPeerConnection.prototype.getLocalStreams;
window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
const nativeStreams = origGetLocalStreams.apply(this);
this._reverseStreams = this._reverseStreams || {};
return nativeStreams.map(stream => this._reverseStreams[stream.id]);
};
const origAddStream = window.RTCPeerConnection.prototype.addStream;
window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
this._streams = this._streams || {};
this._reverseStreams = this._reverseStreams || {};
stream.getTracks().forEach(track => {
const alreadyExists = this.getSenders().find(s => s.track === track);
if (alreadyExists) {
throw new DOMException('Track already exists.', 'InvalidAccessError');
}
});
// Add identity mapping for consistency with addTrack.
// Unless this is being used with a stream from addTrack.
if (!this._reverseStreams[stream.id]) {
const newStream = new window.MediaStream(stream.getTracks());
this._streams[stream.id] = newStream;
this._reverseStreams[newStream.id] = stream;
stream = newStream;
}
origAddStream.apply(this, [stream]);
};
const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
this._streams = this._streams || {};
this._reverseStreams = this._reverseStreams || {};
origRemoveStream.apply(this, [this._streams[stream.id] || stream]);
delete this._reverseStreams[this._streams[stream.id] ? this._streams[stream.id].id : stream.id];
delete this._streams[stream.id];
};
window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
if (this.signalingState === 'closed') {
throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
}
const streams = [].slice.call(arguments, 1);
if (streams.length !== 1 || !streams[0].getTracks().find(t => t === track)) {
// this is not fully correct but all we can manage without
// [[associated MediaStreams]] internal slot.
throw new DOMException('The adapter.js addTrack polyfill only supports a single ' + ' stream which is associated with the specified track.', 'NotSupportedError');
}
const alreadyExists = this.getSenders().find(s => s.track === track);
if (alreadyExists) {
throw new DOMException('Track already exists.', 'InvalidAccessError');
}
this._streams = this._streams || {};
this._reverseStreams = this._reverseStreams || {};
const oldStream = this._streams[stream.id];
if (oldStream) {
// this is using odd Chrome behaviour, use with caution:
// https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
// Note: we rely on the high-level addTrack/dtmf shim to
// create the sender with a dtmf sender.
oldStream.addTrack(track);
// Trigger ONN async.
Promise.resolve().then(() => {
this.dispatchEvent(new Event('negotiationneeded'));
});
} else {
const newStream = new window.MediaStream([track]);
this._streams[stream.id] = newStream;
this._reverseStreams[newStream.id] = stream;
this.addStream(newStream);
}
return this.getSenders().find(s => s.track === track);
};
// replace the internal stream id with the external one and
// vice versa.
function replaceInternalStreamId(pc, description) {
let sdp = description.sdp;
Object.keys(pc._reverseStreams || []).forEach(internalId => {
const externalStream = pc._reverseStreams[internalId];
const internalStream = pc._streams[externalStream.id];
sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id);
});
return new RTCSessionDescription({
type: description.type,
sdp
});
}
function replaceExternalStreamId(pc, description) {
let sdp = description.sdp;
Object.keys(pc._reverseStreams || []).forEach(internalId => {
const externalStream = pc._reverseStreams[internalId];
const internalStream = pc._streams[externalStream.id];
sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id);
});
return new RTCSessionDescription({
type: description.type,
sdp
});
}
['createOffer', 'createAnswer'].forEach(function (method) {
const nativeMethod = window.RTCPeerConnection.prototype[method];
const methodObj = {
[method]() {
const args = arguments;
const isLegacyCall = arguments.length && typeof arguments[0] === 'function';
if (isLegacyCall) {
return nativeMethod.apply(this, [description => {
const desc = replaceInternalStreamId(this, description);
args[0].apply(null, [desc]);
}, err => {
if (args[1]) {
args[1].apply(null, err);
}
}, arguments[2]]);
}
return nativeMethod.apply(this, arguments).then(description => replaceInternalStreamId(this, description));
}
};
window.RTCPeerConnection.prototype[method] = methodObj[method];
});
const origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
if (!arguments.length || !arguments[0].type) {
return origSetLocalDescription.apply(this, arguments);
}
arguments[0] = replaceExternalStreamId(this, arguments[0]);
return origSetLocalDescription.apply(this, arguments);
};
// TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
const origLocalDescription = Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype, 'localDescription');
Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', {
get() {
const description = origLocalDescription.get.apply(this);
if (description.type === '') {
return description;
}
return replaceInternalStreamId(this, description);
}
});
window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
if (this.signalingState === 'closed') {
throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
}
// We can not yet check for sender instanceof RTCRtpSender
// since we shim RTPSender. So we check if sender._pc is set.
if (!sender._pc) {
throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' + 'does not implement interface RTCRtpSender.', 'TypeError');
}
const isLocal = sender._pc === this;
if (!isLocal) {
throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError');
}
// Search for the native stream the senders track belongs to.
this._streams = this._streams || {};
let stream;
Object.keys(this._streams).forEach(streamid => {
const hasTrack = this._streams[streamid].getTracks().find(track => sender.track === track);
if (hasTrack) {
stream = this._streams[streamid];
}
});
if (stream) {
if (stream.getTracks().length === 1) {
// if this is the last track of the stream, remove the stream. This
// takes care of any shimmed _senders.
this.removeStream(this._reverseStreams[stream.id]);
} else {
// relying on the same odd chrome behaviour as above.
stream.removeTrack(sender.track);
}
this.dispatchEvent(new Event('negotiationneeded'));
}
};
}
function shimPeerConnection$1(window, browserDetails) {
if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
// very basic support for old versions.
window.RTCPeerConnection = window.webkitRTCPeerConnection;
}
if (!window.RTCPeerConnection) {
return;
}
// shim implicit creation of RTCSessionDescription/RTCIceCandidate
if (browserDetails.version < 53) {
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
const nativeMethod = window.RTCPeerConnection.prototype[method];
const methodObj = {
[method]() {
arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
}
};
window.RTCPeerConnection.prototype[method] = methodObj[method];
});
}
}
// Attempt to fix ONN in plan-b mode.
function fixNegotiationNeeded(window, browserDetails) {
wrapPeerConnectionEvent(window, 'negotiationneeded', e => {
const pc = e.target;
if (browserDetails.version < 72 || pc.getConfiguration && pc.getConfiguration().sdpSemantics === 'plan-b') {
if (pc.signalingState !== 'stable') {
return;
}
}
return e;
});
}
var chromeShim = /*#__PURE__*/Object.freeze({
__proto__: null,
fixNegotiationNeeded: fixNegotiationNeeded,
shimAddTrackRemoveTrack: shimAddTrackRemoveTrack,
shimAddTrackRemoveTrackWithNative: shimAddTrackRemoveTrackWithNative,
shimGetDisplayMedia: shimGetDisplayMedia$1,
shimGetSendersWithDtmf: shimGetSendersWithDtmf,
shimGetStats: shimGetStats,
shimGetUserMedia: shimGetUserMedia$2,
shimMediaStream: shimMediaStream,
shimOnTrack: shimOnTrack$1,
shimPeerConnection: shimPeerConnection$1,
shimSenderReceiverGetStats: shimSenderReceiverGetStats
});
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimGetUserMedia$1(window, browserDetails) {
const navigator = window && window.navigator;
const MediaStreamTrack = window && window.MediaStreamTrack;
navigator.getUserMedia = function (constraints, onSuccess, onError) {
// Replace Firefox 44+'s deprecation warning with unprefixed version.
deprecated('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia');
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
};
if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
const remap = function (obj, a, b) {
if (a in obj && !(b in obj)) {
obj[b] = obj[a];
delete obj[a];
}
};
const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function (c) {
if (typeof c === 'object' && typeof c.audio === 'object') {
c = JSON.parse(JSON.stringify(c));
remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
}
return nativeGetUserMedia(c);
};
if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
const nativeGetSettings = MediaStreamTrack.prototype.getSettings;
MediaStreamTrack.prototype.getSettings = function () {
const obj = nativeGetSettings.apply(this, arguments);
remap(obj, 'mozAutoGainControl', 'autoGainControl');
remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
return obj;
};
}
if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
const nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
MediaStreamTrack.prototype.applyConstraints = function (c) {
if (this.kind === 'audio' && typeof c === 'object') {
c = JSON.parse(JSON.stringify(c));
remap(c, 'autoGainControl', 'mozAutoGainControl');
remap(c, 'noiseSuppression', 'mozNoiseSuppression');
}
return nativeApplyConstraints.apply(this, [c]);
};
}
}
}
/*
* Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimGetDisplayMedia(window, preferredMediaSource) {
if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
return;
}
if (!window.navigator.mediaDevices) {
return;
}
window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
if (!(constraints && constraints.video)) {
const err = new DOMException('getDisplayMedia without video ' + 'constraints is undefined');
err.name = 'NotFoundError';
// from https://heycam.github.io/webidl/#idl-DOMException-error-names
err.code = 8;
return Promise.reject(err);
}
if (constraints.video === true) {
constraints.video = {
mediaSource: preferredMediaSource
};
} else {
constraints.video.mediaSource = preferredMediaSource;
}
return window.navigator.mediaDevices.getUserMedia(constraints);
};
}
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimOnTrack(window) {
if (typeof window === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
get() {
return {
receiver: this.receiver
};
}
});
}
}
function shimPeerConnection(window, browserDetails) {
if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
return; // probably media.peerconnection.enabled=false in about:config
}
if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
// very basic support for old versions.
window.RTCPeerConnection = window.mozRTCPeerConnection;
}
if (browserDetails.version < 53) {
// shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
const nativeMethod = window.RTCPeerConnection.prototype[method];
const methodObj = {
[method]() {
arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
}
};
window.RTCPeerConnection.prototype[method] = methodObj[method];
});
}
const modernStatsTypes = {
inboundrtp: 'inbound-rtp',
outboundrtp: 'outbound-rtp',
candidatepair: 'candidate-pair',
localcandidate: 'local-candidate',
remotecandidate: 'remote-candidate'
};
const nativeGetStats = window.RTCPeerConnection.prototype.getStats;
window.RTCPeerConnection.prototype.getStats = function getStats() {
const [selector, onSucc, onErr] = arguments;
return nativeGetStats.apply(this, [selector || null]).then(stats => {
if (browserDetails.version < 53 && !onSucc) {
// Shim only promise getStats with spec-hyphens in type names
// Leave callback version alone; misc old uses of forEach before Map
try {
stats.forEach(stat => {
stat.type = modernStatsTypes[stat.type] || stat.type;
});
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
// Avoid TypeError: "type" is read-only, in old versions. 34-43ish
stats.forEach((stat, i) => {
stats.set(i, Object.assign({}, stat, {
type: modernStatsTypes[stat.type] || stat.type
}));
});
}
}
return stats;
}).then(onSucc, onErr);
};
}
function shimSenderGetStats(window) {
if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
return;
}
if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
return;
}
const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
if (origGetSenders) {
window.RTCPeerConnection.prototype.getSenders = function getSenders() {
const senders = origGetSenders.apply(this, []);
senders.forEach(sender => sender._pc = this);
return senders;
};
}
const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
if (origAddTrack) {
window.RTCPeerConnection.prototype.addTrack = function addTrack() {
const sender = origAddTrack.apply(this, arguments);
sender._pc = this;
return sender;
};
}
window.RTCRtpSender.prototype.getStats = function getStats() {
return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map());
};
}
function shimReceiverGetStats(window) {
if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
return;
}
if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
return;
}
const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
if (origGetReceivers) {
window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
const receivers = origGetReceivers.apply(this, []);
receivers.forEach(receiver => receiver._pc = this);
return receivers;
};
}
wrapPeerConnectionEvent(window, 'track', e => {
e.receiver._pc = e.srcElement;
return e;
});
window.RTCRtpReceiver.prototype.getStats = function getStats() {
return this._pc.getStats(this.track);
};
}
function shimRemoveStream(window) {
if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) {
return;
}
window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
deprecated('removeStream', 'removeTrack');
this.getSenders().forEach(sender => {
if (sender.track && stream.getTracks().includes(sender.track)) {
this.removeTrack(sender);
}
});
};
}
function shimRTCDataChannel(window) {
// rename DataChannel to RTCDataChannel (native fix in FF60):
// https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
if (window.DataChannel && !window.RTCDataChannel) {
window.RTCDataChannel = window.DataChannel;
}
}
function shimAddTransceiver(window) {
// https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
// Firefox ignores the init sendEncodings options passed to addTransceiver
// https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
if (!(typeof window === 'object' && window.RTCPeerConnection)) {
return;
}
const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
if (origAddTransceiver) {
window.RTCPeerConnection.prototype.addTransceiver = function addTransceiver() {
this.setParametersPromises = [];
// WebIDL input coercion and validation
let sendEncodings = arguments[1] && arguments[1].sendEncodings;
if (sendEncodings === undefined) {
sendEncodings = [];
}
sendEncodings = [...sendEncodings];
const shouldPerformCheck = sendEncodings.length > 0;
if (shouldPerformCheck) {
// If sendEncodings params are provided, validate grammar
sendEncodings.forEach(encodingParam => {
if ('rid' in encodingParam) {
const ridRegex = /^[a-z0-9]{0,16}$/i;
if (!ridRegex.test(encodingParam.rid)) {
throw new TypeError('Invalid RID value provided.');
}
}
if ('scaleResolutionDownBy' in encodingParam) {
if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
throw new RangeError('scale_resolution_down_by must be >= 1.0');
}
}
if ('maxFramerate' in encodingParam) {
if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
throw new RangeError('max_framerate must be >= 0.0');
}
}
});
}
const transceiver = origAddTransceiver.apply(this, arguments);
if (shouldPerformCheck) {
// Check if the init options were applied. If not we do this in an
// asynchronous way and save the promise reference in a global object.
// This is an ugly hack, but at the same time is way more robust than
// checking the sender parameters before and after the createOffer
// Also note that after the createoffer we are not 100% sure that
// the params were asynchronously applied so we might miss the
// opportunity to recreate offer.
const {
sender
} = transceiver;
const params = sender.getParameters();
if (!('encodings' in params) ||
// Avoid being fooled by patched getParameters() below.
params.encodings.length === 1 && Object.keys(params.encodings[0]).length === 0) {
params.encodings = sendEncodings;
sender.sendEncodings = sendEncodings;
this.setParametersPromises.push(sender.setParameters(params).then(() => {
delete sender.sendEncodings;
}).catch(() => {
delete sender.sendEncodings;
}));
}
}
return transceiver;
};
}
}
function shimGetParameters(window) {
if (!(typeof window === 'object' && window.RTCRtpSender)) {
return;
}
const origGetParameters = window.RTCRtpSender.prototype.getParameters;
if (origGetParameters) {
window.RTCRtpSender.prototype.getParameters = function getParameters() {
const params = origGetParameters.apply(this, arguments);
if (!('encodings' in params)) {
params.encodings = [].concat(this.sendEncodings || [{}]);
}
return params;
};
}
}
function shimCreateOffer(window) {
// https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
// Firefox ignores the init sendEncodings options passed to addTransceiver
// https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
if (!(typeof window === 'object' && window.RTCPeerConnection)) {
return;
}
const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
window.RTCPeerConnection.prototype.createOffer = function createOffer() {
if (this.setParametersPromises && this.setParametersPromises.length) {
return Promise.all(this.setParametersPromises).then(() => {
return origCreateOffer.apply(this, arguments);
}).finally(() => {
this.setParametersPromises = [];
});
}
return origCreateOffer.apply(this, arguments);
};
}
function shimCreateAnswer(window) {
// https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
// Firefox ignores the init sendEncodings options passed to addTransceiver
// https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
if (!(typeof window === 'object' && window.RTCPeerConnection)) {
return;
}
const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
if (this.setParametersPromises && this.setParametersPromises.length) {
return Promise.all(this.setParametersPromises).then(() => {
return origCreateAnswer.apply(this, arguments);
}).finally(() => {
this.setParametersPromises = [];
});
}
return origCreateAnswer.apply(this, arguments);
};
}
var firefoxShim = /*#__PURE__*/Object.freeze({
__proto__: null,
shimAddTransceiver: shimAddTransceiver,
shimCreateAnswer: shimCreateAnswer,
shimCreateOffer: shimCreateOffer,
shimGetDisplayMedia: shimGetDisplayMedia,
shimGetParameters: shimGetParameters,
shimGetUserMedia: shimGetUserMedia$1,
shimOnTrack: shimOnTrack,
shimPeerConnection: shimPeerConnection,
shimRTCDataChannel: shimRTCDataChannel,
shimReceiverGetStats: shimReceiverGetStats,
shimRemoveStream: shimRemoveStream,
shimSenderGetStats: shimSenderGetStats
});
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
function shimLocalStreamsAPI(window) {
if (typeof window !== 'object' || !window.RTCPeerConnection) {
return;
}
if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
if (!this._localStreams) {
this._localStreams = [];
}
return this._localStreams;
};
}
if (!('addStream' in window.RTCPeerConnection.prototype)) {
const _addTrack = window.RTCPeerConnection.prototype.addTrack;
window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
if (!this._localStreams) {
this._localStreams = [];
}
if (!this._localStreams.includes(stream)) {
this._localStreams.push(stream);
}
// Try to emulate Chrome's behaviour of adding in audio-video order.
// Safari orders by track id.
stream.getAudioTracks().forEach(track => _addTrack.call(this, track, stream));
stream.getVideoTracks().forEach(track => _addTrack.call(this, track, stream));
};
window.RTCPeerConnection.prototype.addTrack = function addTrack(track, ...streams) {
if (streams) {
streams.forEach(stream => {
if (!this._localStreams) {
this._localStreams = [stream];
} else if (!this._localStreams.includes(stream)) {
this._localStreams.push(stream);
}
});
}
return _addTrack.apply(this, arguments);
};
}
if (!('removeStream' in window.RTCPeerConnection.prototype)) {
window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
if (!this._localStreams) {
this._localStreams = [];
}
const index = this._localStreams.indexOf(stream);
if (index === -1) {
return;
}
this._localStreams.splice(index, 1);
const tracks = stream.getTracks();
this.getSenders().forEach(sender => {
if (tracks.includes(sender.track)) {
this.removeTrack(sender);
}
});
};
}
}
function shimRemoteStreamsAPI(window) {
if (typeof window !== 'object' || !window.RTCPeerConnection) {
return;
}
if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
window.RTCPeerConnection.prototype.getRemoteStreams = function getRemoteStreams() {
return this._remoteStreams ? this._remoteStreams : [];
};
}
if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
get() {
return this._onaddstream;
},
set(f) {
if (this._onaddstream) {
this.removeEventListener('addstream', this._onaddstream);
this.removeEventListener('track', this._onaddstreampoly);
}
this.addEventListener('addstream', this._onaddstream = f);
this.addEventListener('track', this._onaddstreampoly = e => {
e.streams.forEach(stream => {
if (!this._remoteStreams) {
this._remoteStreams = [];
}
if (this._remoteStreams.includes(stream)) {
return;
}
this._remoteStreams.push(stream);
const event = new Event('addstream');
event.stream = stream;
this.dispatchEvent(event);
});
});
}
});
const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
const pc = this;
if (!this._onaddstreampoly) {
this.addEventListener('track', this._onaddstreampoly = function (e) {
e.streams.forEach(stream => {
if (!pc._remoteStreams) {
pc._remoteStreams = [];
}
if (pc._remoteStreams.indexOf(stream) >= 0) {
return;
}
pc._remoteStreams.push(stream);
const event = new Event('addstream');
event.stream = stream;
pc.dispatchEvent(event);
});
});
}
return origSetRemoteDescription.apply(pc, arguments);
};
}
}
function shimCallbacksAPI(window) {
if (typeof window !== 'object' || !window.RTCPeerConnection) {
return;
}
const prototype = window.RTCPeerConnection.prototype;
const origCreateOffer = prototype.createOffer;
const origCreateAnswer = prototype.createAnswer;
const setLocalDescription = prototype.setLocalDescription;
const setRemoteDescription = prototype.setRemoteDescription;
const addIceCandidate = prototype.addIceCandidate;
prototype.createOffer = function createOffer(successCallback, failureCallback) {
const options = arguments.length >= 2 ? arguments[2] : arguments[0];
const promise = origCreateOffer.apply(this, [options]);
if (!failureCallback) {
return promise;
}
promise.then(successCallback, failureCallback);
return Promise.resolve();
};
prototype.createAnswer = function createAnswer(successCallback, failureCallback) {
const options = arguments.length >= 2 ? arguments[2] : arguments[0];
const promise = origCreateAnswer.apply(this, [options]);
if (!failureCallback) {
return promise;
}
promise.then(successCallback, failureCallback);
return Promise.resolve();
};
let withCallback = function (description, successCallback, failureCallback) {
const promise = setLocalDescription.apply(this, [description]);
if (!failureCallback) {
return promise;
}
promise.then(successCallback, failureCallback);
return Promise.resolve();
};
prototype.setLocalDescription = withCallback;
withCallback = function (description, successCallback, failureCallback) {
const promise = setRemoteDescription.apply(this, [description]);
if (!failureCallback) {
return promise;
}
promise.then(successCallback, failureCallback);
return Promise.resolve();
};
prototype.setRemoteDescription = withCallback;
withCallback = function (candidate, successCallback, failureCallback) {
const promise = addIceCandidate.apply(this, [candidate]);
if (!failureCallback) {
return promise;
}
promise.then(successCallback, failureCallback);
return Promise.resolve();
};
prototype.addIceCandidate = withCallback;
}
function shimGetUserMedia(window) {
const navigator = window && window.navigator;
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// shim not needed in Safari 12.1
const mediaDevices = navigator.mediaDevices;
const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
navigator.mediaDevices.getUserMedia = constraints => {
return _getUserMedia(shimConstraints(constraints));
};
}
if (!navigator.getUserMedia && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
navigator.mediaDevices.getUserMedia(constraints).then(cb, errcb);
}.bind(navigator);
}
}
function shimConstraints(constraints) {
if (constraints && constraints.video !== undefined) {
return Object.assign({}, constraints, {
video: compactObject(constraints.video)
});
}
return constraints;
}
function shimRTCIceServerUrls(window) {
if (!window.RTCPeerConnection) {
return;
}
// migrate from non-spec RTCIceServer.url to RTCIceServer.urls
const OrigPeerConnection = window.RTCPeerConnection;
window.RTCPeerConnection = function RTCPeerConnection(pcConfig, pcConstraints) {
if (pcConfig && pcConfig.iceServers) {
const newIceServers = [];
for (let i = 0; i < pcConfig.iceServers.length; i++) {
let server = pcConfig.iceServers[i];
if (server.urls === undefined && server.url) {
deprecated('RTCIceServer.url', 'RTCIceServer.urls');
server = JSON.parse(JSON.stringify(server));
server.urls = server.url;
delete server.url;
newIceServers.push(server);
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
return new OrigPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if ('generateCertificate' in OrigPeerConnection) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get() {
return OrigPeerConnection.generateCertificate;
}
});
}
}
function shimTrackEventTransceiver(window) {
// Add event.transceiver member over deprecated event.receiver
if (typeof window === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
get() {
return {
receiver: this.receiver
};
}
});
}
}
function shimCreateOfferLegacy(window) {
const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
window.RTCPeerConnection.prototype.createOffer = function createOffer(offerOptions) {
if (offerOptions) {
if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
// support bit values
offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
}
const audioTransceiver = this.getTransceivers().find(transceiver => transceiver.receiver.track.kind === 'audio');
if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
if (audioTransceiver.direction === 'sendrecv') {
if (audioTransceiver.setDirection) {
audioTransceiver.setDirection('sendonly');
} else {
audioTransceiver.direction = 'sendonly';
}
} else if (audioTransceiver.direction === 'recvonly') {
if (audioTransceiver.setDirection) {
audioTransceiver.setDirection('inactive');
} else {
audioTransceiver.direction = 'inactive';
}
}
} else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) {
this.addTransceiver('audio', {
direction: 'recvonly'
});
}
if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
// support bit values
offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
}
const videoTransceiver = this.getTransceivers().find(transceiver => transceiver.receiver.track.kind === 'video');
if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
if (videoTransceiver.direction === 'sendrecv') {
if (videoTransceiver.setDirection) {
videoTransceiver.setDirection('sendonly');
} else {
videoTransceiver.direction = 'sendonly';
}
} else if (videoTransceiver.direction === 'recvonly') {
if (videoTransceiver.setDirection) {
videoTransceiver.setDirection('inactive');
} else {
videoTransceiver.direction = 'inactive';
}
}
} else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) {
this.addTransceiver('video', {
direction: 'recvonly'
});
}
}
return origCreateOffer.apply(this, arguments);
};
}
function shimAudioContext(window) {
if (typeof window !== 'object' || window.AudioContext) {
return;
}
window.AudioContext = window.webkitAudioContext;
}
var safariShim = /*#__PURE__*/Object.freeze({
__proto__: null,
shimAudioContext: shimAudioContext,
shimCallbacksAPI: shimCallbacksAPI,
shimConstraints: shimConstraints,
shimCreateOfferLegacy: shimCreateOfferLegacy,
shimGetUserMedia: shimGetUserMedia,
shimLocalStreamsAPI: shimLocalStreamsAPI,
shimRTCIceServerUrls: shimRTCIceServerUrls,
shimRemoteStreamsAPI: shimRemoteStreamsAPI,
shimTrackEventTransceiver: shimTrackEventTransceiver
});
var sdp$1 = {exports: {}};
/* eslint-env node */
(function (module) {
// SDP helpers.
const SDPUtils = {};
// Generate an alphanumeric identifier for cname or mids.
// TODO: use UUIDs instead? https://gist.github.com/jed/982883
SDPUtils.generateIdentifier = function () {
return Math.random().toString(36).substring(2, 12);
};
// The RTCP CNAME used by all peerconnections from the same JS.
SDPUtils.localCName = SDPUtils.generateIdentifier();
// Splits SDP into lines, dealing with both CRLF and LF.
SDPUtils.splitLines = function (blob) {
return blob.trim().split('\n').map(line => line.trim());
};
// Splits SDP into sessionpart and mediasections. Ensures CRLF.
SDPUtils.splitSections = function (blob) {
const parts = blob.split('\nm=');
return parts.map((part, index) => (index > 0 ? 'm=' + part : part).trim() + '\r\n');
};
// Returns the session description.
SDPUtils.getDescription = function (blob) {
const sections = SDPUtils.splitSections(blob);
return sections && sections[0];
};
// Returns the individual media sections.
SDPUtils.getMediaSections = function (blob) {
const sections = SDPUtils.splitSections(blob);
sections.shift();
return sections;
};
// Returns lines that start with a certain prefix.
SDPUtils.matchPrefix = function (blob, prefix) {
return SDPUtils.splitLines(blob).filter(line => line.indexOf(prefix) === 0);
};
// Parses an ICE candidate line. Sample input:
// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
// rport 55996"
// Input can be prefixed with a=.
SDPUtils.parseCandidate = function (line) {
let parts;
// Parse both variants.
if (line.indexOf('a=candidate:') === 0) {
parts = line.substring(12).split(' ');
} else {
parts = line.substring(10).split(' ');
}
const candidate = {
foundation: parts[0],
component: {
1: 'rtp',
2: 'rtcp'
}[parts[1]] || parts[1],
protocol: parts[2].toLowerCase(),
priority: parseInt(parts[3], 10),
ip: parts[4],
address: parts[4],
// address is an alias for ip.
port: parseInt(parts[5], 10),
// skip parts[6] == 'typ'
type: parts[7]
};
for (let i = 8; i < parts.length; i += 2) {
switch (parts[i]) {
case 'raddr':
candidate.relatedAddress = parts[i + 1];
break;
case 'rport':
candidate.relatedPort = parseInt(parts[i + 1], 10);
break;
case 'tcptype':
candidate.tcpType = parts[i + 1];
break;
case 'ufrag':
candidate.ufrag = parts[i + 1]; // for backward compatibility.
candidate.usernameFragment = parts[i + 1];
break;
default:
// extension handling, in particular ufrag. Don't overwrite.
if (candidate[parts[i]] === undefined) {
candidate[parts[i]] = parts[i + 1];
}
break;
}
}
return candidate;
};
// Translates a candidate object into SDP candidate attribute.
// This does not include the a= prefix!
SDPUtils.writeCandidate = function (candidate) {
const sdp = [];
sdp.push(candidate.foundation);
const component = candidate.component;
if (component === 'rtp') {
sdp.push(1);
} else if (component === 'rtcp') {
sdp.push(2);
} else {
sdp.push(component);
}
sdp.push(candidate.protocol.toUpperCase());
sdp.push(candidate.priority);
sdp.push(candidate.address || candidate.ip);
sdp.push(candidate.port);
const type = candidate.type;
sdp.push('typ');
sdp.push(type);
if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) {
sdp.push('raddr');
sdp.push(candidate.relatedAddress);
sdp.push('rport');
sdp.push(candidate.relatedPort);
}
if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
sdp.push('tcptype');
sdp.push(candidate.tcpType);
}
if (candidate.usernameFragment || candidate.ufrag) {
sdp.push('ufrag');
sdp.push(candidate.usernameFragment || candidate.ufrag);
}
return 'candidate:' + sdp.join(' ');
};
// Parses an ice-options line, returns an array of option tags.
// Sample input:
// a=ice-options:foo bar
SDPUtils.parseIceOptions = function (line) {
return line.substring(14).split(' ');
};
// Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:
// a=rtpmap:111 opus/48000/2
SDPUtils.parseRtpMap = function (line) {
let parts = line.substring(9).split(' ');
const parsed = {
payloadType: parseInt(parts.shift(), 10) // was: id
};
parts = parts[0].split('/');
parsed.name = parts[0];
parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
// legacy alias, got renamed back to channels in ORTC.
parsed.numChannels = parsed.channels;
return parsed;
};
// Generates a rtpmap line from RTCRtpCodecCapability or
// RTCRtpCodecParameters.
SDPUtils.writeRtpMap = function (codec) {
let pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
const channels = codec.channels || codec.numChannels || 1;
return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n';
};
// Parses a extmap line (headerextension from RFC 5285). Sample input:
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
// a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
SDPUtils.parseExtmap = function (line) {
const parts = line.substring(9).split(' ');
return {
id: parseInt(parts[0], 10),
direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
uri: parts[1],
attributes: parts.slice(2).join(' ')
};
};
// Generates an extmap line from RTCRtpHeaderExtensionParameters or
// RTCRtpHeaderExtension.
SDPUtils.writeExtmap = function (headerExtension) {
return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + (headerExtension.attributes ? ' ' + headerExtension.attributes : '') + '\r\n';
};
// Parses a fmtp line, returns dictionary. Sample input:
// a=fmtp:96 vbr=on;cng=on
// Also deals with vbr=on; cng=on
SDPUtils.parseFmtp = function (line) {
const parsed = {};
let kv;
const parts = line.substring(line.indexOf(' ') + 1).split(';');
for (let j = 0; j < parts.length; j++) {
kv = parts[j].trim().split('=');
parsed[kv[0].trim()] = kv[1];
}
return parsed;
};
// Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeFmtp = function (codec) {
let line = '';
let pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.parameters && Object.keys(codec.parameters).length) {
const params = [];
Object.keys(codec.parameters).forEach(param => {
if (codec.parameters[param] !== undefined) {
params.push(param + '=' + codec.parameters[param]);
} else {
params.push(param);
}
});
line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
}
return line;
};
// Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
// a=rtcp-fb:98 nack rpsi
SDPUtils.parseRtcpFb = function (line) {
const parts = line.substring(line.indexOf(' ') + 1).split(' ');
return {
type: parts.shift(),
parameter: parts.join(' ')
};
};
// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeRtcpFb = function (codec) {
let lines = '';
let pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
// FIXME: special handling for trr-int?
codec.rtcpFeedback.forEach(fb => {
lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n';
});
}
return lines;
};
// Parses a RFC 5576 ssrc media attribute. Sample input:
// a=ssrc:3735928559 cname:something
SDPUtils.parseSsrcMedia = function (line) {
const sp = line.indexOf(' ');
const parts = {
ssrc: parseInt(line.substring(7, sp), 10)
};
const colon = line.indexOf(':', sp);
if (colon > -1) {
parts.attribute = line.substring(sp + 1, colon);
parts.value = line.substring(colon + 1);
} else {
parts.attribute = line.substring(sp + 1);
}
return parts;
};
// Parse a ssrc-group line (see RFC 5576). Sample input:
// a=ssrc-group:semantics 12 34
SDPUtils.parseSsrcGroup = function (line) {
const parts = line.substring(13).split(' ');
return {
semantics: parts.shift(),
ssrcs: parts.map(ssrc => parseInt(ssrc, 10))
};
};
// Extracts the MID (RFC 5888) from a media section.
// Returns the MID or undefined if no mid line was found.
SDPUtils.getMid = function (mediaSection) {
const mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
if (mid) {
return mid.substring(6);
}
};
// Parses a fingerprint line for DTLS-SRTP.
SDPUtils.parseFingerprint = function (line) {
const parts = line.substring(14).split(' ');
return {
algorithm: parts[0].toLowerCase(),
// algorithm is case-sensitive in Edge.
value: parts[1].toUpperCase() // the definition is upper-case in RFC 4572.
};
};
// Extracts DTLS parameters from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the fingerprint line as input. See also getIceParameters.
SDPUtils.getDtlsParameters = function (mediaSection, sessionpart) {
const lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:');
// Note: a=setup line is ignored since we use the 'auto' role in Edge.
return {
role: 'auto',
fingerprints: lines.map(SDPUtils.parseFingerprint)
};
};
// Serializes DTLS parameters to SDP.
SDPUtils.writeDtlsParameters = function (params, setupType) {
let sdp = 'a=setup:' + setupType + '\r\n';
params.fingerprints.forEach(fp => {
sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
});
return sdp;
};
// Parses a=crypto lines into
// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
SDPUtils.parseCryptoLine = function (line) {
const parts = line.substring(9).split(' ');
return {
tag: parseInt(parts[0], 10),
cryptoSuite: parts[1],
keyParams: parts[2],
sessionParams: parts.slice(3)
};
};
SDPUtils.writeCryptoLine = function (parameters) {
return 'a=crypto:' + parameters.tag + ' ' + parameters.cryptoSuite + ' ' + (typeof parameters.keyParams === 'object' ? SDPUtils.writeCryptoKeyParams(parameters.keyParams) : parameters.keyParams) + (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') + '\r\n';
};
// Parses the crypto key parameters into
// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
SDPUtils.parseCryptoKeyParams = function (keyParams) {
if (keyParams.indexOf('inline:') !== 0) {
return null;
}
const parts = keyParams.substring(7).split('|');
return {
keyMethod: 'inline',
keySalt: parts[0],
lifeTime: parts[1],
mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
mkiLength: parts[2] ? parts[2].split(':')[1] : undefined
};
};
SDPUtils.writeCryptoKeyParams = function (keyParams) {
return keyParams.keyMethod + ':' + keyParams.keySalt + (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') + (keyParams.mkiValue && keyParams.mkiLength ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength : '');
};
// Extracts all SDES parameters.
SDPUtils.getCryptoParameters = function (mediaSection, sessionpart) {
const lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=crypto:');
return lines.map(SDPUtils.parseCryptoLine);
};
// Parses ICE information from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the ice-ufrag and ice-pwd lines as input.
SDPUtils.getIceParameters = function (mediaSection, sessionpart) {
const ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-ufrag:')[0];
const pwd = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-pwd:')[0];
if (!(ufrag && pwd)) {
return null;
}
return {
usernameFragment: ufrag.substring(12),
password: pwd.substring(10)
};
};
// Serializes ICE parameters to SDP.
SDPUtils.writeIceParameters = function (params) {
let sdp = 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n';
if (params.iceLite) {
sdp += 'a=ice-lite\r\n';
}
return sdp;
};
// Parses the SDP media section and returns RTCRtpParameters.
SDPUtils.parseRtpParameters = function (mediaSection) {
const description = {
codecs: [],
headerExtensions: [],
fecMechanisms: [],
rtcp: []
};
const lines = SDPUtils.splitLines(mediaSection);
const mline = lines[0].split(' ');
description.profile = mline[2];
for (let i = 3; i < mline.length; i++) {
// find all codecs from mline[3..]
const pt = mline[i];
const rtpmapline = SDPUtils.matchPrefix(mediaSection, 'a=rtpmap:' + pt + ' ')[0];
if (rtpmapline) {
const codec = SDPUtils.parseRtpMap(rtpmapline);
const fmtps = SDPUtils.matchPrefix(mediaSection, 'a=fmtp:' + pt + ' ');
// Only the first a=fmtp:<pt> is considered.
codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
codec.rtcpFeedback = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:' + pt + ' ').map(SDPUtils.parseRtcpFb);
description.codecs.push(codec);
// parse FEC mechanisms from rtpmap lines.
switch (codec.name.toUpperCase()) {
case 'RED':
case 'ULPFEC':
description.fecMechanisms.push(codec.name.toUpperCase());
break;
}
}
}
SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(line => {
description.headerExtensions.push(SDPUtils.parseExtmap(line));
});
const wildcardRtcpFb = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:* ').map(SDPUtils.parseRtcpFb);
description.codecs.forEach(codec => {
wildcardRtcpFb.forEach(fb => {
const duplicate = codec.rtcpFeedback.find(existingFeedback => {
return existingFeedback.type === fb.type && existingFeedback.parameter === fb.parameter;
});
if (!duplicate) {
codec.rtcpFeedback.push(fb);
}
});
});
// FIXME: parse rtcp.
return description;
};
// Generates parts of the SDP media section describing the capabilities /
// parameters.
SDPUtils.writeRtpDescription = function (kind, caps) {
let sdp = '';
// Build the mline.
sdp += 'm=' + kind + ' ';
sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
sdp += ' ' + (caps.profile || 'UDP/TLS/RTP/SAVPF') + ' ';
sdp += caps.codecs.map(codec => {
if (codec.preferredPayloadType !== undefined) {
return codec.preferredPayloadType;
}
return codec.payloadType;
}).join(' ') + '\r\n';
sdp += 'c=IN IP4 0.0.0.0\r\n';
sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
// Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
caps.codecs.forEach(codec => {
sdp += SDPUtils.writeRtpMap(codec);
sdp += SDPUtils.writeFmtp(codec);
sdp += SDPUtils.writeRtcpFb(codec);
});
let maxptime = 0;
caps.codecs.forEach(codec => {
if (codec.maxptime > maxptime) {
maxptime = codec.maxptime;
}
});
if (maxptime > 0) {
sdp += 'a=maxptime:' + maxptime + '\r\n';
}
if (caps.headerExtensions) {
caps.headerExtensions.forEach(extension => {
sdp += SDPUtils.writeExtmap(extension);
});
}
// FIXME: write fecMechanisms.
return sdp;
};
// Parses the SDP media section and returns an array of
// RTCRtpEncodingParameters.
SDPUtils.parseRtpEncodingParameters = function (mediaSection) {
const encodingParameters = [];
const description = SDPUtils.parseRtpParameters(mediaSection);
const hasRed = description.fecMechanisms.indexOf('RED') !== -1;
const hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
// filter a=ssrc:... cname:, ignore PlanB-msid
const ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(line => SDPUtils.parseSsrcMedia(line)).filter(parts => parts.attribute === 'cname');
const primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
let secondarySsrc;
const flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID').map(line => {
const parts = line.substring(17).split(' ');
return parts.map(part => parseInt(part, 10));
});
if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
secondarySsrc = flows[0][1];
}
description.codecs.forEach(codec => {
if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
let encParam = {
ssrc: primarySsrc,
codecPayloadType: parseInt(codec.parameters.apt, 10)
};
if (primarySsrc && secondarySsrc) {
encParam.rtx = {
ssrc: secondarySsrc
};
}
encodingParameters.push(encParam);
if (hasRed) {
encParam = JSON.parse(JSON.stringify(encParam));
encParam.fec = {
ssrc: primarySsrc,
mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
};
encodingParameters.push(encParam);
}
}
});
if (encodingParameters.length === 0 && primarySsrc) {
encodingParameters.push({
ssrc: primarySsrc
});
}
// we support both b=AS and b=TIAS but interpret AS as TIAS.
let bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
if (bandwidth.length) {
if (bandwidth[0].indexOf('b=TIAS:') === 0) {
bandwidth = parseInt(bandwidth[0].substring(7), 10);
} else if (bandwidth[0].indexOf('b=AS:') === 0) {
// use formula from JSEP to convert b=AS to TIAS value.
bandwidth = parseInt(bandwidth[0].substring(5), 10) * 1000 * 0.95 - 50 * 40 * 8;
} else {
bandwidth = undefined;
}
encodingParameters.forEach(params => {
params.maxBitrate = bandwidth;
});
}
return encodingParameters;
};
// parses http://draft.ortc.org/#rtcrtcpparameters*
SDPUtils.parseRtcpParameters = function (mediaSection) {
const rtcpParameters = {};
// Gets the first SSRC. Note that with RTX there might be multiple
// SSRCs.
const remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(line => SDPUtils.parseSsrcMedia(line)).filter(obj => obj.attribute === 'cname')[0];
if (remoteSsrc) {
rtcpParameters.cname = remoteSsrc.value;
rtcpParameters.ssrc = remoteSsrc.ssrc;
}
// Edge uses the compound attribute instead of reducedSize
// compound is !reducedSize
const rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
rtcpParameters.reducedSize = rsize.length > 0;
rtcpParameters.compound = rsize.length === 0;
// parses the rtcp-mux attrіbute.
// Note that Edge does not support unmuxed RTCP.
const mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
rtcpParameters.mux = mux.length > 0;
return rtcpParameters;
};
SDPUtils.writeRtcpParameters = function (rtcpParameters) {
let sdp = '';
if (rtcpParameters.reducedSize) {
sdp += 'a=rtcp-rsize\r\n';
}
if (rtcpParameters.mux) {
sdp += 'a=rtcp-mux\r\n';
}
if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {
sdp += 'a=ssrc:' + rtcpParameters.ssrc + ' cname:' + rtcpParameters.cname + '\r\n';
}
return sdp;
};
// parses either a=msid: or a=ssrc:... msid lines and returns
// the id of the MediaStream and MediaStreamTrack.
SDPUtils.parseMsid = function (mediaSection) {
let parts;
const spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
if (spec.length === 1) {
parts = spec[0].substring(7).split(' ');
return {
stream: parts[0],
track: parts[1]
};
}
const planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(line => SDPUtils.parseSsrcMedia(line)).filter(msidParts => msidParts.attribute === 'msid');
if (planB.length > 0) {
parts = planB[0].value.split(' ');
return {
stream: parts[0],
track: parts[1]
};
}
};
// SCTP
// parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
// to draft-ietf-mmusic-sctp-sdp-05
SDPUtils.parseSctpDescription = function (mediaSection) {
const mline = SDPUtils.parseMLine(mediaSection);
const maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
let maxMessageSize;
if (maxSizeLine.length > 0) {
maxMessageSize = parseInt(maxSizeLine[0].substring(19), 10);
}
if (isNaN(maxMessageSize)) {
maxMessageSize = 65536;
}
const sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
if (sctpPort.length > 0) {
return {
port: parseInt(sctpPort[0].substring(12), 10),
protocol: mline.fmt,
maxMessageSize
};
}
const sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
if (sctpMapLines.length > 0) {
const parts = sctpMapLines[0].substring(10).split(' ');
return {
port: parseInt(parts[0], 10),
protocol: parts[1],
maxMessageSize
};
}
};
// SCTP
// outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
// support by now receiving in this format, unless we originally parsed
// as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
// protocol of DTLS/SCTP -- without UDP/ or TCP/)
SDPUtils.writeSctpDescription = function (media, sctp) {
let output = [];
if (media.protocol !== 'DTLS/SCTP') {
output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctp-port:' + sctp.port + '\r\n'];
} else {
output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'];
}
if (sctp.maxMessageSize !== undefined) {
output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
}
return output.join('');
};
// Generate a session ID for SDP.
// https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
// recommends using a cryptographically random +ve 64-bit value
// but right now this should be acceptable and within the right range
SDPUtils.generateSessionId = function () {
return Math.random().toString().substr(2, 22);
};
// Write boiler plate for start of SDP
// sessId argument is optional - if not supplied it will
// be generated randomly
// sessVersion is optional and defaults to 2
// sessUser is optional and defaults to 'thisisadapterortc'
SDPUtils.writeSessionBoilerplate = function (sessId, sessVer, sessUser) {
let sessionId;
const version = sessVer !== undefined ? sessVer : 2;
if (sessId) {
sessionId = sessId;
} else {
sessionId = SDPUtils.generateSessionId();
}
const user = sessUser || 'thisisadapterortc';
// FIXME: sess-id should be an NTP timestamp.
return 'v=0\r\n' + 'o=' + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n';
};
// Gets the direction from the mediaSection or the sessionpart.
SDPUtils.getDirection = function (mediaSection, sessionpart) {
// Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
const lines = SDPUtils.splitLines(mediaSection);
for (let i = 0; i < lines.length; i++) {
switch (lines[i]) {
case 'a=sendrecv':
case 'a=sendonly':
case 'a=recvonly':
case 'a=inactive':
return lines[i].substring(2);
// FIXME: What should happen here?
}
}
if (sessionpart) {
return SDPUtils.getDirection(sessionpart);
}
return 'sendrecv';
};
SDPUtils.getKind = function (mediaSection) {
const lines = SDPUtils.splitLines(mediaSection);
const mline = lines[0].split(' ');
return mline[0].substring(2);
};
SDPUtils.isRejected = function (mediaSection) {
return mediaSection.split(' ', 2)[1] === '0';
};
SDPUtils.parseMLine = function (mediaSection) {
const lines = SDPUtils.splitLines(mediaSection);
const parts = lines[0].substring(2).split(' ');
return {
kind: parts[0],
port: parseInt(parts[1], 10),
protocol: parts[2],
fmt: parts.slice(3).join(' ')
};
};
SDPUtils.parseOLine = function (mediaSection) {
const line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
const parts = line.substring(2).split(' ');
return {
username: parts[0],
sessionId: parts[1],
sessionVersion: parseInt(parts[2], 10),
netType: parts[3],
addressType: parts[4],
address: parts[5]
};
};
// a very naive interpretation of a valid SDP.
SDPUtils.isValidSDP = function (blob) {
if (typeof blob !== 'string' || blob.length === 0) {
return false;
}
const lines = SDPUtils.splitLines(blob);
for (let i = 0; i < lines.length; i++) {
if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
return false;
}
// TODO: check the modifier a bit more.
}
return true;
};
// Expose public methods.
{
module.exports = SDPUtils;
}
})(sdp$1);
var sdpExports = sdp$1.exports;
var SDPUtils = /*@__PURE__*/getDefaultExportFromCjs(sdpExports);
var sdp = /*#__PURE__*/_mergeNamespaces({
__proto__: null,
default: SDPUtils
}, [sdpExports]);
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
function shimRTCIceCandidate(window) {
// foundation is arbitrarily chosen as an indicator for full support for
// https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
if (!window.RTCIceCandidate || window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype) {
return;
}
const NativeRTCIceCandidate = window.RTCIceCandidate;
window.RTCIceCandidate = function RTCIceCandidate(args) {
// Remove the a= which shouldn't be part of the candidate string.
if (typeof args === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) {
args = JSON.parse(JSON.stringify(args));
args.candidate = args.candidate.substring(2);
}
if (args.candidate && args.candidate.length) {
// Augment the native candidate with the parsed fields.
const nativeCandidate = new NativeRTCIceCandidate(args);
const parsedCandidate = SDPUtils.parseCandidate(args.candidate);
for (const key in parsedCandidate) {
if (!(key in nativeCandidate)) {
Object.defineProperty(nativeCandidate, key, {
value: parsedCandidate[key]
});
}
}
// Override serializer to not serialize the extra attributes.
nativeCandidate.toJSON = function toJSON() {
return {
candidate: nativeCandidate.candidate,
sdpMid: nativeCandidate.sdpMid,
sdpMLineIndex: nativeCandidate.sdpMLineIndex,
usernameFragment: nativeCandidate.usernameFragment
};
};
return nativeCandidate;
}
return new NativeRTCIceCandidate(args);
};
window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
// Hook up the augmented candidate in onicecandidate and
// addEventListener('icecandidate', ...)
wrapPeerConnectionEvent(window, 'icecandidate', e => {
if (e.candidate) {
Object.defineProperty(e, 'candidate', {
value: new window.RTCIceCandidate(e.candidate),
writable: 'false'
});
}
return e;
});
}
function shimRTCIceCandidateRelayProtocol(window) {
if (!window.RTCIceCandidate || window.RTCIceCandidate && 'relayProtocol' in window.RTCIceCandidate.prototype) {
return;
}
// Hook up the augmented candidate in onicecandidate and
// addEventListener('icecandidate', ...)
wrapPeerConnectionEvent(window, 'icecandidate', e => {
if (e.candidate) {
const parsedCandidate = SDPUtils.parseCandidate(e.candidate.candidate);
if (parsedCandidate.type === 'relay') {
// This is a libwebrtc-specific mapping of local type preference
// to relayProtocol.
e.candidate.relayProtocol = {
0: 'tls',
1: 'tcp',
2: 'udp'
}[parsedCandidate.priority >> 24];
}
}
return e;
});
}
function shimMaxMessageSize(window, browserDetails) {
if (!window.RTCPeerConnection) {
return;
}
if (!('sctp' in window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
get() {
return typeof this._sctp === 'undefined' ? null : this._sctp;
}
});
}
const sctpInDescription = function (description) {
if (!description || !description.sdp) {
return false;
}
const sections = SDPUtils.splitSections(description.sdp);
sections.shift();
return sections.some(mediaSection => {
const mLine = SDPUtils.parseMLine(mediaSection);
return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1;
});
};
const getRemoteFirefoxVersion = function (description) {
// TODO: Is there a better solution for detecting Firefox?
const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
if (match === null || match.length < 2) {
return -1;
}
const version = parseInt(match[1], 10);
// Test for NaN (yes, this is ugly)
return version !== version ? -1 : version;
};
const getCanSendMaxMessageSize = function (remoteIsFirefox) {
// Every implementation we know can send at least 64 KiB.
// Note: Although Chrome is technically able to send up to 256 KiB, the
// data does not reach the other peer reliably.
// See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
let canSendMaxMessageSize = 65536;
if (browserDetails.browser === 'firefox') {
if (browserDetails.version < 57) {
if (remoteIsFirefox === -1) {
// FF < 57 will send in 16 KiB chunks using the deprecated PPID
// fragmentation.
canSendMaxMessageSize = 16384;
} else {
// However, other FF (and RAWRTC) can reassemble PPID-fragmented
// messages. Thus, supporting ~2 GiB when sending.
canSendMaxMessageSize = 2147483637;
}
} else if (browserDetails.version < 60) {
// Currently, all FF >= 57 will reset the remote maximum message size
// to the default value when a data channel is created at a later
// stage. :(
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536;
} else {
// FF >= 60 supports sending ~2 GiB
canSendMaxMessageSize = 2147483637;
}
}
return canSendMaxMessageSize;
};
const getMaxMessageSize = function (description, remoteIsFirefox) {
// Note: 65536 bytes is the default value from the SDP spec. Also,
// every implementation we know supports receiving 65536 bytes.
let maxMessageSize = 65536;
// FF 57 has a slightly incorrect default remote max message size, so
// we need to adjust it here to avoid a failure when sending.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
if (browserDetails.browser === 'firefox' && browserDetails.version === 57) {
maxMessageSize = 65535;
}
const match = SDPUtils.matchPrefix(description.sdp, 'a=max-message-size:');
if (match.length > 0) {
maxMessageSize = parseInt(match[0].substring(19), 10);
} else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) {
// If the maximum message size is not present in the remote SDP and
// both local and remote are Firefox, the remote peer can receive
// ~2 GiB.
maxMessageSize = 2147483637;
}
return maxMessageSize;
};
const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
this._sctp = null;
// Chrome decided to not expose .sctp in plan-b mode.
// As usual, adapter.js has to do an 'ugly worakaround'
// to cover up the mess.
if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
const {
sdpSemantics
} = this.getConfiguration();
if (sdpSemantics === 'plan-b') {
Object.defineProperty(this, 'sctp', {
get() {
return typeof this._sctp === 'undefined' ? null : this._sctp;
},
enumerable: true,
configurable: true
});
}
}
if (sctpInDescription(arguments[0])) {
// Check if the remote is FF.
const isFirefox = getRemoteFirefoxVersion(arguments[0]);
// Get the maximum message size the local peer is capable of sending
const canSendMMS = getCanSendMaxMessageSize(isFirefox);
// Get the maximum message size of the remote peer.
const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
// Determine final maximum message size
let maxMessageSize;
if (canSendMMS === 0 && remoteMMS === 0) {
maxMessageSize = Number.POSITIVE_INFINITY;
} else if (canSendMMS === 0 || remoteMMS === 0) {
maxMessageSize = Math.max(canSendMMS, remoteMMS);
} else {
maxMessageSize = Math.min(canSendMMS, remoteMMS);
}
// Create a dummy RTCSctpTransport object and the 'maxMessageSize'
// attribute.
const sctp = {};
Object.defineProperty(sctp, 'maxMessageSize', {
get() {
return maxMessageSize;
}
});
this._sctp = sctp;
}
return origSetRemoteDescription.apply(this, arguments);
};
}
function shimSendThrowTypeError(window) {
if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) {
return;
}
// Note: Although Firefox >= 57 has a native implementation, the maximum
// message size can be reset for all data channels at a later stage.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
function wrapDcSend(dc, pc) {
const origDataChannelSend = dc.send;
dc.send = function send() {
const data = arguments[0];
const length = data.length || data.size || data.byteLength;
if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) {
throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)');
}
return origDataChannelSend.apply(dc, arguments);
};
}
const origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel;
window.RTCPeerConnection.prototype.createDataChannel = function createDataChannel() {
const dataChannel = origCreateDataChannel.apply(this, arguments);
wrapDcSend(dataChannel, this);
return dataChannel;
};
wrapPeerConnectionEvent(window, 'datachannel', e => {
wrapDcSend(e.channel, e.target);
return e;
});
}
/* shims RTCConnectionState by pretending it is the same as iceConnectionState.
* See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
* for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
* since DTLS failures would be hidden. See
* https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
* for the Firefox tracking bug.
*/
function shimConnectionState(window) {
if (!window.RTCPeerConnection || 'connectionState' in window.RTCPeerConnection.prototype) {
return;
}
const proto = window.RTCPeerConnection.prototype;
Object.defineProperty(proto, 'connectionState', {
get() {
return {
completed: 'connected',
checking: 'connecting'
}[this.iceConnectionState] || this.iceConnectionState;
},
enumerable: true,
configurable: true
});
Object.defineProperty(proto, 'onconnectionstatechange', {
get() {
return this._onconnectionstatechange || null;
},
set(cb) {
if (this._onconnectionstatechange) {
this.removeEventListener('connectionstatechange', this._onconnectionstatechange);
delete this._onconnectionstatechange;
}
if (cb) {
this.addEventListener('connectionstatechange', this._onconnectionstatechange = cb);
}
},
enumerable: true,
configurable: true
});
['setLocalDescription', 'setRemoteDescription'].forEach(method => {
const origMethod = proto[method];
proto[method] = function () {
if (!this._connectionstatechangepoly) {
this._connectionstatechangepoly = e => {
const pc = e.target;
if (pc._lastConnectionState !== pc.connectionState) {
pc._lastConnectionState = pc.connectionState;
const newEvent = new Event('connectionstatechange', e);
pc.dispatchEvent(newEvent);
}
return e;
};
this.addEventListener('iceconnectionstatechange', this._connectionstatechangepoly);
}
return origMethod.apply(this, arguments);
};
});
}
function removeExtmapAllowMixed(window, browserDetails) {
/* remove a=extmap-allow-mixed for webrtc.org < M71 */
if (!window.RTCPeerConnection) {
return;
}
if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
return;
}
if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
return;
}
const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription(desc) {
if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
const sdp = desc.sdp.split('\n').filter(line => {
return line.trim() !== 'a=extmap-allow-mixed';
}).join('\n');
// Safari enforces read-only-ness of RTCSessionDescription fields.
if (window.RTCSessionDescription && desc instanceof window.RTCSessionDescription) {
arguments[0] = new window.RTCSessionDescription({
type: desc.type,
sdp
});
} else {
desc.sdp = sdp;
}
}
return nativeSRD.apply(this, arguments);
};
}
function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
// Support for addIceCandidate(null or undefined)
// as well as addIceCandidate({candidate: "", ...})
// https://bugs.chromium.org/p/chromium/issues/detail?id=978582
// Note: must be called before other polyfills which change the signature.
if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
return;
}
const nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
return;
}
window.RTCPeerConnection.prototype.addIceCandidate = function addIceCandidate() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
// Firefox 68+ emits and processes {candidate: "", ...}, ignore
// in older versions.
// Native support for ignoring exists for Chrome M77+.
// Safari ignores as well, exact version unknown but works in the same
// version that also ignores addIceCandidate(null).
if ((browserDetails.browser === 'chrome' && browserDetails.version < 78 || browserDetails.browser === 'firefox' && browserDetails.version < 68 || browserDetails.browser === 'safari') && arguments[0] && arguments[0].candidate === '') {
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
}
// Note: Make sure to call this ahead of APIs that modify
// setLocalDescription.length
function shimParameterlessSetLocalDescription(window, browserDetails) {
if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
return;
}
const nativeSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
if (!nativeSetLocalDescription || nativeSetLocalDescription.length === 0) {
return;
}
window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
let desc = arguments[0] || {};
if (typeof desc !== 'object' || desc.type && desc.sdp) {
return nativeSetLocalDescription.apply(this, arguments);
}
// The remaining steps should technically happen when SLD comes off the
// RTCPeerConnection's operations chain (not ahead of going on it), but
// this is too difficult to shim. Instead, this shim only covers the
// common case where the operations chain is empty. This is imperfect, but
// should cover many cases. Rationale: Even if we can't reduce the glare
// window to zero on imperfect implementations, there's value in tapping
// into the perfect negotiation pattern that several browsers support.
desc = {
type: desc.type,
sdp: desc.sdp
};
if (!desc.type) {
switch (this.signalingState) {
case 'stable':
case 'have-local-offer':
case 'have-remote-pranswer':
desc.type = 'offer';
break;
default:
desc.type = 'answer';
break;
}
}
if (desc.sdp || desc.type !== 'offer' && desc.type !== 'answer') {
return nativeSetLocalDescription.apply(this, [desc]);
}
const func = desc.type === 'offer' ? this.createOffer : this.createAnswer;
return func.apply(this).then(d => nativeSetLocalDescription.apply(this, [d]));
};
}
var commonShim = /*#__PURE__*/Object.freeze({
__proto__: null,
removeExtmapAllowMixed: removeExtmapAllowMixed,
shimAddIceCandidateNullOrEmpty: shimAddIceCandidateNullOrEmpty,
shimConnectionState: shimConnectionState,
shimMaxMessageSize: shimMaxMessageSize,
shimParameterlessSetLocalDescription: shimParameterlessSetLocalDescription,
shimRTCIceCandidate: shimRTCIceCandidate,
shimRTCIceCandidateRelayProtocol: shimRTCIceCandidateRelayProtocol,
shimSendThrowTypeError: shimSendThrowTypeError
});
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
// Shimming starts here.
function adapterFactory({
window
} = {}, options = {
shimChrome: true,
shimFirefox: true,
shimSafari: true
}) {
// Utils.
const logging = log;
const browserDetails = detectBrowser(window);
const adapter = {
browserDetails,
commonShim,
extractVersion: extractVersion,
disableLog: disableLog,
disableWarnings: disableWarnings,
// Expose sdp as a convenience. For production apps include directly.
sdp
};
// Shim browser if found.
switch (browserDetails.browser) {
case 'chrome':
if (!chromeShim || !shimPeerConnection$1 || !options.shimChrome) {
logging('Chrome shim is not included in this adapter release.');
return adapter;
}
if (browserDetails.version === null) {
logging('Chrome shim can not determine version, not shimming.');
return adapter;
}
logging('adapter.js shimming chrome.');
// Export to the adapter global object visible in the browser.
adapter.browserShim = chromeShim;
// Must be called before shimPeerConnection.
shimAddIceCandidateNullOrEmpty(window, browserDetails);
shimParameterlessSetLocalDescription(window);
shimGetUserMedia$2(window, browserDetails);
shimMediaStream(window);
shimPeerConnection$1(window, browserDetails);
shimOnTrack$1(window);
shimAddTrackRemoveTrack(window, browserDetails);
shimGetSendersWithDtmf(window);
shimGetStats(window);
shimSenderReceiverGetStats(window);
fixNegotiationNeeded(window, browserDetails);
shimRTCIceCandidate(window);
shimRTCIceCandidateRelayProtocol(window);
shimConnectionState(window);
shimMaxMessageSize(window, browserDetails);
shimSendThrowTypeError(window);
removeExtmapAllowMixed(window, browserDetails);
break;
case 'firefox':
if (!firefoxShim || !shimPeerConnection || !options.shimFirefox) {
logging('Firefox shim is not included in this adapter release.');
return adapter;
}
logging('adapter.js shimming firefox.');
// Export to the adapter global object visible in the browser.
adapter.browserShim = firefoxShim;
// Must be called before shimPeerConnection.
shimAddIceCandidateNullOrEmpty(window, browserDetails);
shimParameterlessSetLocalDescription(window);
shimGetUserMedia$1(window, browserDetails);
shimPeerConnection(window, browserDetails);
shimOnTrack(window);
shimRemoveStream(window);
shimSenderGetStats(window);
shimReceiverGetStats(window);
shimRTCDataChannel(window);
shimAddTransceiver(window);
shimGetParameters(window);
shimCreateOffer(window);
shimCreateAnswer(window);
shimRTCIceCandidate(window);
shimConnectionState(window);
shimMaxMessageSize(window, browserDetails);
shimSendThrowTypeError(window);
break;
case 'safari':
if (!safariShim || !options.shimSafari) {
logging('Safari shim is not included in this adapter release.');
return adapter;
}
logging('adapter.js shimming safari.');
// Export to the adapter global object visible in the browser.
adapter.browserShim = safariShim;
// Must be called before shimCallbackAPI.
shimAddIceCandidateNullOrEmpty(window, browserDetails);
shimParameterlessSetLocalDescription(window);
shimRTCIceServerUrls(window);
shimCreateOfferLegacy(window);
shimCallbacksAPI(window);
shimLocalStreamsAPI(window);
shimRemoteStreamsAPI(window);
shimTrackEventTransceiver(window);
shimGetUserMedia(window);
shimAudioContext(window);
shimRTCIceCandidate(window);
shimRTCIceCandidateRelayProtocol(window);
shimMaxMessageSize(window, browserDetails);
shimSendThrowTypeError(window);
removeExtmapAllowMixed(window, browserDetails);
break;
default:
logging('Unsupported browser!');
break;
}
return adapter;
}
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
const adapter = adapterFactory({
window: typeof window === 'undefined' ? undefined : window
});
var logger$3 = new Logger('webrtc');
logger$3.info('浏览器详情:', adapter.browserDetails);
var WebRtc = /*#__PURE__*/function (_Event) {
_inherits(WebRtc, _Event);
var _super = _createSuper(WebRtc);
function WebRtc() {
var _this;
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, WebRtc);
_this = _super.call(this);
_this.containerLable = null;
_this.dhVideo = null;
_this.dhAudio = null;
_this.sessionType = 'answer'; //'answer' 应答模式
_this.peeConfig = null;
_this.muted = false; //是否静音播放视频,默认不静音
_this.enhanceOpus = false; //是否开启立体声
_this.vpxMaxBitrate = 0; // 码率增强
_this.openAsr = false; // 是否立即开启ASR识别
_this.peerConnection = null;
_this.mediaStreamConstraints = config.mediaStreamConstraints || {
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: false
}
};
_this.localMediaStream = null; //本地(采集设备)媒体流
_this.remoteStream = null; //rtc远端媒体流
_this.reportTimer = null; //上报report事件定时器
_this.trackLength = 0;
_this.useVideoAgent = false;
_this.useAudioAgent = false;
_this.isSupportVideoAgent = false;
_this.videoAgentContainer = null;
_this.isRemoteStream = false;
_this.camera = null;
_this.isStreamSwitch = false;
_this.videoSender = null;
//展示媒体流容器
_this.setsContainerLable(config.containerLable);
return _this;
}
//开始连接创建RTCPeerConnection实例
_createClass(WebRtc, [{
key: "open",
value: function open() {
var _options$enhanceOpus,
_this2 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.sessionType = options.sessionType; //呼叫或应答
this.peeConfig = options.peeConfig;
this.muted = !!options.muted;
this.enhanceOpus = (_options$enhanceOpus = options.enhanceOpus) !== null && _options$enhanceOpus !== void 0 ? _options$enhanceOpus : this.enhanceOpus;
this.vpxMaxBitrate = options.vpxMaxBitrate;
this.openAsr = options.openAsr;
this.transparent = options.transparent;
this.wipeGreen = options.wipeGreen;
this.useVideoAgent = options.useVideoAgent;
this.useAudioAgent = options.useAudioAgent;
this.isSupportVideoAgent = options.isSupportVideoAgent;
this.videoAgentContainer = options.videoAgentContainer;
if (!options.useAudioAgent) {
this.createDHVideo(options.transparent || options.wipeGreen);
} else {
this.createDHAudio();
}
if (options.isSupportVideoAgent && !options.useAudioAgent) {
this.mediaStreamConstraints.video = {
facingMode: "user"
};
}
this.peerConnection = new RTCPeerConnection(this.peeConfig);
this.peerConnection.addEventListener('datachannel', function (data) {
//监听datachannel通道事件
var channel = data.channel;
channel.onopen = function (event) {
console.log("rtc datachannel ".concat(channel.label, " opened"));
};
channel.onmessage = function (event) {
//监听datachannel的接收消息
console.log("Recv From rtc datachannel ".concat(channel.label, ", msg: ").concat(event.data));
var data = JSON.parse(event.data);
var params = data.params;
if (params.state === 'asrData') {
_this2.emit(WebRtc.EventType.ASRDATA, params);
} else if (params.state === 'asrStop') {
_this2.emit(WebRtc.EventType.ASRSTOP, params);
} else if (params.state === 'asrStart') {
_this2.emit(WebRtc.EventType.ASRSTART, params);
} else if (params.state === 'speakStart') {
_this2.emit(WebRtc.EventType.SPEAKSTART, params);
} else if (params.state === 'speakStop') {
_this2.emit(WebRtc.EventType.SPEAKSTOP, params);
} else if (params.state === 'speakText') {
_this2.emit(WebRtc.EventType.SPEAKSECTION, params);
} else if (params.state === 'ttsSpeakStart') {
_this2.emit(WebRtc.EventType.TTSSPEAKSTART, params);
} else if (params.state === 'ttsSpeakStop') {
_this2.emit(WebRtc.EventType.TTSSPEAKSTOP, params);
} else if (params.state === 'ttsSpeakText') {
_this2.emit(WebRtc.EventType.TTSSPEAKSECTION, params);
}
};
});
this.addHandler();
}
//关闭连接
}, {
key: "close",
value: function close() {
this.trackLength = 0;
this.destroyCamera();
this.closeLocalMediaStream();
this.localMediaStream = null;
if (this.peerConnection && this.peerConnection.connectionState !== 'closed') {
this.peerConnection.getSenders().forEach(function (sender) {
return sender.replaceTrack(null);
});
this.peerConnection.close();
this.peerConnection = null;
}
if (this.reportTimer) {
clearInterval(this.reportTimer);
}
stopWipe();
this.isRemoteStream = false;
}
}, {
key: "addHandler",
value: function addHandler() {
var _this3 = this;
//当需要会话协商更改时触发,
//这种协商应该作为提议者进行,因为有些会话改变不能作为应答者进行协商。
this.peerConnection.onnegotiationneeded = function () {
logger$3.info('<onnegotiationneeded> peerConnection会话协商');
};
//webRtc连接状态
this.peerConnection.onconnectionstatechange = function () {
logger$3.info("[peerConnection\u8FDE\u63A5\u72B6\u6001] onconnectionstatechange - connectionState: ".concat(_this3.peerConnection.connectionState));
var connectionState = _this3.peerConnection.connectionState;
var params = {
step: 'connectionstate',
connectionState: connectionState
};
if (connectionState === 'disconnected' || connectionState === 'failed') {
params.success = false;
} else if (connectionState === 'connected') {
params.success = true;
_this3.playRemoteStream();
}
_this3.emit(WebRtc.EventType.STATUS, params);
};
//信令状态更改时触发
//信令状态:描述连接或重新连接到另一个对等端的信令过程的状态。
this.peerConnection.onsignalingstatechange = function () {
logger$3.info("[peerConnection\u4FE1\u4EE4\u72B6\u6001] onsignalingstatechange - signalingState: ".concat(_this3.peerConnection.signalingState));
};
//ICE收集状态变更时回调
this.peerConnection.onicegatheringstatechange = function () {
logger$3.info("[peerConnectionICE\u6536\u96C6\u72B6\u6001] onicegatheringstatechange - iceGatheringState: ".concat(_this3.peerConnection.iceGatheringState));
};
//当设置本地会话描述peerConnection.setLocalDescription()后触发candidate回调
this.peerConnection.onicecandidate = function (_ref) {
var candidate = _ref.candidate;
// 收集可用的candidate通过信令服务器把候选信息发送给远端
if (candidate) {
_this3.emit(WebRtc.EventType.SENDCANDIDATE, candidate);
}
};
//ice连接状态变更
this.peerConnection.oniceconnectionstatechange = function () {
logger$3.info("[peerConnectionICE\u8FDE\u63A5\u72B6\u6001] oniceconnectionstatechange - iceConnectionState: ".concat(_this3.peerConnection.iceConnectionState));
};
this.peerConnection.ontrack = function (event) {
logger$3.info('[peerConnection接收轨道] ontrack');
_this3.trackLength++;
// if (this.trackLength > 1) {
// this.playRemoteStream()
// }
};
this.report();
}
// 对外报告WebRTC状态信息
}, {
key: "report",
value: function report() {
var _this4 = this;
clearInterval(this.reportTimer);
if (!this.peerConnection) return;
this.reportTimer = setInterval(function () {
_this4.peerConnection.getStats().then(function (stats) {
var r = _this4._explainStats(stats, _this4.lastStats);
if (_this4.lastStats) {
_this4.emit(WebRtc.EventType.REPORT, r);
}
_this4.lastStats = stats;
});
}, 1000);
}
/**
* 将需要的stats解释出来
* @param {RTCStatsReport} stats 当前 stats
* @param {RTCStatsReport} last 上一次stats
* @returns 加工后的对象,格式如下
*/
}, {
key: "_explainStats",
value: function _explainStats(stats, last) {
if (!last) {
last = stats;
}
var currStats = Array.from(stats).map(function (item) {
return item[1];
});
var lastStats = Array.from(last).map(function (item) {
return item[1];
});
var r = {};
var pickedInfo = null;
var temp1 = null;
var temp2 = null;
// 下行视频流相关指标
temp1 = currStats.find(function (item) {
return 'inbound-rtp' === item.type && 'video' === item.kind;
});
if (temp1) {
pickedInfo = pick(temp1, ['frameWidth', 'frameHeight', 'framesPerSecond', 'packetsLost']);
set(r, 'video.download', pickedInfo);
temp2 = lastStats.find(function (item) {
return 'inbound-rtp' === item.type && 'video' === item.kind;
});
if (temp2) {
merge(r.video.download, {
packetsLostPerSecond: temp1.packetsLost - temp2.packetsLost // 丢包率
});
}
}
// 当前ICE通路信息
temp1 = currStats.find(function (item) {
return 'candidate-pair' === item.type && 'succeeded' === item.state && item.nominated;
});
if (temp1) {
pickedInfo = pick(temp1, ['bytesSent', 'bytesReceived', 'currentRoundTripTime', 'timestamp']);
pickedInfo.currentRoundTripTime = pickedInfo.currentRoundTripTime * 1000; // 往返时间 单位ms
set(r, 'connection', pickedInfo);
temp2 = lastStats.find(function (item) {
return 'candidate-pair' === item.type && 'succeeded' === item.state && item.nominated;
});
if (temp2) {
merge(r.connection, {
receivedBitsPerSecond: (temp1.bytesReceived - temp2.bytesReceived) * 8,
//接收码率
sentBitsPerSecond: (temp1.bytesSent - temp2.bytesSent) * 8 //发送码率
});
}
}
return r;
}
//添加candidate
}, {
key: "addIceCandidate",
value: function addIceCandidate(candidate) {
if (!candidate) {
return new Error('Candidate does not exist');
}
this.peerConnection.addIceCandidate(candidate).then(function () {
// Do stuff when the candidate is successfully passed to the ICE agent
})["catch"](function (error) {
logger$3.error('Error: Failure during addIceCandidate()', error);
});
}
//设置容器
}, {
key: "setsContainerLable",
value: function setsContainerLable(containerLable) {
if (containerLable) {
containerLable = typeof containerLable === 'string' ? document.querySelector(containerLable) : containerLable instanceof HTMLElement ? containerLable : null;
}
if (!containerLable) {
throw new Error('containerLable is null');
}
this.containerLable = containerLable;
}
//获取answer
}, {
key: "createAnswer",
value: function createAnswer() {
this.setLocalDescription('createAnswer', this.peerConnection.createAnswer());
}
//设置本地sdp
}, {
key: "setLocalDescription",
value: function setLocalDescription(step, sdpPromise) {
var _this5 = this;
sdpPromise.then(function (sessionDescription) {
if (_this5.enhanceOpus) {
sessionDescription.sdp = sessionDescription.sdp.replace(/\r\na=fmtp:111 minptime=10;useinbandfec=1/g, '\r\na=fmtp:111 minptime=10;useinbandfec=1;stereo=1;maxaveragebitrate=128000;maxplaybackrate=48000');
}
// 设置 vpx 的码率
if (_this5.vpxMaxBitrate && _this5.vpxMaxBitrate > 0) {
logger$3.info("\u7801\u7387\u8BBE\u7F6E\u4E3A\uFF1A".concat(_this5.vpxMaxBitrate));
var max = _this5.vpxMaxBitrate;
var min = max * 0.8;
var start = min;
sessionDescription.sdp = sessionDescription.sdp.replace(/\r\na=rtcp-fb:96 transport-cc/g, "\r\na=rtcp-fb:96 transport-cc\r\na=fmtp:96 x-google-max-bitrate=".concat(max, ";x-google-min-bitrate=").concat(min, ";x-google-start-bitrate=").concat(start));
sessionDescription.sdp = sessionDescription.sdp.replace(/\r\na=fmtp:98 profile-id=0/g, "\r\na=fmtp:98 profile-id=0;x-google-max-bitrate=".concat(max, ";x-google-min-bitrate=").concat(min, ";x-google-start-bitrate=").concat(start));
sessionDescription.sdp = sessionDescription.sdp.replace(/\r\na=fmtp:100 profile-id=2/g, "\r\na=fmtp:100 profile-id=2;x-google-max-bitrate=".concat(max, ";x-google-min-bitrate=").concat(min, ";x-google-start-bitrate=").concat(start));
}
//设置本地描述
return _this5.peerConnection.setLocalDescription(sessionDescription);
}).then(function () {
// 发送localDescription
_this5.sendSdp(_this5.peerConnection.localDescription);
})["catch"](function (error) {
_this5.emit(WebRtc.EventType.STATUS, {
step: step,
success: false,
message: "".concat(step, " failed.")
});
logger$3.error("".concat(step, " sdp failed"), error);
});
}
//设置远端描述
}, {
key: "setRemoteDescription",
value: function setRemoteDescription(sessionDescription) {
var _this6 = this;
var isRestartICE = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.peerConnection.setRemoteDescription(sessionDescription).then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (!(_this6.sessionType === 'answer')) {
_context.next = 5;
break;
}
if (!(_this6.openAsr && !isRestartICE)) {
_context.next = 4;
break;
}
_context.next = 4;
return _this6.getMediaStream();
case 4:
if (_this6.peerConnection) {
if (!isRestartICE) {
_this6.peerAddTrack();
}
_this6.createAnswer();
} else {
_this6.closeLocalMediaStream();
}
case 5:
case "end":
return _context.stop();
}
}, _callee);
})))["catch"](function (error) {
logger$3.error('setremotedescription failed', error);
_this6.emit(WebRtc.EventType.STATUS, {
step: 'setRemoteDescription',
success: false,
message: 'setremotedescription failed'
});
});
}
//获取媒体设备能力,捕获媒体流
}, {
key: "getMediaStream",
value: function getMediaStream() {
var _this7 = this;
return navigator.mediaDevices.getUserMedia(this.mediaStreamConstraints).then(function (stream) {
logger$3.info('获取到本地媒体流');
_this7.localMediaStream = stream;
})["catch"](function (error) {
var name = error.name,
message = error.message;
logger$3.error("getUserMedia failed. ".concat(name, ": ").concat(message));
_this7.emit(WebRtc.EventType.STATUS, {
step: 'getUserMedia',
success: false,
message: "getUserMedia failed. ".concat(name, ": ").concat(message)
});
});
}
}, {
key: "handleUserVideoAgent",
value: function handleUserVideoAgent() {
var _this8 = this;
if (this.isSupportVideoAgent && this.localMediaStream) {
var _this$localMediaStrea;
// 销毁本地流
var videoTracks = (_this$localMediaStrea = this.localMediaStream) === null || _this$localMediaStrea === void 0 ? void 0 : _this$localMediaStrea.getVideoTracks();
videoTracks === null || videoTracks === void 0 ? void 0 : videoTracks.forEach(function (track) {
track.stop(); // 停止轨道
_this8.localMediaStream.removeTrack(track); // 从流中移除
});
// 销毁管道
this.videoSender = this.peerConnection.getSenders().find(function (sender) {
return sender.track && sender.track.kind === 'video';
});
if (this.videoSender) {
this.videoSender.replaceTrack(null);
}
}
if (this.useVideoAgent && this.isSupportVideoAgent) {
this.createCamera();
}
return true;
}
}, {
key: "peerAddTrack",
value: function peerAddTrack() {
var _this$localMediaStrea2,
_this9 = this;
// 把本地媒体流轨道添加到连接上
(_this$localMediaStrea2 = this.localMediaStream) === null || _this$localMediaStrea2 === void 0 ? void 0 : _this$localMediaStrea2.getTracks().forEach(function (track) {
return _this9.peerConnection.addTrack(track, _this9.localMediaStream);
});
if (!this.useAudioAgent) {
this.handleUserVideoAgent();
}
}
//关闭本地媒体设备流
}, {
key: "closeLocalMediaStream",
value: function closeLocalMediaStream() {
var _this$localMediaStrea3;
logger$3.info('关闭本地媒体设备流');
var tracks = (_this$localMediaStrea3 = this.localMediaStream) === null || _this$localMediaStrea3 === void 0 ? void 0 : _this$localMediaStrea3.getTracks();
if (tracks !== null && tracks !== void 0 && tracks.length) {
tracks.forEach(function (track) {
track.stop();
});
}
if (this.videoSender) {
this.videoSender.replaceTrack(null);
this.videoSender = null;
}
}
}, {
key: "enableAudioContext",
value: function enableAudioContext() {
this.localMediaStream.getTracks().forEach(function (track) {
if (track.kind === 'audio') {
track.enabled = true;
}
});
}
}, {
key: "disableAudioContext",
value: function disableAudioContext() {
this.localMediaStream.getTracks().forEach(function (track) {
if (track.kind === 'audio') {
track.enabled = false;
}
});
}
}, {
key: "switchstreamBetweenDigitalAndCamera",
value: function switchstreamBetweenDigitalAndCamera() {
if (this.isSupportVideoAgent && this.camera && this.dhVideo) {
var tracks = this.peerConnection.getReceivers().map(function (receiver) {
return receiver.track;
});
if (this.isStreamSwitch) {
this.dhVideo.srcObject = this.remoteStream = new MediaStream([tracks[0], tracks[1]]);
this.camera.srcObject = this.localMediaStream;
this.isStreamSwitch = false;
} else {
this.dhVideo.srcObject = this.localMediaStream;
this.camera.srcObject = this.remoteStream = new MediaStream([tracks[0], tracks[1]]);
this.isStreamSwitch = true;
}
}
}
}, {
key: "createCamera",
value: function createCamera() {
var _this10 = this;
if (this.camera) return;
this.mediaStreamConstraints.video = {
facingMode: "user"
};
navigator.mediaDevices.getUserMedia(this.mediaStreamConstraints).then(function (stream) {
_this10.localMediaStream = stream;
var videoTrack = _this10.localMediaStream.getVideoTracks()[0]; // 获取视频轨道
_this10.videoSender.replaceTrack(videoTrack); // 替换现有的(占位)视频轨道
var camera = _this10.camera = document.createElement('video');
camera.setAttribute('playsinline', true);
camera.setAttribute('autoplay', true);
camera.muted = true;
camera.srcObject = _this10.localMediaStream;
if (_this10.videoAgentContainer) {
Object.assign(camera.style, {
width: '100%',
height: '100%',
zIndex: 10,
position: 'absolute',
top: '0',
right: '0',
objectFit: 'cover',
transform: 'rotateY(180deg)'
});
var dom = document.querySelector(_this10.videoAgentContainer);
console.log('dom', dom);
if (dom) {
dom.appendChild(camera);
}
} else {
Object.assign(camera.style, {
width: '25%',
height: '25%',
zIndex: 10,
position: 'absolute',
top: '0',
right: '0',
objectFit: 'cover',
transform: 'rotateY(180deg)'
});
_this10.containerLable.appendChild(camera);
}
_this10.showCamera();
});
}
}, {
key: "destroyCamera",
value: function destroyCamera() {
var _this11 = this;
if (!this.camera) return;
if (this.videoSender) {
this.videoSender.replaceTrack(null);
}
var videoTracks = this.localMediaStream.getVideoTracks();
videoTracks.forEach(function (track) {
track.stop(); // 停止轨道
_this11.localMediaStream.removeTrack(track); // 从流中移除
});
if (this.videoAgentContainer) {
var _document$querySelect;
(_document$querySelect = document.querySelector(this.videoAgentContainer)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.removeChild(this.camera);
} else {
var _this$containerLable;
(_this$containerLable = this.containerLable) === null || _this$containerLable === void 0 ? void 0 : _this$containerLable.removeChild(this.camera);
}
this.camera.srcObject = null;
this.camera = null;
this.emit(WebRtc.EventType.CAMERACHANGE, {
status: 'hidden'
});
}
}, {
key: "switchCameraMode",
value: function () {
var _switchCameraMode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var _videoTrack$getSettin,
_videoTrack$getSettin2,
_this12 = this;
var videoTrack, newFacingMode;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
videoTrack = this.localMediaStream.getVideoTracks()[0];
if (videoTrack !== null && videoTrack !== void 0 && (_videoTrack$getSettin = videoTrack.getSettings()) !== null && _videoTrack$getSettin !== void 0 && _videoTrack$getSettin.facingMode) {
_context3.next = 4;
break;
}
logger$3.error("Currently there is no switching device");
return _context3.abrupt("return");
case 4:
newFacingMode = (videoTrack === null || videoTrack === void 0 || (_videoTrack$getSettin2 = videoTrack.getSettings()) === null || _videoTrack$getSettin2 === void 0 ? void 0 : _videoTrack$getSettin2.facingMode) === "user" ? "environment" : "user";
this.mediaStreamConstraints.video = {
facingMode: newFacingMode
};
if (this.localMediaStream) {
this.localMediaStream.getTracks().forEach(function (track) {
return track.stop();
});
}
navigator.mediaDevices.getUserMedia(this.mediaStreamConstraints).then( /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(stream) {
var newVideoTrack, newAudioTrack, videoSender, audioSender;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
newVideoTrack = stream.getVideoTracks()[0];
newAudioTrack = stream.getAudioTracks()[0]; // 替换 RTC 中的视频轨道和音频轨道
videoSender = _this12.peerConnection.getSenders().find(function (sender) {
return sender.track && sender.track.kind === "video";
});
audioSender = _this12.peerConnection.getSenders().find(function (sender) {
return sender.track && sender.track.kind === "audio";
});
if (!_this12.videoSender) {
_context2.next = 9;
break;
}
_context2.next = 7;
return _this12.videoSender.replaceTrack(newVideoTrack);
case 7:
_context2.next = 11;
break;
case 9:
videoSender.replaceTrack(newVideoTrack);
_this12.videoSender = videoSender;
case 11:
if (!audioSender) {
_context2.next = 14;
break;
}
_context2.next = 14;
return audioSender.replaceTrack(newAudioTrack);
case 14:
_this12.localMediaStream = stream;
_this12.camera.srcObject = _this12.localMediaStream;
Object.assign(_this12.camera.style, {
transform: newFacingMode === 'environment' ? 'rotateY(0deg)' : 'rotateY(180deg)'
});
_this12.emit(WebRtc.EventType.CAMERACHANGE, {
mode: newFacingMode,
status: 'show'
});
case 18:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}())["catch"](function (error) {
var name = error.name,
message = error.message;
logger$3.error("getUserMedia failed. ".concat(name, ": ").concat(message));
});
case 8:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function switchCameraMode() {
return _switchCameraMode.apply(this, arguments);
}
return switchCameraMode;
}()
}, {
key: "playCamera",
value: function playCamera() {
if (this.camera) {
var _this$camera;
(_this$camera = this.camera) === null || _this$camera === void 0 ? void 0 : _this$camera.play();
}
}
}, {
key: "showCamera",
value: function showCamera() {
if (this.camera) {
Object.assign(this.camera.style, {
visibility: 'visible'
});
this.emit(WebRtc.EventType.CAMERACHANGE, {
status: 'show'
});
}
}
}, {
key: "hideCamera",
value: function hideCamera() {
if (this.camera) {
Object.assign(this.camera.style, {
visibility: 'hidden'
});
this.emit(WebRtc.EventType.CAMERACHANGE, {
status: 'hidden'
});
}
}
}, {
key: "createDHAudio",
value: function createDHAudio() {
if (this.dhAudio) return;
this.dhAudio = document.createElement('audio');
this.dhAudio.autoplay = true; //远端流自动播放
// Object.assign(this.dhAudio.style, {
// display: 'none',
// })
this.containerLable.appendChild(this.dhAudio);
}
/**
* 创建视频标签
* @param {boolean} isTransparent 是否透明背景
* @returns
*/
}, {
key: "createDHVideo",
value: function createDHVideo(isTransparent) {
var _this13 = this;
if (this.dhVideo) return;
this.dhVideo = document.createElement('video');
this.dhVideo.autoplay = true; //远端流自动播放
this.dhVideo.muted = this.muted; //是否静音
this.dhVideo.addEventListener('playing', function () {
var _this13$dhVideo$style, _this13$dhVideo$style2;
logger$3.info('dhvideo playing', (_this13$dhVideo$style = _this13.dhVideo.style) === null || _this13$dhVideo$style === void 0 ? void 0 : _this13$dhVideo$style.visibility);
if (((_this13$dhVideo$style2 = _this13.dhVideo.style) === null || _this13$dhVideo$style2 === void 0 ? void 0 : _this13$dhVideo$style2.visibility) !== 'visible') {
_this13.showDHVideo();
_this13.emit(WebRtc.EventType.SHOW);
}
});
if (isTransparent) {
Object.assign(this.dhVideo.style, {
width: '1px',
height: '1px',
zIndex: -1,
position: 'absolute',
top: '50%',
left: '50%'
});
} else {
Object.assign(this.dhVideo.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
objectFit: 'cover'
});
}
Object.assign(this.dhVideo.style, {
visibility: 'hidden'
});
this.dhVideo.setAttribute('playsinline', true);
this.dhVideo.setAttribute('preload', 'auto');
Object.assign(this.containerLable.style, {
position: 'relative'
});
this.containerLable.appendChild(this.dhVideo);
}
}, {
key: "showDHVideo",
value: function showDHVideo() {
Object.assign(this.dhVideo.style, {
visibility: 'visible'
});
if (this.wipeGreen) {
// 优先使用扣绿幕方案,节省服端资源
wipeGreen(this.dhVideo);
} else if (this.transparent) {
wipe(this.dhVideo);
}
}
}, {
key: "hideDHVideo",
value: function hideDHVideo() {
if (this.dhVideo) {
Object.assign(this.dhVideo.style, {
visibility: 'hidden'
});
}
}
/**
* 移除视频标签
*/
}, {
key: "removeVideoLabel",
value: function removeVideoLabel() {
if (this.containerLable && this.dhVideo) {
this.containerLable.removeChild(this.dhVideo);
this.dhVideo = null;
}
}
/**
* 设置远端媒体流静音状态
* @param {Boolean} muted true: 静音, false: 取消静音
*/
}, {
key: "setVideoMuted",
value: function setVideoMuted(muted) {
if (!this.dhVideo) return;
if (this.dhVideo.muted !== muted) {
this.dhVideo.muted = muted;
}
}
//发送SDP
}, {
key: "sendSdp",
value: function sendSdp(localDescription) {
// logger.info('sendSdp localDescription', localDescription)
this.emit(WebRtc.EventType.SENDSDP, localDescription);
}
}, {
key: "playRemoteStream",
value: function playRemoteStream() {
var _this14 = this;
if (this.isRemoteStream) return false;
try {
var tracks = this.peerConnection.getReceivers().map(function (receiver) {
return receiver.track;
});
if (this.useAudioAgent) {
this.dhAudio.srcObject = this.remoteStream = new MediaStream([tracks[0]]);
} else {
this.dhVideo.srcObject = this.remoteStream = new MediaStream([tracks[0], tracks[1]]);
}
this.isRemoteStream = true;
setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
var _this14$dhVideo;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
if (!_this14.useAudioAgent) {
_context4.next = 6;
break;
}
_context4.next = 3;
return _this14.dhAudio.play();
case 3:
_this14.emit(WebRtc.EventType.SHOW);
_context4.next = 15;
break;
case 6:
if (!(((_this14$dhVideo = _this14.dhVideo) === null || _this14$dhVideo === void 0 || (_this14$dhVideo = _this14$dhVideo.style) === null || _this14$dhVideo === void 0 ? void 0 : _this14$dhVideo.visibility) !== 'visible')) {
_context4.next = 15;
break;
}
_context4.prev = 7;
_context4.next = 10;
return _this14.dhVideo.play();
case 10:
_context4.next = 15;
break;
case 12:
_context4.prev = 12;
_context4.t0 = _context4["catch"](7);
_this14.emit(WebRtc.EventType.NEEDUSERINTERACT);
case 15:
case "end":
return _context4.stop();
}
}, _callee4, null, [[7, 12]]);
})), 250);
} catch (e) {
console.warn(e);
}
}
}, {
key: "reopenAsr",
value: function reopenAsr() {
this.openAsr = true;
}
}, {
key: "destroy",
value: function destroy() {
this.close();
_get(_getPrototypeOf(WebRtc.prototype), "destroy", this).call(this);
}
}]);
return WebRtc;
}(Event$1);
//自定义事件
_defineProperty(WebRtc, "EventType", {
STATUS: 'STATUS',
//状态更新
SENDSDP: 'SENDSDP',
//发送 answer SDP
SENDCANDIDATE: 'SENDCANDIDATE',
//发送candidate
REPORT: 'REPORT',
//报告网络信息
SHOW: 'SHOW',
//RTC流可显示
NEEDUSERINTERACT: 'NEEDUSERINTERACT',
//需要用户交互目前用来处理ioswebview内必须由用户出发play的问题
ASRSTART: 'ASRSTART',
ASRSTOP: 'ASRSTOP',
ASRDATA: 'ASRDATA',
SPEAKSTART: 'SPEAKSTART',
SPEAKSTOP: 'SPEAKSTOP',
SPEAKSECTION: 'SPEAKSECTION',
TTSSPEAKSTART: 'TTSSPEAKSTART',
TTSSPEAKSTOP: 'TTSSPEAKSTOP',
TTSSPEAKSECTION: 'TTSSPEAKSECTION',
CAMERACHANGE: 'CAMERACHANGE',
RESTARTICE: 'RESTARTICE'
});
var mqtt_min = {exports: {}};
(function (module, exports) {
!function (e) {
module.exports = e();
console.log(module.exports);
}(function () {
return function () {
return function e(t, r, n) {
function i(s, a) {
if (!r[s]) {
if (!t[s]) {
var l = "function" == typeof commonjsRequire && commonjsRequire;
if (!a && l) return l(s, !0);
if (o) return o(s, !0);
var u = new Error("Cannot find module '" + s + "'");
throw u.code = "MODULE_NOT_FOUND", u;
}
var c = r[s] = {
exports: {}
};
t[s][0].call(c.exports, function (e) {
return i(t[s][1][e] || e);
}, c, c.exports, e, t, r, n);
}
return r[s].exports;
}
for (var o = "function" == typeof commonjsRequire && commonjsRequire, s = 0; s < n.length; s++) i(n[s]);
return i;
};
}()({
1: [function (e, t, r) {
(function (r, n) {
(function () {
const i = e("events").EventEmitter,
o = e("./store"),
s = e("./topic-alias-recv"),
a = e("./topic-alias-send"),
l = e("mqtt-packet"),
u = e("./default-message-id-provider"),
c = e("readable-stream").Writable,
h = e("inherits"),
f = e("reinterval"),
p = e("rfdc/default"),
d = e("./validations"),
g = e("xtend"),
y = e("debug")("mqttjs:client"),
b = r ? r.nextTick : function (e) {
setTimeout(e, 0);
},
m = n.setImmediate || function (e) {
b(e);
},
v = {
keepalive: 60,
reschedulePings: !0,
protocolId: "MQTT",
protocolVersion: 4,
reconnectPeriod: 1e3,
connectTimeout: 3e4,
clean: !0,
resubscribe: !0
},
w = ["ECONNREFUSED", "EADDRINUSE", "ECONNRESET", "ENOTFOUND"],
_ = {
0: "",
1: "Unacceptable protocol version",
2: "Identifier rejected",
3: "Server unavailable",
4: "Bad username or password",
5: "Not authorized",
16: "No matching subscribers",
17: "No subscription existed",
128: "Unspecified error",
129: "Malformed Packet",
130: "Protocol Error",
131: "Implementation specific error",
132: "Unsupported Protocol Version",
133: "Client Identifier not valid",
134: "Bad User Name or Password",
135: "Not authorized",
136: "Server unavailable",
137: "Server busy",
138: "Banned",
139: "Server shutting down",
140: "Bad authentication method",
141: "Keep Alive timeout",
142: "Session taken over",
143: "Topic Filter invalid",
144: "Topic Name invalid",
145: "Packet identifier in use",
146: "Packet Identifier not found",
147: "Receive Maximum exceeded",
148: "Topic Alias invalid",
149: "Packet too large",
150: "Message rate too high",
151: "Quota exceeded",
152: "Administrative action",
153: "Payload format invalid",
154: "Retain not supported",
155: "QoS not supported",
156: "Use another server",
157: "Server moved",
158: "Shared Subscriptions not supported",
159: "Connection rate exceeded",
160: "Maximum connect time",
161: "Subscription Identifiers not supported",
162: "Wildcard Subscriptions not supported"
};
function k(e, t) {
let r;
t.properties && (r = t.properties.topicAlias);
let n = t.topic.toString();
if (0 === n.length) {
if (void 0 === r) return new Error("Unregistered Topic Alias");
if (void 0 === (n = e.topicAliasSend.getTopicByAlias(r))) return new Error("Unregistered Topic Alias");
t.topic = n;
}
r && delete t.properties.topicAlias;
}
function S(e, t, r) {
y("sendPacket :: packet: %O", t), y("sendPacket :: emitting `packetsend`"), e.emit("packetsend", t), y("sendPacket :: writing to stream");
const n = l.writeToStream(t, e.stream, e.options);
y("sendPacket :: writeToStream result %s", n), !n && r && r !== C ? (y("sendPacket :: handle events on `drain` once through callback."), e.stream.once("drain", r)) : r && (y("sendPacket :: invoking cb"), r());
}
function E(e, t, r, n) {
y("storeAndSend :: store packet with cmd %s to outgoingStore", t.cmd);
let i,
o = t;
if ("publish" === o.cmd && (o = p(t), i = k(e, o))) return r && r(i);
e.outgoingStore.put(o, function (i) {
if (i) return r && r(i);
n(), S(e, t, r);
});
}
function C(e) {
y("nop ::", e);
}
function T(e, t) {
let r;
const n = this;
if (!(this instanceof T)) return new T(e, t);
for (r in this.options = t || {}, v) void 0 === this.options[r] ? this.options[r] = v[r] : this.options[r] = t[r];
y("MqttClient :: options.protocol", t.protocol), y("MqttClient :: options.protocolVersion", t.protocolVersion), y("MqttClient :: options.username", t.username), y("MqttClient :: options.keepalive", t.keepalive), y("MqttClient :: options.reconnectPeriod", t.reconnectPeriod), y("MqttClient :: options.rejectUnauthorized", t.rejectUnauthorized), y("MqttClient :: options.topicAliasMaximum", t.topicAliasMaximum), this.options.clientId = "string" == typeof t.clientId ? t.clientId : "mqttjs_" + Math.random().toString(16).substr(2, 8), y("MqttClient :: clientId", this.options.clientId), this.options.customHandleAcks = 5 === t.protocolVersion && t.customHandleAcks ? t.customHandleAcks : function () {
arguments[3](0);
}, this.streamBuilder = e, this.messageIdProvider = void 0 === this.options.messageIdProvider ? new u() : this.options.messageIdProvider, this.outgoingStore = t.outgoingStore || new o(), this.incomingStore = t.incomingStore || new o(), this.queueQoSZero = void 0 === t.queueQoSZero || t.queueQoSZero, this._resubscribeTopics = {}, this.messageIdToTopic = {}, this.pingTimer = null, this.connected = !1, this.disconnecting = !1, this.queue = [], this.connackTimer = null, this.reconnectTimer = null, this._storeProcessing = !1, this._packetIdsDuringStoreProcessing = {}, this._storeProcessingQueue = [], this.outgoing = {}, this._firstConnection = !0, t.topicAliasMaximum > 0 && (t.topicAliasMaximum > 65535 ? y("MqttClient :: options.topicAliasMaximum is out of range") : this.topicAliasRecv = new s(t.topicAliasMaximum)), this.on("connect", function () {
const e = this.queue;
y("connect :: sending queued packets"), function t() {
const r = e.shift();
y("deliver :: entry %o", r);
let i = null;
if (!r) return void n._resubscribe();
i = r.packet, y("deliver :: call _sendPacket for %o", i);
let o = !0;
i.messageId && 0 !== i.messageId && (n.messageIdProvider.register(i.messageId) || (o = !1)), o ? n._sendPacket(i, function (e) {
r.cb && r.cb(e), t();
}) : (y("messageId: %d has already used. The message is skipped and removed.", i.messageId), t());
}();
}), this.on("close", function () {
y("close :: connected set to `false`"), this.connected = !1, y("close :: clearing connackTimer"), clearTimeout(this.connackTimer), y("close :: clearing ping timer"), null !== n.pingTimer && (n.pingTimer.clear(), n.pingTimer = null), this.topicAliasRecv && this.topicAliasRecv.clear(), y("close :: calling _setupReconnect"), this._setupReconnect();
}), i.call(this), y("MqttClient :: setting up stream"), this._setupStream();
}
h(T, i), T.prototype._setupStream = function () {
const e = this,
t = new c(),
r = l.parser(this.options);
let n = null;
const i = [];
function o() {
if (i.length) b(s);else {
const e = n;
n = null, e();
}
}
function s() {
y("work :: getting next packet in queue");
const t = i.shift();
if (t) y("work :: packet pulled from queue"), e._handlePacket(t, o);else {
y("work :: no packets in queue");
const e = n;
n = null, y("work :: done flag is %s", !!e), e && e();
}
}
y("_setupStream :: calling method to clear reconnect"), this._clearReconnect(), y("_setupStream :: using streamBuilder provided to client to create stream"), this.stream = this.streamBuilder(this), r.on("packet", function (e) {
y("parser :: on packet push to packets array."), i.push(e);
}), t._write = function (e, t, i) {
n = i, y("writable stream :: parsing buffer"), r.parse(e), s();
}, y("_setupStream :: pipe stream to writable stream"), this.stream.pipe(t), this.stream.on("error", function (t) {
y("streamErrorHandler :: error", t.message), w.includes(t.code) ? (y("streamErrorHandler :: emitting error"), e.emit("error", t)) : C(t);
}), this.stream.on("close", function () {
var t;
y("(%s)stream :: on close", e.options.clientId), (t = e.outgoing) && (y("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"), Object.keys(t).forEach(function (e) {
t[e].volatile && "function" == typeof t[e].cb && (t[e].cb(new Error("Connection closed")), delete t[e]);
})), y("stream: emit close to MqttClient"), e.emit("close");
}), y("_setupStream: sending packet `connect`");
const a = Object.create(this.options);
if (a.cmd = "connect", this.topicAliasRecv && (a.properties || (a.properties = {}), this.topicAliasRecv && (a.properties.topicAliasMaximum = this.topicAliasRecv.max)), S(this, a), r.on("error", this.emit.bind(this, "error")), this.options.properties) {
if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) return e.end(() => this.emit("error", new Error("Packet has no Authentication Method"))), this;
if (this.options.properties.authenticationMethod && this.options.authPacket && "object" == typeof this.options.authPacket) {
S(this, g({
cmd: "auth",
reasonCode: 0
}, this.options.authPacket));
}
}
this.stream.setMaxListeners(1e3), clearTimeout(this.connackTimer), this.connackTimer = setTimeout(function () {
y("!!connectTimeout hit!! Calling _cleanUp with force `true`"), e._cleanUp(!0);
}, this.options.connectTimeout);
}, T.prototype._handlePacket = function (e, t) {
const r = this.options;
if (5 === r.protocolVersion && r.properties && r.properties.maximumPacketSize && r.properties.maximumPacketSize < e.length) return this.emit("error", new Error("exceeding packets size " + e.cmd)), this.end({
reasonCode: 149,
properties: {
reasonString: "Maximum packet size was exceeded"
}
}), this;
switch (y("_handlePacket :: emitting packetreceive"), this.emit("packetreceive", e), e.cmd) {
case "publish":
this._handlePublish(e, t);
break;
case "puback":
case "pubrec":
case "pubcomp":
case "suback":
case "unsuback":
this._handleAck(e), t();
break;
case "pubrel":
this._handlePubrel(e, t);
break;
case "connack":
this._handleConnack(e), t();
break;
case "auth":
this._handleAuth(e), t();
break;
case "pingresp":
this._handlePingresp(e), t();
break;
case "disconnect":
this._handleDisconnect(e), t();
}
}, T.prototype._checkDisconnecting = function (e) {
return this.disconnecting && (e && e !== C ? e(new Error("client disconnecting")) : this.emit("error", new Error("client disconnecting"))), this.disconnecting;
}, T.prototype.publish = function (e, t, r, n) {
y("publish :: message `%s` to topic `%s`", t, e);
const i = this.options;
"function" == typeof r && (n = r, r = null);
if (r = g({
qos: 0,
retain: !1,
dup: !1
}, r), this._checkDisconnecting(n)) return this;
const o = this,
s = function () {
let s = 0;
if ((1 === r.qos || 2 === r.qos) && null === (s = o._nextId())) return y("No messageId left"), !1;
const a = {
cmd: "publish",
topic: e,
payload: t,
qos: r.qos,
retain: r.retain,
messageId: s,
dup: r.dup
};
switch (5 === i.protocolVersion && (a.properties = r.properties), y("publish :: qos", r.qos), r.qos) {
case 1:
case 2:
o.outgoing[a.messageId] = {
volatile: !1,
cb: n || C
}, y("MqttClient:publish: packet cmd: %s", a.cmd), o._sendPacket(a, void 0, r.cbStorePut);
break;
default:
y("MqttClient:publish: packet cmd: %s", a.cmd), o._sendPacket(a, n, r.cbStorePut);
}
return !0;
};
return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !s()) && this._storeProcessingQueue.push({
invoke: s,
cbStorePut: r.cbStorePut,
callback: n
}), this;
}, T.prototype.subscribe = function () {
const e = this,
t = new Array(arguments.length);
for (let e = 0; e < arguments.length; e++) t[e] = arguments[e];
const r = [];
let n = t.shift();
const i = n.resubscribe;
let o = t.pop() || C,
s = t.pop();
const a = this.options.protocolVersion;
delete n.resubscribe, "string" == typeof n && (n = [n]), "function" != typeof o && (s = o, o = C);
const l = d.validateTopics(n);
if (null !== l) return m(o, new Error("Invalid topic " + l)), this;
if (this._checkDisconnecting(o)) return y("subscribe: discconecting true"), this;
const u = {
qos: 0
};
if (5 === a && (u.nl = !1, u.rap = !1, u.rh = 0), s = g(u, s), Array.isArray(n) ? n.forEach(function (t) {
if (y("subscribe: array topic %s", t), !Object.prototype.hasOwnProperty.call(e._resubscribeTopics, t) || e._resubscribeTopics[t].qos < s.qos || i) {
const e = {
topic: t,
qos: s.qos
};
5 === a && (e.nl = s.nl, e.rap = s.rap, e.rh = s.rh, e.properties = s.properties), y("subscribe: pushing topic `%s` and qos `%s` to subs list", e.topic, e.qos), r.push(e);
}
}) : Object.keys(n).forEach(function (t) {
if (y("subscribe: object topic %s", t), !Object.prototype.hasOwnProperty.call(e._resubscribeTopics, t) || e._resubscribeTopics[t].qos < n[t].qos || i) {
const e = {
topic: t,
qos: n[t].qos
};
5 === a && (e.nl = n[t].nl, e.rap = n[t].rap, e.rh = n[t].rh, e.properties = s.properties), y("subscribe: pushing `%s` to subs list", e), r.push(e);
}
}), !r.length) return o(null, []), this;
const c = function () {
const t = e._nextId();
if (null === t) return y("No messageId left"), !1;
const n = {
cmd: "subscribe",
subscriptions: r,
qos: 1,
retain: !1,
dup: !1,
messageId: t
};
if (s.properties && (n.properties = s.properties), e.options.resubscribe) {
y("subscribe :: resubscribe true");
const t = [];
r.forEach(function (r) {
if (e.options.reconnectPeriod > 0) {
const n = {
qos: r.qos
};
5 === a && (n.nl = r.nl || !1, n.rap = r.rap || !1, n.rh = r.rh || 0, n.properties = r.properties), e._resubscribeTopics[r.topic] = n, t.push(r.topic);
}
}), e.messageIdToTopic[n.messageId] = t;
}
return e.outgoing[n.messageId] = {
volatile: !0,
cb: function (e, t) {
if (!e) {
const e = t.granted;
for (let t = 0; t < e.length; t += 1) r[t].qos = e[t];
}
o(e, r);
}
}, y("subscribe :: call _sendPacket"), e._sendPacket(n), !0;
};
return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !c()) && this._storeProcessingQueue.push({
invoke: c,
callback: o
}), this;
}, T.prototype.unsubscribe = function () {
const e = this,
t = new Array(arguments.length);
for (let e = 0; e < arguments.length; e++) t[e] = arguments[e];
let r = t.shift(),
n = t.pop() || C,
i = t.pop();
"string" == typeof r && (r = [r]), "function" != typeof n && (i = n, n = C);
const o = d.validateTopics(r);
if (null !== o) return m(n, new Error("Invalid topic " + o)), this;
if (e._checkDisconnecting(n)) return this;
const s = function () {
const t = e._nextId();
if (null === t) return y("No messageId left"), !1;
const o = {
cmd: "unsubscribe",
qos: 1,
messageId: t
};
return "string" == typeof r ? o.unsubscriptions = [r] : Array.isArray(r) && (o.unsubscriptions = r), e.options.resubscribe && o.unsubscriptions.forEach(function (t) {
delete e._resubscribeTopics[t];
}), "object" == typeof i && i.properties && (o.properties = i.properties), e.outgoing[o.messageId] = {
volatile: !0,
cb: n
}, y("unsubscribe: call _sendPacket"), e._sendPacket(o), !0;
};
return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !s()) && this._storeProcessingQueue.push({
invoke: s,
callback: n
}), this;
}, T.prototype.end = function (e, t, r) {
const n = this;
function i() {
y("end :: (%s) :: finish :: calling _cleanUp with force %s", n.options.clientId, e), n._cleanUp(e, () => {
y("end :: finish :: calling process.nextTick on closeStores"), b(function () {
y("end :: closeStores: closing incoming and outgoing stores"), n.disconnected = !0, n.incomingStore.close(function (e) {
n.outgoingStore.close(function (t) {
if (y("end :: closeStores: emitting end"), n.emit("end"), r) {
const n = e || t;
y("end :: closeStores: invoking callback with args"), r(n);
}
});
}), n._deferredReconnect && n._deferredReconnect();
}.bind(n));
}, t);
}
return y("end :: (%s)", this.options.clientId), null != e && "boolean" == typeof e || (r = t || C, t = e, e = !1, "object" != typeof t && (r = t, t = null, "function" != typeof r && (r = C))), "object" != typeof t && (r = t, t = null), y("end :: cb? %s", !!r), r = r || C, this.disconnecting ? (r(), this) : (this._clearReconnect(), this.disconnecting = !0, !e && Object.keys(this.outgoing).length > 0 ? (y("end :: (%s) :: calling finish in 10ms once outgoing is empty", n.options.clientId), this.once("outgoingEmpty", setTimeout.bind(null, i, 10))) : (y("end :: (%s) :: immediately calling finish", n.options.clientId), i()), this);
}, T.prototype.removeOutgoingMessage = function (e) {
const t = this.outgoing[e] ? this.outgoing[e].cb : null;
return delete this.outgoing[e], this.outgoingStore.del({
messageId: e
}, function () {
t(new Error("Message removed"));
}), this;
}, T.prototype.reconnect = function (e) {
y("client reconnect");
const t = this,
r = function () {
e ? (t.options.incomingStore = e.incomingStore, t.options.outgoingStore = e.outgoingStore) : (t.options.incomingStore = null, t.options.outgoingStore = null), t.incomingStore = t.options.incomingStore || new o(), t.outgoingStore = t.options.outgoingStore || new o(), t.disconnecting = !1, t.disconnected = !1, t._deferredReconnect = null, t._reconnect();
};
return this.disconnecting && !this.disconnected ? this._deferredReconnect = r : r(), this;
}, T.prototype._reconnect = function () {
y("_reconnect: emitting reconnect to client"), this.emit("reconnect"), this.connected ? (this.end(() => {
this._setupStream();
}), y("client already connected. disconnecting first.")) : (y("_reconnect: calling _setupStream"), this._setupStream());
}, T.prototype._setupReconnect = function () {
const e = this;
!e.disconnecting && !e.reconnectTimer && e.options.reconnectPeriod > 0 ? (this.reconnecting || (y("_setupReconnect :: emit `offline` state"), this.emit("offline"), y("_setupReconnect :: set `reconnecting` to `true`"), this.reconnecting = !0), y("_setupReconnect :: setting reconnectTimer for %d ms", e.options.reconnectPeriod), e.reconnectTimer = setInterval(function () {
y("reconnectTimer :: reconnect triggered!"), e._reconnect();
}, e.options.reconnectPeriod)) : y("_setupReconnect :: doing nothing...");
}, T.prototype._clearReconnect = function () {
y("_clearReconnect : clearing reconnect timer"), this.reconnectTimer && (clearInterval(this.reconnectTimer), this.reconnectTimer = null);
}, T.prototype._cleanUp = function (e, t) {
const r = arguments[2];
if (t && (y("_cleanUp :: done callback provided for on stream close"), this.stream.on("close", t)), y("_cleanUp :: forced? %s", e), e) 0 === this.options.reconnectPeriod && this.options.clean && (n = this.outgoing) && (y("flush: queue exists? %b", !!n), Object.keys(n).forEach(function (e) {
"function" == typeof n[e].cb && (n[e].cb(new Error("Connection closed")), delete n[e]);
})), y("_cleanUp :: (%s) :: destroying stream", this.options.clientId), this.stream.destroy();else {
const e = g({
cmd: "disconnect"
}, r);
y("_cleanUp :: (%s) :: call _sendPacket with disconnect packet", this.options.clientId), this._sendPacket(e, m.bind(null, this.stream.end.bind(this.stream)));
}
var n;
this.disconnecting || (y("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."), this._clearReconnect(), this._setupReconnect()), null !== this.pingTimer && (y("_cleanUp :: clearing pingTimer"), this.pingTimer.clear(), this.pingTimer = null), t && !this.connected && (y("_cleanUp :: (%s) :: removing stream `done` callback `close` listener", this.options.clientId), this.stream.removeListener("close", t), t());
}, T.prototype._sendPacket = function (e, t, r) {
y("_sendPacket :: (%s) :: start", this.options.clientId), r = r || C, t = t || C;
const n = function (e, t) {
if (5 === e.options.protocolVersion && "publish" === t.cmd) {
let r;
t.properties && (r = t.properties.topicAlias);
const n = t.topic.toString();
if (e.topicAliasSend) {
if (r) {
if (0 !== n.length && (y("applyTopicAlias :: register topic: %s - alias: %d", n, r), !e.topicAliasSend.put(n, r))) return y("applyTopicAlias :: error out of range. topic: %s - alias: %d", n, r), new Error("Sending Topic Alias out of range");
} else 0 !== n.length && (e.options.autoAssignTopicAlias ? (r = e.topicAliasSend.getAliasByTopic(n)) ? (t.topic = "", t.properties = {
...t.properties,
topicAlias: r
}, y("applyTopicAlias :: auto assign(use) topic: %s - alias: %d", n, r)) : (r = e.topicAliasSend.getLruAlias(), e.topicAliasSend.put(n, r), t.properties = {
...t.properties,
topicAlias: r
}, y("applyTopicAlias :: auto assign topic: %s - alias: %d", n, r)) : e.options.autoUseTopicAlias && (r = e.topicAliasSend.getAliasByTopic(n)) && (t.topic = "", t.properties = {
...t.properties,
topicAlias: r
}, y("applyTopicAlias :: auto use topic: %s - alias: %d", n, r)));
} else if (r) return y("applyTopicAlias :: error out of range. topic: %s - alias: %d", n, r), new Error("Sending Topic Alias out of range");
}
}(this, e);
if (n) t(n);else {
if (!this.connected) return "auth" === e.cmd ? (this._shiftPingInterval(), void S(this, e, t)) : (y("_sendPacket :: client not connected. Storing packet offline."), void this._storePacket(e, t, r));
switch (this._shiftPingInterval(), e.cmd) {
case "publish":
break;
case "pubrel":
return void E(this, e, t, r);
default:
return void S(this, e, t);
}
switch (e.qos) {
case 2:
case 1:
E(this, e, t, r);
break;
case 0:
default:
S(this, e, t);
}
y("_sendPacket :: (%s) :: end", this.options.clientId);
}
}, T.prototype._storePacket = function (e, t, r) {
y("_storePacket :: packet: %o", e), y("_storePacket :: cb? %s", !!t), r = r || C;
let n = e;
if ("publish" === n.cmd) {
const r = k(this, n = p(e));
if (r) return t && t(r);
}
0 === (n.qos || 0) && this.queueQoSZero || "publish" !== n.cmd ? this.queue.push({
packet: n,
cb: t
}) : n.qos > 0 ? (t = this.outgoing[n.messageId] ? this.outgoing[n.messageId].cb : null, this.outgoingStore.put(n, function (e) {
if (e) return t && t(e);
r();
})) : t && t(new Error("No connection to broker"));
}, T.prototype._setupPingTimer = function () {
y("_setupPingTimer :: keepalive %d (seconds)", this.options.keepalive);
const e = this;
!this.pingTimer && this.options.keepalive && (this.pingResp = !0, this.pingTimer = f(function () {
e._checkPing();
}, 1e3 * this.options.keepalive));
}, T.prototype._shiftPingInterval = function () {
this.pingTimer && this.options.keepalive && this.options.reschedulePings && this.pingTimer.reschedule(1e3 * this.options.keepalive);
}, T.prototype._checkPing = function () {
y("_checkPing :: checking ping..."), this.pingResp ? (y("_checkPing :: ping response received. Clearing flag and sending `pingreq`"), this.pingResp = !1, this._sendPacket({
cmd: "pingreq"
})) : (y("_checkPing :: calling _cleanUp with force true"), this._cleanUp(!0));
}, T.prototype._handlePingresp = function () {
this.pingResp = !0;
}, T.prototype._handleConnack = function (e) {
y("_handleConnack");
const t = this.options,
r = 5 === t.protocolVersion ? e.reasonCode : e.returnCode;
if (clearTimeout(this.connackTimer), delete this.topicAliasSend, e.properties) {
if (e.properties.topicAliasMaximum) {
if (e.properties.topicAliasMaximum > 65535) return void this.emit("error", new Error("topicAliasMaximum from broker is out of range"));
e.properties.topicAliasMaximum > 0 && (this.topicAliasSend = new a(e.properties.topicAliasMaximum));
}
e.properties.serverKeepAlive && t.keepalive && (t.keepalive = e.properties.serverKeepAlive, this._shiftPingInterval()), e.properties.maximumPacketSize && (t.properties || (t.properties = {}), t.properties.maximumPacketSize = e.properties.maximumPacketSize);
}
if (0 === r) this.reconnecting = !1, this._onConnect(e);else if (r > 0) {
const e = new Error("Connection refused: " + _[r]);
e.code = r, this.emit("error", e);
}
}, T.prototype._handleAuth = function (e) {
const t = this.options.protocolVersion,
r = 5 === t ? e.reasonCode : e.returnCode;
if (5 !== t) {
const e = new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:" + t);
return e.code = r, void this.emit("error", e);
}
const n = this;
this.handleAuth(e, function (e, t) {
if (e) n.emit("error", e);else if (24 === r) n.reconnecting = !1, n._sendPacket(t);else {
const t = new Error("Connection refused: " + _[r]);
e.code = r, n.emit("error", t);
}
});
}, T.prototype.handleAuth = function (e, t) {
t();
}, T.prototype._handlePublish = function (e, t) {
y("_handlePublish: packet %o", e), t = void 0 !== t ? t : C;
let r = e.topic.toString();
const n = e.payload,
i = e.qos,
o = e.messageId,
s = this,
a = this.options,
l = [0, 16, 128, 131, 135, 144, 145, 151, 153];
if (5 === this.options.protocolVersion) {
let t;
if (e.properties && (t = e.properties.topicAlias), void 0 !== t) if (0 === r.length) {
if (!(t > 0 && t <= 65535)) return y("_handlePublish :: topic alias out of range. alias: %d", t), void this.emit("error", new Error("Received Topic Alias is out of range"));
{
const e = this.topicAliasRecv.getTopicByAlias(t);
if (!e) return y("_handlePublish :: unregistered topic alias. alias: %d", t), void this.emit("error", new Error("Received unregistered Topic Alias"));
y("_handlePublish :: topic complemented by alias. topic: %s - alias: %d", r = e, t);
}
} else {
if (!this.topicAliasRecv.put(r, t)) return y("_handlePublish :: topic alias out of range. alias: %d", t), void this.emit("error", new Error("Received Topic Alias is out of range"));
y("_handlePublish :: registered topic: %s - alias: %d", r, t);
}
}
switch (y("_handlePublish: qos %d", i), i) {
case 2:
a.customHandleAcks(r, n, e, function (r, n) {
return r instanceof Error || (n = r, r = null), r ? s.emit("error", r) : -1 === l.indexOf(n) ? s.emit("error", new Error("Wrong reason code for pubrec")) : void (n ? s._sendPacket({
cmd: "pubrec",
messageId: o,
reasonCode: n
}, t) : s.incomingStore.put(e, function () {
s._sendPacket({
cmd: "pubrec",
messageId: o
}, t);
}));
});
break;
case 1:
a.customHandleAcks(r, n, e, function (i, a) {
return i instanceof Error || (a = i, i = null), i ? s.emit("error", i) : -1 === l.indexOf(a) ? s.emit("error", new Error("Wrong reason code for puback")) : (a || s.emit("message", r, n, e), void s.handleMessage(e, function (e) {
if (e) return t && t(e);
s._sendPacket({
cmd: "puback",
messageId: o,
reasonCode: a
}, t);
}));
});
break;
case 0:
this.emit("message", r, n, e), this.handleMessage(e, t);
break;
default:
y("_handlePublish: unknown QoS. Doing nothing.");
}
}, T.prototype.handleMessage = function (e, t) {
t();
}, T.prototype._handleAck = function (e) {
const t = e.messageId,
r = e.cmd;
let n = null;
const i = this.outgoing[t] ? this.outgoing[t].cb : null,
o = this;
let s;
if (i) {
switch (y("_handleAck :: packet type", r), r) {
case "pubcomp":
case "puback":
{
const r = e.reasonCode;
r && r > 0 && 16 !== r && ((s = new Error("Publish error: " + _[r])).code = r, i(s, e)), delete this.outgoing[t], this.outgoingStore.del(e, i), this.messageIdProvider.deallocate(t), this._invokeStoreProcessingQueue();
break;
}
case "pubrec":
{
n = {
cmd: "pubrel",
qos: 2,
messageId: t
};
const r = e.reasonCode;
r && r > 0 && 16 !== r ? ((s = new Error("Publish error: " + _[r])).code = r, i(s, e)) : this._sendPacket(n);
break;
}
case "suback":
delete this.outgoing[t], this.messageIdProvider.deallocate(t);
for (let r = 0; r < e.granted.length; r++) if (0 != (128 & e.granted[r])) {
const e = this.messageIdToTopic[t];
e && e.forEach(function (e) {
delete o._resubscribeTopics[e];
});
}
this._invokeStoreProcessingQueue(), i(null, e);
break;
case "unsuback":
delete this.outgoing[t], this.messageIdProvider.deallocate(t), this._invokeStoreProcessingQueue(), i(null);
break;
default:
o.emit("error", new Error("unrecognized packet type"));
}
this.disconnecting && 0 === Object.keys(this.outgoing).length && this.emit("outgoingEmpty");
} else y("_handleAck :: Server sent an ack in error. Ignoring.");
}, T.prototype._handlePubrel = function (e, t) {
y("handling pubrel packet"), t = void 0 !== t ? t : C;
const r = this,
n = {
cmd: "pubcomp",
messageId: e.messageId
};
r.incomingStore.get(e, function (e, i) {
e ? r._sendPacket(n, t) : (r.emit("message", i.topic, i.payload, i), r.handleMessage(i, function (e) {
if (e) return t(e);
r.incomingStore.del(i, C), r._sendPacket(n, t);
}));
});
}, T.prototype._handleDisconnect = function (e) {
this.emit("disconnect", e);
}, T.prototype._nextId = function () {
return this.messageIdProvider.allocate();
}, T.prototype.getLastMessageId = function () {
return this.messageIdProvider.getLastAllocated();
}, T.prototype._resubscribe = function () {
y("_resubscribe");
const e = Object.keys(this._resubscribeTopics);
if (!this._firstConnection && (this.options.clean || 5 === this.options.protocolVersion && !this.connackPacket.sessionPresent) && e.length > 0) if (this.options.resubscribe) {
if (5 === this.options.protocolVersion) {
y("_resubscribe: protocolVersion 5");
for (let t = 0; t < e.length; t++) {
const r = {};
r[e[t]] = this._resubscribeTopics[e[t]], r.resubscribe = !0, this.subscribe(r, {
properties: r[e[t]].properties
});
}
} else this._resubscribeTopics.resubscribe = !0, this.subscribe(this._resubscribeTopics);
} else this._resubscribeTopics = {};
this._firstConnection = !1;
}, T.prototype._onConnect = function (e) {
if (this.disconnected) return void this.emit("connect", e);
const t = this;
this.connackPacket = e, this.messageIdProvider.clear(), this._setupPingTimer(), this.connected = !0, function r() {
let n = t.outgoingStore.createStream();
function i() {
t._storeProcessing = !1, t._packetIdsDuringStoreProcessing = {};
}
function o() {
n.destroy(), n = null, t._flushStoreProcessingQueue(), i();
}
t.once("close", o), n.on("error", function (e) {
i(), t._flushStoreProcessingQueue(), t.removeListener("close", o), t.emit("error", e);
}), n.on("end", function () {
let n = !0;
for (const e in t._packetIdsDuringStoreProcessing) if (!t._packetIdsDuringStoreProcessing[e]) {
n = !1;
break;
}
n ? (i(), t.removeListener("close", o), t._invokeAllStoreProcessingQueue(), t.emit("connect", e)) : r();
}), function e() {
if (!n) return;
t._storeProcessing = !0;
const r = n.read(1);
let i;
r ? t._packetIdsDuringStoreProcessing[r.messageId] ? e() : t.disconnecting || t.reconnectTimer ? n.destroy && n.destroy() : (i = t.outgoing[r.messageId] ? t.outgoing[r.messageId].cb : null, t.outgoing[r.messageId] = {
volatile: !1,
cb: function (t, r) {
i && i(t, r), e();
}
}, t._packetIdsDuringStoreProcessing[r.messageId] = !0, t.messageIdProvider.register(r.messageId) ? t._sendPacket(r) : y("messageId: %d has already used.", r.messageId)) : n.once("readable", e);
}();
}();
}, T.prototype._invokeStoreProcessingQueue = function () {
if (this._storeProcessingQueue.length > 0) {
const e = this._storeProcessingQueue[0];
if (e && e.invoke()) return this._storeProcessingQueue.shift(), !0;
}
return !1;
}, T.prototype._invokeAllStoreProcessingQueue = function () {
for (; this._invokeStoreProcessingQueue(););
}, T.prototype._flushStoreProcessingQueue = function () {
for (const e of this._storeProcessingQueue) e.cbStorePut && e.cbStorePut(new Error("Connection closed")), e.callback && e.callback(new Error("Connection closed"));
this._storeProcessingQueue.splice(0);
}, t.exports = T;
}).call(this);
}).call(this, e("_process"), "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {
"./default-message-id-provider": 7,
"./store": 8,
"./topic-alias-recv": 9,
"./topic-alias-send": 10,
"./validations": 11,
_process: 50,
debug: 18,
events: 22,
inherits: 24,
"mqtt-packet": 40,
"readable-stream": 69,
reinterval: 70,
"rfdc/default": 71,
xtend: 81
}],
2: [function (e, t, r) {
const {
Buffer: n
} = e("buffer"),
i = e("readable-stream").Transform,
o = e("duplexify");
let s,
a,
l,
u = !1;
t.exports = function (e, t) {
if (t.hostname = t.hostname || t.host, !t.hostname) throw new Error("Could not determine host. Specify host manually.");
const r = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt";
!function (e) {
e.hostname || (e.hostname = "localhost"), e.path || (e.path = "/"), e.wsOptions || (e.wsOptions = {});
}(t);
const c = function (e, t) {
const r = "alis" === e.protocol ? "wss" : "ws";
let n = r + "://" + e.hostname + e.path;
return e.port && 80 !== e.port && 443 !== e.port && (n = r + "://" + e.hostname + ":" + e.port + e.path), "function" == typeof e.transformWsUrl && (n = e.transformWsUrl(n, e, t)), n;
}(t, e);
return (s = t.my).connectSocket({
url: c,
protocols: r
}), a = function () {
const e = new i();
return e._write = function (e, t, r) {
s.sendSocketMessage({
data: e.buffer,
success: function () {
r();
},
fail: function () {
r(new Error());
}
});
}, e._flush = function (e) {
s.closeSocket({
success: function () {
e();
}
});
}, e;
}(), l = o.obj(), u || (u = !0, s.onSocketOpen(function () {
l.setReadable(a), l.setWritable(a), l.emit("connect");
}), s.onSocketMessage(function (e) {
if ("string" == typeof e.data) {
const t = n.from(e.data, "base64");
a.push(t);
} else {
const t = new FileReader();
t.addEventListener("load", function () {
let e = t.result;
e = e instanceof ArrayBuffer ? n.from(e) : n.from(e, "utf8"), a.push(e);
}), t.readAsArrayBuffer(e.data);
}
}), s.onSocketClose(function () {
l.end(), l.destroy();
}), s.onSocketError(function (e) {
l.destroy(e);
})), l;
};
}, {
buffer: 17,
duplexify: 20,
"readable-stream": 69
}],
3: [function (e, t, r) {
const n = e("net"),
i = e("debug")("mqttjs:tcp");
t.exports = function (e, t) {
t.port = t.port || 1883, t.hostname = t.hostname || t.host || "localhost";
const r = t.port,
o = t.hostname;
return i("port %d and host %s", r, o), n.createConnection(r, o);
};
}, {
debug: 18,
net: 16
}],
4: [function (e, t, r) {
const n = e("tls"),
i = e("net"),
o = e("debug")("mqttjs:tls");
t.exports = function (e, t) {
t.port = t.port || 8883, t.host = t.hostname || t.host || "localhost", 0 === i.isIP(t.host) && (t.servername = t.host), t.rejectUnauthorized = !1 !== t.rejectUnauthorized, delete t.path, o("port %d host %s rejectUnauthorized %b", t.port, t.host, t.rejectUnauthorized);
const r = n.connect(t);
function s(n) {
t.rejectUnauthorized && e.emit("error", n), r.end();
}
return r.on("secureConnect", function () {
t.rejectUnauthorized && !r.authorized ? r.emit("error", new Error("TLS not authorized")) : r.removeListener("error", s);
}), r.on("error", s), r;
};
}, {
debug: 18,
net: 16,
tls: 16
}],
5: [function (e, t, r) {
(function (r) {
(function () {
const {
Buffer: n
} = e("buffer"),
i = e("ws"),
o = e("debug")("mqttjs:ws"),
s = e("duplexify"),
a = e("readable-stream").Transform,
l = ["rejectUnauthorized", "ca", "cert", "key", "pfx", "passphrase"],
u = void 0 !== r && "browser" === r.title || "function" == typeof __webpack_require__;
function c(e, t) {
let r = e.protocol + "://" + e.hostname + ":" + e.port + e.path;
return "function" == typeof e.transformWsUrl && (r = e.transformWsUrl(r, e, t)), r;
}
function h(e) {
const t = e;
return e.hostname || (t.hostname = "localhost"), e.port || ("wss" === e.protocol ? t.port = 443 : t.port = 80), e.path || (t.path = "/"), e.wsOptions || (t.wsOptions = {}), u || "wss" !== e.protocol || l.forEach(function (r) {
Object.prototype.hasOwnProperty.call(e, r) && !Object.prototype.hasOwnProperty.call(e.wsOptions, r) && (t.wsOptions[r] = e[r]);
}), t;
}
t.exports = u ? function (e, t) {
let r;
o("browserStreamBuilder");
const i = function (e) {
const t = h(e);
if (t.hostname || (t.hostname = t.host), !t.hostname) {
if ("undefined" == typeof document) throw new Error("Could not determine host. Specify host manually.");
const e = new URL(document.URL);
t.hostname = e.hostname, t.port || (t.port = e.port);
}
return void 0 === t.objectMode && (t.objectMode = !(!0 === t.binary || void 0 === t.binary)), t;
}(t).browserBufferSize || 524288,
l = t.browserBufferTimeout || 1e3,
u = !t.objectMode,
f = function (e, t) {
const r = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt",
n = c(t, e),
i = new WebSocket(n, [r]);
return i.binaryType = "arraybuffer", i;
}(e, t),
p = function (e, t, r) {
const n = new a({
objectModeMode: e.objectMode
});
return n._write = t, n._flush = r, n;
}(t, function e(t, r, o) {
f.bufferedAmount > i && setTimeout(e, l, t, r, o), u && "string" == typeof t && (t = n.from(t, "utf8"));
try {
f.send(t);
} catch (e) {
return o(e);
}
o();
}, function (e) {
f.close(), e();
});
t.objectMode || (p._writev = v), p.on("close", () => {
f.close();
});
const d = void 0 !== f.addEventListener;
function g() {
r.setReadable(p), r.setWritable(p), r.emit("connect");
}
function y() {
r.end(), r.destroy();
}
function b(e) {
r.destroy(e);
}
function m(e) {
let t = e.data;
t = t instanceof ArrayBuffer ? n.from(t) : n.from(t, "utf8"), p.push(t);
}
function v(e, t) {
const r = new Array(e.length);
for (let t = 0; t < e.length; t++) "string" == typeof e[t].chunk ? r[t] = n.from(e[t], "utf8") : r[t] = e[t].chunk;
this._write(n.concat(r), "binary", t);
}
return f.readyState === f.OPEN ? r = p : (r = r = s(void 0, void 0, t), t.objectMode || (r._writev = v), d ? f.addEventListener("open", g) : f.onopen = g), r.socket = f, d ? (f.addEventListener("close", y), f.addEventListener("error", b), f.addEventListener("message", m)) : (f.onclose = y, f.onerror = b, f.onmessage = m), r;
} : function (e, t) {
o("streamBuilder");
const r = h(t),
n = c(r, e),
s = function (e, t, r) {
o("createWebSocket"), o("protocol: " + r.protocolId + " " + r.protocolVersion);
const n = "MQIsdp" === r.protocolId && 3 === r.protocolVersion ? "mqttv3.1" : "mqtt";
return o("creating new Websocket for url: " + t + " and protocol: " + n), new i(t, [n], r.wsOptions);
}(0, n, r),
a = i.createWebSocketStream(s, r.wsOptions);
return a.url = n, s.on("close", () => {
a.destroy();
}), a;
};
}).call(this);
}).call(this, e("_process"));
}, {
_process: 50,
buffer: 17,
debug: 18,
duplexify: 20,
"readable-stream": 69,
ws: 80
}],
6: [function (e, t, r) {
const {
Buffer: n
} = e("buffer"),
i = e("readable-stream").Transform,
o = e("duplexify");
let s, a, l;
t.exports = function (e, t) {
if (t.hostname = t.hostname || t.host, !t.hostname) throw new Error("Could not determine host. Specify host manually.");
const r = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt";
!function (e) {
e.hostname || (e.hostname = "localhost"), e.path || (e.path = "/"), e.wsOptions || (e.wsOptions = {});
}(t);
const u = function (e, t) {
const r = "wxs" === e.protocol ? "wss" : "ws";
let n = r + "://" + e.hostname + e.path;
return e.port && 80 !== e.port && 443 !== e.port && (n = r + "://" + e.hostname + ":" + e.port + e.path), "function" == typeof e.transformWsUrl && (n = e.transformWsUrl(n, e, t)), n;
}(t, e);
s = wx.connectSocket({
url: u,
protocols: [r]
}), a = function () {
const e = new i();
return e._write = function (e, t, r) {
s.send({
data: e.buffer,
success: function () {
r();
},
fail: function (e) {
r(new Error(e));
}
});
}, e._flush = function (e) {
s.close({
success: function () {
e();
}
});
}, e;
}(), (l = o.obj())._destroy = function (e, t) {
s.close({
success: function () {
t && t(e);
}
});
};
const c = l.destroy;
return l.destroy = function () {
l.destroy = c;
const e = this;
setTimeout(function () {
s.close({
fail: function () {
e._destroy(new Error());
}
});
}, 0);
}.bind(l), s.onOpen(function () {
l.setReadable(a), l.setWritable(a), l.emit("connect");
}), s.onMessage(function (e) {
let t = e.data;
t = t instanceof ArrayBuffer ? n.from(t) : n.from(t, "utf8"), a.push(t);
}), s.onClose(function () {
l.end(), l.destroy();
}), s.onError(function (e) {
l.destroy(new Error(e.errMsg));
}), l;
};
}, {
buffer: 17,
duplexify: 20,
"readable-stream": 69
}],
7: [function (e, t, r) {
function n() {
if (!(this instanceof n)) return new n();
this.nextId = Math.max(1, Math.floor(65535 * Math.random()));
}
n.prototype.allocate = function () {
const e = this.nextId++;
return 65536 === this.nextId && (this.nextId = 1), e;
}, n.prototype.getLastAllocated = function () {
return 1 === this.nextId ? 65535 : this.nextId - 1;
}, n.prototype.register = function (e) {
return !0;
}, n.prototype.deallocate = function (e) {}, n.prototype.clear = function () {}, t.exports = n;
}, {}],
8: [function (e, t, r) {
const n = e("xtend"),
i = e("readable-stream").Readable,
o = {
objectMode: !0
},
s = {
clean: !0
};
function a(e) {
if (!(this instanceof a)) return new a(e);
this.options = e || {}, this.options = n(s, e), this._inflights = new Map();
}
a.prototype.put = function (e, t) {
return this._inflights.set(e.messageId, e), t && t(), this;
}, a.prototype.createStream = function () {
const e = new i(o),
t = [];
let r = !1,
n = 0;
return this._inflights.forEach(function (e, r) {
t.push(e);
}), e._read = function () {
!r && n < t.length ? this.push(t[n++]) : this.push(null);
}, e.destroy = function () {
if (r) return;
const e = this;
r = !0, setTimeout(function () {
e.emit("close");
}, 0);
}, e;
}, a.prototype.del = function (e, t) {
return (e = this._inflights.get(e.messageId)) ? (this._inflights.delete(e.messageId), t(null, e)) : t && t(new Error("missing packet")), this;
}, a.prototype.get = function (e, t) {
return (e = this._inflights.get(e.messageId)) ? t(null, e) : t && t(new Error("missing packet")), this;
}, a.prototype.close = function (e) {
this.options.clean && (this._inflights = null), e && e();
}, t.exports = a;
}, {
"readable-stream": 69,
xtend: 81
}],
9: [function (e, t, r) {
function n(e) {
if (!(this instanceof n)) return new n(e);
this.aliasToTopic = {}, this.max = e;
}
n.prototype.put = function (e, t) {
return !(0 === t || t > this.max) && (this.aliasToTopic[t] = e, this.length = Object.keys(this.aliasToTopic).length, !0);
}, n.prototype.getTopicByAlias = function (e) {
return this.aliasToTopic[e];
}, n.prototype.clear = function () {
this.aliasToTopic = {};
}, t.exports = n;
}, {}],
10: [function (e, t, r) {
const n = e("lru-cache"),
i = e("number-allocator").NumberAllocator;
function o(e) {
if (!(this instanceof o)) return new o(e);
e > 0 && (this.aliasToTopic = new n({
max: e
}), this.topicToAlias = {}, this.numberAllocator = new i(1, e), this.max = e, this.length = 0);
}
o.prototype.put = function (e, t) {
if (0 === t || t > this.max) return !1;
const r = this.aliasToTopic.get(t);
return r && delete this.topicToAlias[r], this.aliasToTopic.set(t, e), this.topicToAlias[e] = t, this.numberAllocator.use(t), this.length = this.aliasToTopic.length, !0;
}, o.prototype.getTopicByAlias = function (e) {
return this.aliasToTopic.get(e);
}, o.prototype.getAliasByTopic = function (e) {
const t = this.topicToAlias[e];
return void 0 !== t && this.aliasToTopic.get(t), t;
}, o.prototype.clear = function () {
this.aliasToTopic.reset(), this.topicToAlias = {}, this.numberAllocator.clear(), this.length = 0;
}, o.prototype.getLruAlias = function () {
const e = this.numberAllocator.firstVacant();
return e || this.aliasToTopic.keys()[this.aliasToTopic.length - 1];
}, t.exports = o;
}, {
"lru-cache": 37,
"number-allocator": 46
}],
11: [function (e, t, r) {
function n(e) {
const t = e.split("/");
for (let e = 0; e < t.length; e++) if ("+" !== t[e]) {
if ("#" === t[e]) return e === t.length - 1;
if (-1 !== t[e].indexOf("+") || -1 !== t[e].indexOf("#")) return !1;
}
return !0;
}
t.exports = {
validateTopics: function (e) {
if (0 === e.length) return "empty_topic_list";
for (let t = 0; t < e.length; t++) if (!n(e[t])) return e[t];
return null;
}
};
}, {}],
12: [function (e, t, r) {
(function (r) {
(function () {
const n = e("../client"),
i = e("../store"),
o = e("url"),
s = e("xtend"),
a = e("debug")("mqttjs"),
l = {};
function u(e, t) {
if (a("connecting to an MQTT broker..."), "object" != typeof e || t || (t = e, e = null), t = t || {}, e) {
const r = o.parse(e, !0);
if (null != r.port && (r.port = Number(r.port)), null === (t = s(r, t)).protocol) throw new Error("Missing protocol");
t.protocol = t.protocol.replace(/:$/, "");
}
if (function (e) {
let t;
e.auth && ((t = e.auth.match(/^(.+):(.+)$/)) ? (e.username = t[1], e.password = t[2]) : e.username = e.auth);
}(t), t.query && "string" == typeof t.query.clientId && (t.clientId = t.query.clientId), t.cert && t.key) {
if (!t.protocol) throw new Error("Missing secure protocol key");
if (-1 === ["mqtts", "wss", "wxs", "alis"].indexOf(t.protocol)) switch (t.protocol) {
case "mqtt":
t.protocol = "mqtts";
break;
case "ws":
t.protocol = "wss";
break;
case "wx":
t.protocol = "wxs";
break;
case "ali":
t.protocol = "alis";
break;
default:
throw new Error('Unknown protocol for secure connection: "' + t.protocol + '"!');
}
}
if (!l[t.protocol]) {
const e = -1 !== ["mqtts", "wss"].indexOf(t.protocol);
t.protocol = ["mqtt", "mqtts", "ws", "wss", "wx", "wxs", "ali", "alis"].filter(function (t, r) {
return (!e || r % 2 != 0) && "function" == typeof l[t];
})[0];
}
if (!1 === t.clean && !t.clientId) throw new Error("Missing clientId for unclean clients");
t.protocol && (t.defaultProtocol = t.protocol);
const r = new n(function (e) {
return t.servers && (e._reconnectCount && e._reconnectCount !== t.servers.length || (e._reconnectCount = 0), t.host = t.servers[e._reconnectCount].host, t.port = t.servers[e._reconnectCount].port, t.protocol = t.servers[e._reconnectCount].protocol ? t.servers[e._reconnectCount].protocol : t.defaultProtocol, t.hostname = t.host, e._reconnectCount++), a("calling streambuilder for", t.protocol), l[t.protocol](e, t);
}, t);
return r.on("error", function () {}), r;
}
void 0 !== r && "browser" !== r.title || "function" != typeof __webpack_require__ ? (l.mqtt = e("./tcp"), l.tcp = e("./tcp"), l.ssl = e("./tls"), l.tls = e("./tls"), l.mqtts = e("./tls")) : (l.wx = e("./wx"), l.wxs = e("./wx"), l.ali = e("./ali"), l.alis = e("./ali")), l.ws = e("./ws"), l.wss = e("./ws"), t.exports = u, t.exports.connect = u, t.exports.MqttClient = n, t.exports.Store = i;
}).call(this);
}).call(this, e("_process"));
}, {
"../client": 1,
"../store": 8,
"./ali": 2,
"./tcp": 3,
"./tls": 4,
"./ws": 5,
"./wx": 6,
_process: 50,
debug: 18,
url: 76,
xtend: 81
}],
13: [function (e, t, r) {
r.byteLength = function (e) {
var t = u(e),
r = t[0],
n = t[1];
return 3 * (r + n) / 4 - n;
}, r.toByteArray = function (e) {
var t,
r,
n = u(e),
s = n[0],
a = n[1],
l = new o(function (e, t, r) {
return 3 * (t + r) / 4 - r;
}(0, s, a)),
c = 0,
h = a > 0 ? s - 4 : s;
for (r = 0; r < h; r += 4) t = i[e.charCodeAt(r)] << 18 | i[e.charCodeAt(r + 1)] << 12 | i[e.charCodeAt(r + 2)] << 6 | i[e.charCodeAt(r + 3)], l[c++] = t >> 16 & 255, l[c++] = t >> 8 & 255, l[c++] = 255 & t;
2 === a && (t = i[e.charCodeAt(r)] << 2 | i[e.charCodeAt(r + 1)] >> 4, l[c++] = 255 & t);
1 === a && (t = i[e.charCodeAt(r)] << 10 | i[e.charCodeAt(r + 1)] << 4 | i[e.charCodeAt(r + 2)] >> 2, l[c++] = t >> 8 & 255, l[c++] = 255 & t);
return l;
}, r.fromByteArray = function (e) {
for (var t, r = e.length, i = r % 3, o = [], s = 0, a = r - i; s < a; s += 16383) o.push(c(e, s, s + 16383 > a ? a : s + 16383));
1 === i ? (t = e[r - 1], o.push(n[t >> 2] + n[t << 4 & 63] + "==")) : 2 === i && (t = (e[r - 2] << 8) + e[r - 1], o.push(n[t >> 10] + n[t >> 4 & 63] + n[t << 2 & 63] + "="));
return o.join("");
};
for (var n = [], i = [], o = "undefined" != typeof Uint8Array ? Uint8Array : Array, s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", a = 0, l = s.length; a < l; ++a) n[a] = s[a], i[s.charCodeAt(a)] = a;
function u(e) {
var t = e.length;
if (t % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
var r = e.indexOf("=");
return -1 === r && (r = t), [r, r === t ? 0 : 4 - r % 4];
}
function c(e, t, r) {
for (var i, o, s = [], a = t; a < r; a += 3) i = (e[a] << 16 & 16711680) + (e[a + 1] << 8 & 65280) + (255 & e[a + 2]), s.push(n[(o = i) >> 18 & 63] + n[o >> 12 & 63] + n[o >> 6 & 63] + n[63 & o]);
return s.join("");
}
i["-".charCodeAt(0)] = 62, i["_".charCodeAt(0)] = 63;
}, {}],
14: [function (e, t, r) {
const {
Buffer: n
} = e("buffer"),
i = Symbol.for("BufferList");
function o(e) {
if (!(this instanceof o)) return new o(e);
o._init.call(this, e);
}
o._init = function (e) {
Object.defineProperty(this, i, {
value: !0
}), this._bufs = [], this.length = 0, e && this.append(e);
}, o.prototype._new = function (e) {
return new o(e);
}, o.prototype._offset = function (e) {
if (0 === e) return [0, 0];
let t = 0;
for (let r = 0; r < this._bufs.length; r++) {
const n = t + this._bufs[r].length;
if (e < n || r === this._bufs.length - 1) return [r, e - t];
t = n;
}
}, o.prototype._reverseOffset = function (e) {
const t = e[0];
let r = e[1];
for (let e = 0; e < t; e++) r += this._bufs[e].length;
return r;
}, o.prototype.get = function (e) {
if (e > this.length || e < 0) return;
const t = this._offset(e);
return this._bufs[t[0]][t[1]];
}, o.prototype.slice = function (e, t) {
return "number" == typeof e && e < 0 && (e += this.length), "number" == typeof t && t < 0 && (t += this.length), this.copy(null, 0, e, t);
}, o.prototype.copy = function (e, t, r, i) {
if (("number" != typeof r || r < 0) && (r = 0), ("number" != typeof i || i > this.length) && (i = this.length), r >= this.length) return e || n.alloc(0);
if (i <= 0) return e || n.alloc(0);
const o = !!e,
s = this._offset(r),
a = i - r;
let l = a,
u = o && t || 0,
c = s[1];
if (0 === r && i === this.length) {
if (!o) return 1 === this._bufs.length ? this._bufs[0] : n.concat(this._bufs, this.length);
for (let t = 0; t < this._bufs.length; t++) this._bufs[t].copy(e, u), u += this._bufs[t].length;
return e;
}
if (l <= this._bufs[s[0]].length - c) return o ? this._bufs[s[0]].copy(e, t, c, c + l) : this._bufs[s[0]].slice(c, c + l);
o || (e = n.allocUnsafe(a));
for (let t = s[0]; t < this._bufs.length; t++) {
const r = this._bufs[t].length - c;
if (!(l > r)) {
this._bufs[t].copy(e, u, c, c + l), u += r;
break;
}
this._bufs[t].copy(e, u, c), u += r, l -= r, c && (c = 0);
}
return e.length > u ? e.slice(0, u) : e;
}, o.prototype.shallowSlice = function (e, t) {
if (e = e || 0, t = "number" != typeof t ? this.length : t, e < 0 && (e += this.length), t < 0 && (t += this.length), e === t) return this._new();
const r = this._offset(e),
n = this._offset(t),
i = this._bufs.slice(r[0], n[0] + 1);
return 0 === n[1] ? i.pop() : i[i.length - 1] = i[i.length - 1].slice(0, n[1]), 0 !== r[1] && (i[0] = i[0].slice(r[1])), this._new(i);
}, o.prototype.toString = function (e, t, r) {
return this.slice(t, r).toString(e);
}, o.prototype.consume = function (e) {
if (e = Math.trunc(e), Number.isNaN(e) || e <= 0) return this;
for (; this._bufs.length;) {
if (!(e >= this._bufs[0].length)) {
this._bufs[0] = this._bufs[0].slice(e), this.length -= e;
break;
}
e -= this._bufs[0].length, this.length -= this._bufs[0].length, this._bufs.shift();
}
return this;
}, o.prototype.duplicate = function () {
const e = this._new();
for (let t = 0; t < this._bufs.length; t++) e.append(this._bufs[t]);
return e;
}, o.prototype.append = function (e) {
if (null == e) return this;
if (e.buffer) this._appendBuffer(n.from(e.buffer, e.byteOffset, e.byteLength));else if (Array.isArray(e)) for (let t = 0; t < e.length; t++) this.append(e[t]);else if (this._isBufferList(e)) for (let t = 0; t < e._bufs.length; t++) this.append(e._bufs[t]);else "number" == typeof e && (e = e.toString()), this._appendBuffer(n.from(e));
return this;
}, o.prototype._appendBuffer = function (e) {
this._bufs.push(e), this.length += e.length;
}, o.prototype.indexOf = function (e, t, r) {
if (void 0 === r && "string" == typeof t && (r = t, t = void 0), "function" == typeof e || Array.isArray(e)) throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');
if ("number" == typeof e ? e = n.from([e]) : "string" == typeof e ? e = n.from(e, r) : this._isBufferList(e) ? e = e.slice() : Array.isArray(e.buffer) ? e = n.from(e.buffer, e.byteOffset, e.byteLength) : n.isBuffer(e) || (e = n.from(e)), t = Number(t || 0), isNaN(t) && (t = 0), t < 0 && (t = this.length + t), t < 0 && (t = 0), 0 === e.length) return t > this.length ? this.length : t;
const i = this._offset(t);
let o = i[0],
s = i[1];
for (; o < this._bufs.length; o++) {
const t = this._bufs[o];
for (; s < t.length;) {
if (t.length - s >= e.length) {
const r = t.indexOf(e, s);
if (-1 !== r) return this._reverseOffset([o, r]);
s = t.length - e.length + 1;
} else {
const t = this._reverseOffset([o, s]);
if (this._match(t, e)) return t;
s++;
}
}
s = 0;
}
return -1;
}, o.prototype._match = function (e, t) {
if (this.length - e < t.length) return !1;
for (let r = 0; r < t.length; r++) if (this.get(e + r) !== t[r]) return !1;
return !0;
}, function () {
const e = {
readDoubleBE: 8,
readDoubleLE: 8,
readFloatBE: 4,
readFloatLE: 4,
readInt32BE: 4,
readInt32LE: 4,
readUInt32BE: 4,
readUInt32LE: 4,
readInt16BE: 2,
readInt16LE: 2,
readUInt16BE: 2,
readUInt16LE: 2,
readInt8: 1,
readUInt8: 1,
readIntBE: null,
readIntLE: null,
readUIntBE: null,
readUIntLE: null
};
for (const t in e) !function (t) {
o.prototype[t] = null === e[t] ? function (e, r) {
return this.slice(e, e + r)[t](0, r);
} : function (r = 0) {
return this.slice(r, r + e[t])[t](0);
};
}(t);
}(), o.prototype._isBufferList = function (e) {
return e instanceof o || o.isBufferList(e);
}, o.isBufferList = function (e) {
return null != e && e[i];
}, t.exports = o;
}, {
buffer: 17
}],
15: [function (e, t, r) {
const n = e("readable-stream").Duplex,
i = e("inherits"),
o = e("./BufferList");
function s(e) {
if (!(this instanceof s)) return new s(e);
if ("function" == typeof e) {
this._callback = e;
const t = function (e) {
this._callback && (this._callback(e), this._callback = null);
}.bind(this);
this.on("pipe", function (e) {
e.on("error", t);
}), this.on("unpipe", function (e) {
e.removeListener("error", t);
}), e = null;
}
o._init.call(this, e), n.call(this);
}
i(s, n), Object.assign(s.prototype, o.prototype), s.prototype._new = function (e) {
return new s(e);
}, s.prototype._write = function (e, t, r) {
this._appendBuffer(e), "function" == typeof r && r();
}, s.prototype._read = function (e) {
if (!this.length) return this.push(null);
e = Math.min(e, this.length), this.push(this.slice(0, e)), this.consume(e);
}, s.prototype.end = function (e) {
n.prototype.end.call(this, e), this._callback && (this._callback(null, this.slice()), this._callback = null);
}, s.prototype._destroy = function (e, t) {
this._bufs.length = 0, this.length = 0, t(e);
}, s.prototype._isBufferList = function (e) {
return e instanceof s || e instanceof o || s.isBufferList(e);
}, s.isBufferList = o.isBufferList, t.exports = s, t.exports.BufferListStream = s, t.exports.BufferList = o;
}, {
"./BufferList": 14,
inherits: 24,
"readable-stream": 69
}],
16: [function (e, t, r) {}, {}],
17: [function (e, t, r) {
(function (t) {
(function () {
var t = e("base64-js"),
n = e("ieee754");
r.Buffer = s, r.SlowBuffer = function (e) {
+e != e && (e = 0);
return s.alloc(+e);
}, r.INSPECT_MAX_BYTES = 50;
var i = 2147483647;
function o(e) {
if (e > i) throw new RangeError('The value "' + e + '" is invalid for option "size"');
var t = new Uint8Array(e);
return t.__proto__ = s.prototype, t;
}
function s(e, t, r) {
if ("number" == typeof e) {
if ("string" == typeof t) throw new TypeError('The "string" argument must be of type string. Received type number');
return u(e);
}
return a(e, t, r);
}
function a(e, t, r) {
if ("string" == typeof e) return function (e, t) {
"string" == typeof t && "" !== t || (t = "utf8");
if (!s.isEncoding(t)) throw new TypeError("Unknown encoding: " + t);
var r = 0 | f(e, t),
n = o(r),
i = n.write(e, t);
i !== r && (n = n.slice(0, i));
return n;
}(e, t);
if (ArrayBuffer.isView(e)) return c(e);
if (null == e) throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e);
if (q(e, ArrayBuffer) || e && q(e.buffer, ArrayBuffer)) return function (e, t, r) {
if (t < 0 || e.byteLength < t) throw new RangeError('"offset" is outside of buffer bounds');
if (e.byteLength < t + (r || 0)) throw new RangeError('"length" is outside of buffer bounds');
var n;
n = void 0 === t && void 0 === r ? new Uint8Array(e) : void 0 === r ? new Uint8Array(e, t) : new Uint8Array(e, t, r);
return n.__proto__ = s.prototype, n;
}(e, t, r);
if ("number" == typeof e) throw new TypeError('The "value" argument must not be of type number. Received type number');
var n = e.valueOf && e.valueOf();
if (null != n && n !== e) return s.from(n, t, r);
var i = function (e) {
if (s.isBuffer(e)) {
var t = 0 | h(e.length),
r = o(t);
return 0 === r.length ? r : (e.copy(r, 0, 0, t), r);
}
if (void 0 !== e.length) return "number" != typeof e.length || D(e.length) ? o(0) : c(e);
if ("Buffer" === e.type && Array.isArray(e.data)) return c(e.data);
}(e);
if (i) return i;
if ("undefined" != typeof Symbol && null != Symbol.toPrimitive && "function" == typeof e[Symbol.toPrimitive]) return s.from(e[Symbol.toPrimitive]("string"), t, r);
throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e);
}
function l(e) {
if ("number" != typeof e) throw new TypeError('"size" argument must be of type number');
if (e < 0) throw new RangeError('The value "' + e + '" is invalid for option "size"');
}
function u(e) {
return l(e), o(e < 0 ? 0 : 0 | h(e));
}
function c(e) {
for (var t = e.length < 0 ? 0 : 0 | h(e.length), r = o(t), n = 0; n < t; n += 1) r[n] = 255 & e[n];
return r;
}
function h(e) {
if (e >= i) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + i.toString(16) + " bytes");
return 0 | e;
}
function f(e, t) {
if (s.isBuffer(e)) return e.length;
if (ArrayBuffer.isView(e) || q(e, ArrayBuffer)) return e.byteLength;
if ("string" != typeof e) throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e);
var r = e.length,
n = arguments.length > 2 && !0 === arguments[2];
if (!n && 0 === r) return 0;
for (var i = !1;;) switch (t) {
case "ascii":
case "latin1":
case "binary":
return r;
case "utf8":
case "utf-8":
return L(e).length;
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return 2 * r;
case "hex":
return r >>> 1;
case "base64":
return j(e).length;
default:
if (i) return n ? -1 : L(e).length;
t = ("" + t).toLowerCase(), i = !0;
}
}
function p(e, t, r) {
var n = e[t];
e[t] = e[r], e[r] = n;
}
function d(e, t, r, n, i) {
if (0 === e.length) return -1;
if ("string" == typeof r ? (n = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), D(r = +r) && (r = i ? 0 : e.length - 1), r < 0 && (r = e.length + r), r >= e.length) {
if (i) return -1;
r = e.length - 1;
} else if (r < 0) {
if (!i) return -1;
r = 0;
}
if ("string" == typeof t && (t = s.from(t, n)), s.isBuffer(t)) return 0 === t.length ? -1 : g(e, t, r, n, i);
if ("number" == typeof t) return t &= 255, "function" == typeof Uint8Array.prototype.indexOf ? i ? Uint8Array.prototype.indexOf.call(e, t, r) : Uint8Array.prototype.lastIndexOf.call(e, t, r) : g(e, [t], r, n, i);
throw new TypeError("val must be string, number or Buffer");
}
function g(e, t, r, n, i) {
var o,
s = 1,
a = e.length,
l = t.length;
if (void 0 !== n && ("ucs2" === (n = String(n).toLowerCase()) || "ucs-2" === n || "utf16le" === n || "utf-16le" === n)) {
if (e.length < 2 || t.length < 2) return -1;
s = 2, a /= 2, l /= 2, r /= 2;
}
function u(e, t) {
return 1 === s ? e[t] : e.readUInt16BE(t * s);
}
if (i) {
var c = -1;
for (o = r; o < a; o++) if (u(e, o) === u(t, -1 === c ? 0 : o - c)) {
if (-1 === c && (c = o), o - c + 1 === l) return c * s;
} else -1 !== c && (o -= o - c), c = -1;
} else for (r + l > a && (r = a - l), o = r; o >= 0; o--) {
for (var h = !0, f = 0; f < l; f++) if (u(e, o + f) !== u(t, f)) {
h = !1;
break;
}
if (h) return o;
}
return -1;
}
function y(e, t, r, n) {
r = Number(r) || 0;
var i = e.length - r;
n ? (n = Number(n)) > i && (n = i) : n = i;
var o = t.length;
n > o / 2 && (n = o / 2);
for (var s = 0; s < n; ++s) {
var a = parseInt(t.substr(2 * s, 2), 16);
if (D(a)) return s;
e[r + s] = a;
}
return s;
}
function b(e, t, r, n) {
return U(L(t, e.length - r), e, r, n);
}
function m(e, t, r, n) {
return U(function (e) {
for (var t = [], r = 0; r < e.length; ++r) t.push(255 & e.charCodeAt(r));
return t;
}(t), e, r, n);
}
function v(e, t, r, n) {
return m(e, t, r, n);
}
function w(e, t, r, n) {
return U(j(t), e, r, n);
}
function _(e, t, r, n) {
return U(function (e, t) {
for (var r, n, i, o = [], s = 0; s < e.length && !((t -= 2) < 0); ++s) r = e.charCodeAt(s), n = r >> 8, i = r % 256, o.push(i), o.push(n);
return o;
}(t, e.length - r), e, r, n);
}
function k(e, r, n) {
return 0 === r && n === e.length ? t.fromByteArray(e) : t.fromByteArray(e.slice(r, n));
}
function S(e, t, r) {
r = Math.min(e.length, r);
for (var n = [], i = t; i < r;) {
var o,
s,
a,
l,
u = e[i],
c = null,
h = u > 239 ? 4 : u > 223 ? 3 : u > 191 ? 2 : 1;
if (i + h <= r) switch (h) {
case 1:
u < 128 && (c = u);
break;
case 2:
128 == (192 & (o = e[i + 1])) && (l = (31 & u) << 6 | 63 & o) > 127 && (c = l);
break;
case 3:
o = e[i + 1], s = e[i + 2], 128 == (192 & o) && 128 == (192 & s) && (l = (15 & u) << 12 | (63 & o) << 6 | 63 & s) > 2047 && (l < 55296 || l > 57343) && (c = l);
break;
case 4:
o = e[i + 1], s = e[i + 2], a = e[i + 3], 128 == (192 & o) && 128 == (192 & s) && 128 == (192 & a) && (l = (15 & u) << 18 | (63 & o) << 12 | (63 & s) << 6 | 63 & a) > 65535 && l < 1114112 && (c = l);
}
null === c ? (c = 65533, h = 1) : c > 65535 && (c -= 65536, n.push(c >>> 10 & 1023 | 55296), c = 56320 | 1023 & c), n.push(c), i += h;
}
return function (e) {
var t = e.length;
if (t <= E) return String.fromCharCode.apply(String, e);
var r = "",
n = 0;
for (; n < t;) r += String.fromCharCode.apply(String, e.slice(n, n += E));
return r;
}(n);
}
r.kMaxLength = i, s.TYPED_ARRAY_SUPPORT = function () {
try {
var e = new Uint8Array(1);
return e.__proto__ = {
__proto__: Uint8Array.prototype,
foo: function () {
return 42;
}
}, 42 === e.foo();
} catch (e) {
return !1;
}
}(), s.TYPED_ARRAY_SUPPORT || "undefined" == typeof console || "function" != typeof console.error || console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."), Object.defineProperty(s.prototype, "parent", {
enumerable: !0,
get: function () {
if (s.isBuffer(this)) return this.buffer;
}
}), Object.defineProperty(s.prototype, "offset", {
enumerable: !0,
get: function () {
if (s.isBuffer(this)) return this.byteOffset;
}
}), "undefined" != typeof Symbol && null != Symbol.species && s[Symbol.species] === s && Object.defineProperty(s, Symbol.species, {
value: null,
configurable: !0,
enumerable: !1,
writable: !1
}), s.poolSize = 8192, s.from = function (e, t, r) {
return a(e, t, r);
}, s.prototype.__proto__ = Uint8Array.prototype, s.__proto__ = Uint8Array, s.alloc = function (e, t, r) {
return function (e, t, r) {
return l(e), e <= 0 ? o(e) : void 0 !== t ? "string" == typeof r ? o(e).fill(t, r) : o(e).fill(t) : o(e);
}(e, t, r);
}, s.allocUnsafe = function (e) {
return u(e);
}, s.allocUnsafeSlow = function (e) {
return u(e);
}, s.isBuffer = function (e) {
return null != e && !0 === e._isBuffer && e !== s.prototype;
}, s.compare = function (e, t) {
if (q(e, Uint8Array) && (e = s.from(e, e.offset, e.byteLength)), q(t, Uint8Array) && (t = s.from(t, t.offset, t.byteLength)), !s.isBuffer(e) || !s.isBuffer(t)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
if (e === t) return 0;
for (var r = e.length, n = t.length, i = 0, o = Math.min(r, n); i < o; ++i) if (e[i] !== t[i]) {
r = e[i], n = t[i];
break;
}
return r < n ? -1 : n < r ? 1 : 0;
}, s.isEncoding = function (e) {
switch (String(e).toLowerCase()) {
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "latin1":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return !0;
default:
return !1;
}
}, s.concat = function (e, t) {
if (!Array.isArray(e)) throw new TypeError('"list" argument must be an Array of Buffers');
if (0 === e.length) return s.alloc(0);
var r;
if (void 0 === t) for (t = 0, r = 0; r < e.length; ++r) t += e[r].length;
var n = s.allocUnsafe(t),
i = 0;
for (r = 0; r < e.length; ++r) {
var o = e[r];
if (q(o, Uint8Array) && (o = s.from(o)), !s.isBuffer(o)) throw new TypeError('"list" argument must be an Array of Buffers');
o.copy(n, i), i += o.length;
}
return n;
}, s.byteLength = f, s.prototype._isBuffer = !0, s.prototype.swap16 = function () {
var e = this.length;
if (e % 2 != 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
for (var t = 0; t < e; t += 2) p(this, t, t + 1);
return this;
}, s.prototype.swap32 = function () {
var e = this.length;
if (e % 4 != 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
for (var t = 0; t < e; t += 4) p(this, t, t + 3), p(this, t + 1, t + 2);
return this;
}, s.prototype.swap64 = function () {
var e = this.length;
if (e % 8 != 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
for (var t = 0; t < e; t += 8) p(this, t, t + 7), p(this, t + 1, t + 6), p(this, t + 2, t + 5), p(this, t + 3, t + 4);
return this;
}, s.prototype.toString = function () {
var e = this.length;
return 0 === e ? "" : 0 === arguments.length ? S(this, 0, e) : function (e, t, r) {
var n = !1;
if ((void 0 === t || t < 0) && (t = 0), t > this.length) return "";
if ((void 0 === r || r > this.length) && (r = this.length), r <= 0) return "";
if ((r >>>= 0) <= (t >>>= 0)) return "";
for (e || (e = "utf8");;) switch (e) {
case "hex":
return x(this, t, r);
case "utf8":
case "utf-8":
return S(this, t, r);
case "ascii":
return C(this, t, r);
case "latin1":
case "binary":
return T(this, t, r);
case "base64":
return k(this, t, r);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return A(this, t, r);
default:
if (n) throw new TypeError("Unknown encoding: " + e);
e = (e + "").toLowerCase(), n = !0;
}
}.apply(this, arguments);
}, s.prototype.toLocaleString = s.prototype.toString, s.prototype.equals = function (e) {
if (!s.isBuffer(e)) throw new TypeError("Argument must be a Buffer");
return this === e || 0 === s.compare(this, e);
}, s.prototype.inspect = function () {
var e = "",
t = r.INSPECT_MAX_BYTES;
return e = this.toString("hex", 0, t).replace(/(.{2})/g, "$1 ").trim(), this.length > t && (e += " ... "), "<Buffer " + e + ">";
}, s.prototype.compare = function (e, t, r, n, i) {
if (q(e, Uint8Array) && (e = s.from(e, e.offset, e.byteLength)), !s.isBuffer(e)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof e);
if (void 0 === t && (t = 0), void 0 === r && (r = e ? e.length : 0), void 0 === n && (n = 0), void 0 === i && (i = this.length), t < 0 || r > e.length || n < 0 || i > this.length) throw new RangeError("out of range index");
if (n >= i && t >= r) return 0;
if (n >= i) return -1;
if (t >= r) return 1;
if (t >>>= 0, r >>>= 0, n >>>= 0, i >>>= 0, this === e) return 0;
for (var o = i - n, a = r - t, l = Math.min(o, a), u = this.slice(n, i), c = e.slice(t, r), h = 0; h < l; ++h) if (u[h] !== c[h]) {
o = u[h], a = c[h];
break;
}
return o < a ? -1 : a < o ? 1 : 0;
}, s.prototype.includes = function (e, t, r) {
return -1 !== this.indexOf(e, t, r);
}, s.prototype.indexOf = function (e, t, r) {
return d(this, e, t, r, !0);
}, s.prototype.lastIndexOf = function (e, t, r) {
return d(this, e, t, r, !1);
}, s.prototype.write = function (e, t, r, n) {
if (void 0 === t) n = "utf8", r = this.length, t = 0;else if (void 0 === r && "string" == typeof t) n = t, r = this.length, t = 0;else {
if (!isFinite(t)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
t >>>= 0, isFinite(r) ? (r >>>= 0, void 0 === n && (n = "utf8")) : (n = r, r = void 0);
}
var i = this.length - t;
if ((void 0 === r || r > i) && (r = i), e.length > 0 && (r < 0 || t < 0) || t > this.length) throw new RangeError("Attempt to write outside buffer bounds");
n || (n = "utf8");
for (var o = !1;;) switch (n) {
case "hex":
return y(this, e, t, r);
case "utf8":
case "utf-8":
return b(this, e, t, r);
case "ascii":
return m(this, e, t, r);
case "latin1":
case "binary":
return v(this, e, t, r);
case "base64":
return w(this, e, t, r);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return _(this, e, t, r);
default:
if (o) throw new TypeError("Unknown encoding: " + n);
n = ("" + n).toLowerCase(), o = !0;
}
}, s.prototype.toJSON = function () {
return {
type: "Buffer",
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
var E = 4096;
function C(e, t, r) {
var n = "";
r = Math.min(e.length, r);
for (var i = t; i < r; ++i) n += String.fromCharCode(127 & e[i]);
return n;
}
function T(e, t, r) {
var n = "";
r = Math.min(e.length, r);
for (var i = t; i < r; ++i) n += String.fromCharCode(e[i]);
return n;
}
function x(e, t, r) {
var n = e.length;
(!t || t < 0) && (t = 0), (!r || r < 0 || r > n) && (r = n);
for (var i = "", o = t; o < r; ++o) i += N(e[o]);
return i;
}
function A(e, t, r) {
for (var n = e.slice(t, r), i = "", o = 0; o < n.length; o += 2) i += String.fromCharCode(n[o] + 256 * n[o + 1]);
return i;
}
function I(e, t, r) {
if (e % 1 != 0 || e < 0) throw new RangeError("offset is not uint");
if (e + t > r) throw new RangeError("Trying to access beyond buffer length");
}
function P(e, t, r, n, i, o) {
if (!s.isBuffer(e)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (t > i || t < o) throw new RangeError('"value" argument is out of bounds');
if (r + n > e.length) throw new RangeError("Index out of range");
}
function O(e, t, r, n, i, o) {
if (r + n > e.length) throw new RangeError("Index out of range");
if (r < 0) throw new RangeError("Index out of range");
}
function B(e, t, r, i, o) {
return t = +t, r >>>= 0, o || O(e, 0, r, 4), n.write(e, t, r, i, 23, 4), r + 4;
}
function R(e, t, r, i, o) {
return t = +t, r >>>= 0, o || O(e, 0, r, 8), n.write(e, t, r, i, 52, 8), r + 8;
}
s.prototype.slice = function (e, t) {
var r = this.length;
e = ~~e, t = void 0 === t ? r : ~~t, e < 0 ? (e += r) < 0 && (e = 0) : e > r && (e = r), t < 0 ? (t += r) < 0 && (t = 0) : t > r && (t = r), t < e && (t = e);
var n = this.subarray(e, t);
return n.__proto__ = s.prototype, n;
}, s.prototype.readUIntLE = function (e, t, r) {
e >>>= 0, t >>>= 0, r || I(e, t, this.length);
for (var n = this[e], i = 1, o = 0; ++o < t && (i *= 256);) n += this[e + o] * i;
return n;
}, s.prototype.readUIntBE = function (e, t, r) {
e >>>= 0, t >>>= 0, r || I(e, t, this.length);
for (var n = this[e + --t], i = 1; t > 0 && (i *= 256);) n += this[e + --t] * i;
return n;
}, s.prototype.readUInt8 = function (e, t) {
return e >>>= 0, t || I(e, 1, this.length), this[e];
}, s.prototype.readUInt16LE = function (e, t) {
return e >>>= 0, t || I(e, 2, this.length), this[e] | this[e + 1] << 8;
}, s.prototype.readUInt16BE = function (e, t) {
return e >>>= 0, t || I(e, 2, this.length), this[e] << 8 | this[e + 1];
}, s.prototype.readUInt32LE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), (this[e] | this[e + 1] << 8 | this[e + 2] << 16) + 16777216 * this[e + 3];
}, s.prototype.readUInt32BE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), 16777216 * this[e] + (this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3]);
}, s.prototype.readIntLE = function (e, t, r) {
e >>>= 0, t >>>= 0, r || I(e, t, this.length);
for (var n = this[e], i = 1, o = 0; ++o < t && (i *= 256);) n += this[e + o] * i;
return n >= (i *= 128) && (n -= Math.pow(2, 8 * t)), n;
}, s.prototype.readIntBE = function (e, t, r) {
e >>>= 0, t >>>= 0, r || I(e, t, this.length);
for (var n = t, i = 1, o = this[e + --n]; n > 0 && (i *= 256);) o += this[e + --n] * i;
return o >= (i *= 128) && (o -= Math.pow(2, 8 * t)), o;
}, s.prototype.readInt8 = function (e, t) {
return e >>>= 0, t || I(e, 1, this.length), 128 & this[e] ? -1 * (255 - this[e] + 1) : this[e];
}, s.prototype.readInt16LE = function (e, t) {
e >>>= 0, t || I(e, 2, this.length);
var r = this[e] | this[e + 1] << 8;
return 32768 & r ? 4294901760 | r : r;
}, s.prototype.readInt16BE = function (e, t) {
e >>>= 0, t || I(e, 2, this.length);
var r = this[e + 1] | this[e] << 8;
return 32768 & r ? 4294901760 | r : r;
}, s.prototype.readInt32LE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), this[e] | this[e + 1] << 8 | this[e + 2] << 16 | this[e + 3] << 24;
}, s.prototype.readInt32BE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), this[e] << 24 | this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3];
}, s.prototype.readFloatLE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), n.read(this, e, !0, 23, 4);
}, s.prototype.readFloatBE = function (e, t) {
return e >>>= 0, t || I(e, 4, this.length), n.read(this, e, !1, 23, 4);
}, s.prototype.readDoubleLE = function (e, t) {
return e >>>= 0, t || I(e, 8, this.length), n.read(this, e, !0, 52, 8);
}, s.prototype.readDoubleBE = function (e, t) {
return e >>>= 0, t || I(e, 8, this.length), n.read(this, e, !1, 52, 8);
}, s.prototype.writeUIntLE = function (e, t, r, n) {
(e = +e, t >>>= 0, r >>>= 0, n) || P(this, e, t, r, Math.pow(2, 8 * r) - 1, 0);
var i = 1,
o = 0;
for (this[t] = 255 & e; ++o < r && (i *= 256);) this[t + o] = e / i & 255;
return t + r;
}, s.prototype.writeUIntBE = function (e, t, r, n) {
(e = +e, t >>>= 0, r >>>= 0, n) || P(this, e, t, r, Math.pow(2, 8 * r) - 1, 0);
var i = r - 1,
o = 1;
for (this[t + i] = 255 & e; --i >= 0 && (o *= 256);) this[t + i] = e / o & 255;
return t + r;
}, s.prototype.writeUInt8 = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 1, 255, 0), this[t] = 255 & e, t + 1;
}, s.prototype.writeUInt16LE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 2, 65535, 0), this[t] = 255 & e, this[t + 1] = e >>> 8, t + 2;
}, s.prototype.writeUInt16BE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 2, 65535, 0), this[t] = e >>> 8, this[t + 1] = 255 & e, t + 2;
}, s.prototype.writeUInt32LE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 4, 4294967295, 0), this[t + 3] = e >>> 24, this[t + 2] = e >>> 16, this[t + 1] = e >>> 8, this[t] = 255 & e, t + 4;
}, s.prototype.writeUInt32BE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 4, 4294967295, 0), this[t] = e >>> 24, this[t + 1] = e >>> 16, this[t + 2] = e >>> 8, this[t + 3] = 255 & e, t + 4;
}, s.prototype.writeIntLE = function (e, t, r, n) {
if (e = +e, t >>>= 0, !n) {
var i = Math.pow(2, 8 * r - 1);
P(this, e, t, r, i - 1, -i);
}
var o = 0,
s = 1,
a = 0;
for (this[t] = 255 & e; ++o < r && (s *= 256);) e < 0 && 0 === a && 0 !== this[t + o - 1] && (a = 1), this[t + o] = (e / s >> 0) - a & 255;
return t + r;
}, s.prototype.writeIntBE = function (e, t, r, n) {
if (e = +e, t >>>= 0, !n) {
var i = Math.pow(2, 8 * r - 1);
P(this, e, t, r, i - 1, -i);
}
var o = r - 1,
s = 1,
a = 0;
for (this[t + o] = 255 & e; --o >= 0 && (s *= 256);) e < 0 && 0 === a && 0 !== this[t + o + 1] && (a = 1), this[t + o] = (e / s >> 0) - a & 255;
return t + r;
}, s.prototype.writeInt8 = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 1, 127, -128), e < 0 && (e = 255 + e + 1), this[t] = 255 & e, t + 1;
}, s.prototype.writeInt16LE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 2, 32767, -32768), this[t] = 255 & e, this[t + 1] = e >>> 8, t + 2;
}, s.prototype.writeInt16BE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 2, 32767, -32768), this[t] = e >>> 8, this[t + 1] = 255 & e, t + 2;
}, s.prototype.writeInt32LE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 4, 2147483647, -2147483648), this[t] = 255 & e, this[t + 1] = e >>> 8, this[t + 2] = e >>> 16, this[t + 3] = e >>> 24, t + 4;
}, s.prototype.writeInt32BE = function (e, t, r) {
return e = +e, t >>>= 0, r || P(this, e, t, 4, 2147483647, -2147483648), e < 0 && (e = 4294967295 + e + 1), this[t] = e >>> 24, this[t + 1] = e >>> 16, this[t + 2] = e >>> 8, this[t + 3] = 255 & e, t + 4;
}, s.prototype.writeFloatLE = function (e, t, r) {
return B(this, e, t, !0, r);
}, s.prototype.writeFloatBE = function (e, t, r) {
return B(this, e, t, !1, r);
}, s.prototype.writeDoubleLE = function (e, t, r) {
return R(this, e, t, !0, r);
}, s.prototype.writeDoubleBE = function (e, t, r) {
return R(this, e, t, !1, r);
}, s.prototype.copy = function (e, t, r, n) {
if (!s.isBuffer(e)) throw new TypeError("argument should be a Buffer");
if (r || (r = 0), n || 0 === n || (n = this.length), t >= e.length && (t = e.length), t || (t = 0), n > 0 && n < r && (n = r), n === r) return 0;
if (0 === e.length || 0 === this.length) return 0;
if (t < 0) throw new RangeError("targetStart out of bounds");
if (r < 0 || r >= this.length) throw new RangeError("Index out of range");
if (n < 0) throw new RangeError("sourceEnd out of bounds");
n > this.length && (n = this.length), e.length - t < n - r && (n = e.length - t + r);
var i = n - r;
if (this === e && "function" == typeof Uint8Array.prototype.copyWithin) this.copyWithin(t, r, n);else if (this === e && r < t && t < n) for (var o = i - 1; o >= 0; --o) e[o + t] = this[o + r];else Uint8Array.prototype.set.call(e, this.subarray(r, n), t);
return i;
}, s.prototype.fill = function (e, t, r, n) {
if ("string" == typeof e) {
if ("string" == typeof t ? (n = t, t = 0, r = this.length) : "string" == typeof r && (n = r, r = this.length), void 0 !== n && "string" != typeof n) throw new TypeError("encoding must be a string");
if ("string" == typeof n && !s.isEncoding(n)) throw new TypeError("Unknown encoding: " + n);
if (1 === e.length) {
var i = e.charCodeAt(0);
("utf8" === n && i < 128 || "latin1" === n) && (e = i);
}
} else "number" == typeof e && (e &= 255);
if (t < 0 || this.length < t || this.length < r) throw new RangeError("Out of range index");
if (r <= t) return this;
var o;
if (t >>>= 0, r = void 0 === r ? this.length : r >>> 0, e || (e = 0), "number" == typeof e) for (o = t; o < r; ++o) this[o] = e;else {
var a = s.isBuffer(e) ? e : s.from(e, n),
l = a.length;
if (0 === l) throw new TypeError('The value "' + e + '" is invalid for argument "value"');
for (o = 0; o < r - t; ++o) this[o + t] = a[o % l];
}
return this;
};
var M = /[^+/0-9A-Za-z-_]/g;
function N(e) {
return e < 16 ? "0" + e.toString(16) : e.toString(16);
}
function L(e, t) {
var r;
t = t || 1 / 0;
for (var n = e.length, i = null, o = [], s = 0; s < n; ++s) {
if ((r = e.charCodeAt(s)) > 55295 && r < 57344) {
if (!i) {
if (r > 56319) {
(t -= 3) > -1 && o.push(239, 191, 189);
continue;
}
if (s + 1 === n) {
(t -= 3) > -1 && o.push(239, 191, 189);
continue;
}
i = r;
continue;
}
if (r < 56320) {
(t -= 3) > -1 && o.push(239, 191, 189), i = r;
continue;
}
r = 65536 + (i - 55296 << 10 | r - 56320);
} else i && (t -= 3) > -1 && o.push(239, 191, 189);
if (i = null, r < 128) {
if ((t -= 1) < 0) break;
o.push(r);
} else if (r < 2048) {
if ((t -= 2) < 0) break;
o.push(r >> 6 | 192, 63 & r | 128);
} else if (r < 65536) {
if ((t -= 3) < 0) break;
o.push(r >> 12 | 224, r >> 6 & 63 | 128, 63 & r | 128);
} else {
if (!(r < 1114112)) throw new Error("Invalid code point");
if ((t -= 4) < 0) break;
o.push(r >> 18 | 240, r >> 12 & 63 | 128, r >> 6 & 63 | 128, 63 & r | 128);
}
}
return o;
}
function j(e) {
return t.toByteArray(function (e) {
if ((e = (e = e.split("=")[0]).trim().replace(M, "")).length < 2) return "";
for (; e.length % 4 != 0;) e += "=";
return e;
}(e));
}
function U(e, t, r, n) {
for (var i = 0; i < n && !(i + r >= t.length || i >= e.length); ++i) t[i + r] = e[i];
return i;
}
function q(e, t) {
return e instanceof t || null != e && null != e.constructor && null != e.constructor.name && e.constructor.name === t.name;
}
function D(e) {
return e != e;
}
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
"base64-js": 13,
buffer: 17,
ieee754: 23
}],
18: [function (e, t, r) {
(function (n) {
(function () {
r.formatArgs = function (e) {
if (e[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + e[0] + (this.useColors ? "%c " : " ") + "+" + t.exports.humanize(this.diff), !this.useColors) return;
const r = "color: " + this.color;
e.splice(1, 0, r, "color: inherit");
let n = 0,
i = 0;
e[0].replace(/%[a-zA-Z%]/g, e => {
"%%" !== e && "%c" === e && (i = ++n);
}), e.splice(i, 0, r);
}, r.save = function (e) {
try {
e ? r.storage.setItem("debug", e) : r.storage.removeItem("debug");
} catch (e) {}
}, r.load = function () {
let e;
try {
e = r.storage.getItem("debug");
} catch (e) {}
!e && void 0 !== n && "env" in n && (e = n.env.DEBUG);
return e;
}, r.useColors = function () {
if ("undefined" != typeof window && window.process && ("renderer" === window.process.type || window.process.__nwjs)) return !0;
if ("undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) return !1;
return "undefined" != typeof document && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || "undefined" != typeof window && window.console && (window.console.firebug || window.console.exception && window.console.table) || "undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || "undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}, r.storage = function () {
try {
return localStorage;
} catch (e) {}
}(), r.destroy = (() => {
let e = !1;
return () => {
e || (e = !0, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
};
})(), r.colors = ["#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33"], r.log = console.debug || console.log || (() => {}), t.exports = e("./common")(r);
const {
formatters: i
} = t.exports;
i.j = function (e) {
try {
return JSON.stringify(e);
} catch (e) {
return "[UnexpectedJSONParseError]: " + e.message;
}
};
}).call(this);
}).call(this, e("_process"));
}, {
"./common": 19,
_process: 50
}],
19: [function (e, t, r) {
t.exports = function (t) {
function r(e) {
let t,
i,
o,
s = null;
function a(...e) {
if (!a.enabled) return;
const n = a,
i = Number(new Date()),
o = i - (t || i);
n.diff = o, n.prev = t, n.curr = i, t = i, e[0] = r.coerce(e[0]), "string" != typeof e[0] && e.unshift("%O");
let s = 0;
e[0] = e[0].replace(/%([a-zA-Z%])/g, (t, i) => {
if ("%%" === t) return "%";
s++;
const o = r.formatters[i];
if ("function" == typeof o) {
const r = e[s];
t = o.call(n, r), e.splice(s, 1), s--;
}
return t;
}), r.formatArgs.call(n, e), (n.log || r.log).apply(n, e);
}
return a.namespace = e, a.useColors = r.useColors(), a.color = r.selectColor(e), a.extend = n, a.destroy = r.destroy, Object.defineProperty(a, "enabled", {
enumerable: !0,
configurable: !1,
get: () => null !== s ? s : (i !== r.namespaces && (i = r.namespaces, o = r.enabled(e)), o),
set: e => {
s = e;
}
}), "function" == typeof r.init && r.init(a), a;
}
function n(e, t) {
const n = r(this.namespace + (void 0 === t ? ":" : t) + e);
return n.log = this.log, n;
}
function i(e) {
return e.toString().substring(2, e.toString().length - 2).replace(/\.\*\?$/, "*");
}
return r.debug = r, r.default = r, r.coerce = function (e) {
return e instanceof Error ? e.stack || e.message : e;
}, r.disable = function () {
const e = [...r.names.map(i), ...r.skips.map(i).map(e => "-" + e)].join(",");
return r.enable(""), e;
}, r.enable = function (e) {
let t;
r.save(e), r.namespaces = e, r.names = [], r.skips = [];
const n = ("string" == typeof e ? e : "").split(/[\s,]+/),
i = n.length;
for (t = 0; t < i; t++) n[t] && ("-" === (e = n[t].replace(/\*/g, ".*?"))[0] ? r.skips.push(new RegExp("^" + e.substr(1) + "$")) : r.names.push(new RegExp("^" + e + "$")));
}, r.enabled = function (e) {
if ("*" === e[e.length - 1]) return !0;
let t, n;
for (t = 0, n = r.skips.length; t < n; t++) if (r.skips[t].test(e)) return !1;
for (t = 0, n = r.names.length; t < n; t++) if (r.names[t].test(e)) return !0;
return !1;
}, r.humanize = e("ms"), r.destroy = function () {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}, Object.keys(t).forEach(e => {
r[e] = t[e];
}), r.names = [], r.skips = [], r.formatters = {}, r.selectColor = function (e) {
let t = 0;
for (let r = 0; r < e.length; r++) t = (t << 5) - t + e.charCodeAt(r), t |= 0;
return r.colors[Math.abs(t) % r.colors.length];
}, r.enable(r.load()), r;
};
}, {
ms: 45
}],
20: [function (e, t, r) {
(function (r, n) {
(function () {
var i = e("readable-stream"),
o = e("end-of-stream"),
s = e("inherits"),
a = e("stream-shift"),
l = n.from && n.from !== Uint8Array.from ? n.from([0]) : new n([0]),
u = function (e, t) {
e._corked ? e.once("uncork", t) : t();
},
c = function (e, t) {
return function (r) {
r ? function (e, t) {
e._autoDestroy && e.destroy(t);
}(e, "premature close" === r.message ? null : r) : t && !e._ended && e.end();
};
},
h = function () {},
f = function (e, t, r) {
if (!(this instanceof f)) return new f(e, t, r);
i.Duplex.call(this, r), this._writable = null, this._readable = null, this._readable2 = null, this._autoDestroy = !r || !1 !== r.autoDestroy, this._forwardDestroy = !r || !1 !== r.destroy, this._forwardEnd = !r || !1 !== r.end, this._corked = 1, this._ondrain = null, this._drained = !1, this._forwarding = !1, this._unwrite = null, this._unread = null, this._ended = !1, this.destroyed = !1, e && this.setWritable(e), t && this.setReadable(t);
};
s(f, i.Duplex), f.obj = function (e, t, r) {
return r || (r = {}), r.objectMode = !0, r.highWaterMark = 16, new f(e, t, r);
}, f.prototype.cork = function () {
1 == ++this._corked && this.emit("cork");
}, f.prototype.uncork = function () {
this._corked && 0 == --this._corked && this.emit("uncork");
}, f.prototype.setWritable = function (e) {
if (this._unwrite && this._unwrite(), this.destroyed) e && e.destroy && e.destroy();else if (null !== e && !1 !== e) {
var t = this,
n = o(e, {
writable: !0,
readable: !1
}, c(this, this._forwardEnd)),
i = function () {
var e = t._ondrain;
t._ondrain = null, e && e();
};
this._unwrite && r.nextTick(i), this._writable = e, this._writable.on("drain", i), this._unwrite = function () {
t._writable.removeListener("drain", i), n();
}, this.uncork();
} else this.end();
}, f.prototype.setReadable = function (e) {
if (this._unread && this._unread(), this.destroyed) e && e.destroy && e.destroy();else {
if (null === e || !1 === e) return this.push(null), void this.resume();
var t,
r = this,
n = o(e, {
writable: !1,
readable: !0
}, c(this)),
s = function () {
r._forward();
},
a = function () {
r.push(null);
};
this._drained = !0, this._readable = e, this._readable2 = e._readableState ? e : (t = e, new i.Readable({
objectMode: !0,
highWaterMark: 16
}).wrap(t)), this._readable2.on("readable", s), this._readable2.on("end", a), this._unread = function () {
r._readable2.removeListener("readable", s), r._readable2.removeListener("end", a), n();
}, this._forward();
}
}, f.prototype._read = function () {
this._drained = !0, this._forward();
}, f.prototype._forward = function () {
if (!this._forwarding && this._readable2 && this._drained) {
var e;
for (this._forwarding = !0; this._drained && null !== (e = a(this._readable2));) this.destroyed || (this._drained = this.push(e));
this._forwarding = !1;
}
}, f.prototype.destroy = function (e, t) {
if (t || (t = h), this.destroyed) return t(null);
this.destroyed = !0;
var n = this;
r.nextTick(function () {
n._destroy(e), t(null);
});
}, f.prototype._destroy = function (e) {
if (e) {
var t = this._ondrain;
this._ondrain = null, t ? t(e) : this.emit("error", e);
}
this._forwardDestroy && (this._readable && this._readable.destroy && this._readable.destroy(), this._writable && this._writable.destroy && this._writable.destroy()), this.emit("close");
}, f.prototype._write = function (e, t, r) {
if (!this.destroyed) return this._corked ? u(this, this._write.bind(this, e, t, r)) : e === l ? this._finish(r) : this._writable ? void (!1 === this._writable.write(e) ? this._ondrain = r : this.destroyed || r()) : r();
}, f.prototype._finish = function (e) {
var t = this;
this.emit("preend"), u(this, function () {
var r, n;
r = t._forwardEnd && t._writable, n = function () {
!1 === t._writableState.prefinished && (t._writableState.prefinished = !0), t.emit("prefinish"), u(t, e);
}, r ? r._writableState && r._writableState.finished ? n() : r._writableState ? r.end(n) : (r.end(), n()) : n();
});
}, f.prototype.end = function (e, t, r) {
return "function" == typeof e ? this.end(null, null, e) : "function" == typeof t ? this.end(e, null, t) : (this._ended = !0, e && this.write(e), this._writableState.ending || this._writableState.destroyed || this.write(l), i.Writable.prototype.end.call(this, r));
}, t.exports = f;
}).call(this);
}).call(this, e("_process"), e("buffer").Buffer);
}, {
_process: 50,
buffer: 17,
"end-of-stream": 21,
inherits: 24,
"readable-stream": 69,
"stream-shift": 74
}],
21: [function (e, t, r) {
(function (r) {
(function () {
var n = e("once"),
i = function () {},
o = function (e, t, s) {
if ("function" == typeof t) return o(e, null, t);
t || (t = {}), s = n(s || i);
var a = e._writableState,
l = e._readableState,
u = t.readable || !1 !== t.readable && e.readable,
c = t.writable || !1 !== t.writable && e.writable,
h = !1,
f = function () {
e.writable || p();
},
p = function () {
c = !1, u || s.call(e);
},
d = function () {
u = !1, c || s.call(e);
},
g = function (t) {
s.call(e, t ? new Error("exited with error code: " + t) : null);
},
y = function (t) {
s.call(e, t);
},
b = function () {
r.nextTick(m);
},
m = function () {
if (!h) return (!u || l && l.ended && !l.destroyed) && (!c || a && a.ended && !a.destroyed) ? void 0 : s.call(e, new Error("premature close"));
},
v = function () {
e.req.on("finish", p);
};
return !function (e) {
return e.setHeader && "function" == typeof e.abort;
}(e) ? c && !a && (e.on("end", f), e.on("close", f)) : (e.on("complete", p), e.on("abort", b), e.req ? v() : e.on("request", v)), function (e) {
return e.stdio && Array.isArray(e.stdio) && 3 === e.stdio.length;
}(e) && e.on("exit", g), e.on("end", d), e.on("finish", p), !1 !== t.error && e.on("error", y), e.on("close", b), function () {
h = !0, e.removeListener("complete", p), e.removeListener("abort", b), e.removeListener("request", v), e.req && e.req.removeListener("finish", p), e.removeListener("end", f), e.removeListener("close", f), e.removeListener("finish", p), e.removeListener("exit", g), e.removeListener("end", d), e.removeListener("error", y), e.removeListener("close", b);
};
};
t.exports = o;
}).call(this);
}).call(this, e("_process"));
}, {
_process: 50,
once: 48
}],
22: [function (e, t, r) {
var n = Object.create || function (e) {
var t = function () {};
return t.prototype = e, new t();
},
i = Object.keys || function (e) {
var t = [];
for (var r in e) Object.prototype.hasOwnProperty.call(e, r) && t.push(r);
return r;
},
o = Function.prototype.bind || function (e) {
var t = this;
return function () {
return t.apply(e, arguments);
};
};
function s() {
this._events && Object.prototype.hasOwnProperty.call(this, "_events") || (this._events = n(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
}
t.exports = s, s.EventEmitter = s, s.prototype._events = void 0, s.prototype._maxListeners = void 0;
var a,
l = 10;
try {
var u = {};
Object.defineProperty && Object.defineProperty(u, "x", {
value: 0
}), a = 0 === u.x;
} catch (e) {
a = !1;
}
function c(e) {
return void 0 === e._maxListeners ? s.defaultMaxListeners : e._maxListeners;
}
function h(e, t, r, i) {
var o, s, a;
if ("function" != typeof r) throw new TypeError('"listener" argument must be a function');
if ((s = e._events) ? (s.newListener && (e.emit("newListener", t, r.listener ? r.listener : r), s = e._events), a = s[t]) : (s = e._events = n(null), e._eventsCount = 0), a) {
if ("function" == typeof a ? a = s[t] = i ? [r, a] : [a, r] : i ? a.unshift(r) : a.push(r), !a.warned && (o = c(e)) && o > 0 && a.length > o) {
a.warned = !0;
var l = new Error("Possible EventEmitter memory leak detected. " + a.length + ' "' + String(t) + '" listeners added. Use emitter.setMaxListeners() to increase limit.');
l.name = "MaxListenersExceededWarning", l.emitter = e, l.type = t, l.count = a.length, "object" == typeof console && console.warn && console.warn("%s: %s", l.name, l.message);
}
} else a = s[t] = r, ++e._eventsCount;
return e;
}
function f() {
if (!this.fired) switch (this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length) {
case 0:
return this.listener.call(this.target);
case 1:
return this.listener.call(this.target, arguments[0]);
case 2:
return this.listener.call(this.target, arguments[0], arguments[1]);
case 3:
return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]);
default:
for (var e = new Array(arguments.length), t = 0; t < e.length; ++t) e[t] = arguments[t];
this.listener.apply(this.target, e);
}
}
function p(e, t, r) {
var n = {
fired: !1,
wrapFn: void 0,
target: e,
type: t,
listener: r
},
i = o.call(f, n);
return i.listener = r, n.wrapFn = i, i;
}
function d(e, t, r) {
var n = e._events;
if (!n) return [];
var i = n[t];
return i ? "function" == typeof i ? r ? [i.listener || i] : [i] : r ? function (e) {
for (var t = new Array(e.length), r = 0; r < t.length; ++r) t[r] = e[r].listener || e[r];
return t;
}(i) : y(i, i.length) : [];
}
function g(e) {
var t = this._events;
if (t) {
var r = t[e];
if ("function" == typeof r) return 1;
if (r) return r.length;
}
return 0;
}
function y(e, t) {
for (var r = new Array(t), n = 0; n < t; ++n) r[n] = e[n];
return r;
}
a ? Object.defineProperty(s, "defaultMaxListeners", {
enumerable: !0,
get: function () {
return l;
},
set: function (e) {
if ("number" != typeof e || e < 0 || e != e) throw new TypeError('"defaultMaxListeners" must be a positive number');
l = e;
}
}) : s.defaultMaxListeners = l, s.prototype.setMaxListeners = function (e) {
if ("number" != typeof e || e < 0 || isNaN(e)) throw new TypeError('"n" argument must be a positive number');
return this._maxListeners = e, this;
}, s.prototype.getMaxListeners = function () {
return c(this);
}, s.prototype.emit = function (e) {
var t,
r,
n,
i,
o,
s,
a = "error" === e;
if (s = this._events) a = a && null == s.error;else if (!a) return !1;
if (a) {
if (arguments.length > 1 && (t = arguments[1]), t instanceof Error) throw t;
var l = new Error('Unhandled "error" event. (' + t + ")");
throw l.context = t, l;
}
if (!(r = s[e])) return !1;
var u = "function" == typeof r;
switch (n = arguments.length) {
case 1:
!function (e, t, r) {
if (t) e.call(r);else for (var n = e.length, i = y(e, n), o = 0; o < n; ++o) i[o].call(r);
}(r, u, this);
break;
case 2:
!function (e, t, r, n) {
if (t) e.call(r, n);else for (var i = e.length, o = y(e, i), s = 0; s < i; ++s) o[s].call(r, n);
}(r, u, this, arguments[1]);
break;
case 3:
!function (e, t, r, n, i) {
if (t) e.call(r, n, i);else for (var o = e.length, s = y(e, o), a = 0; a < o; ++a) s[a].call(r, n, i);
}(r, u, this, arguments[1], arguments[2]);
break;
case 4:
!function (e, t, r, n, i, o) {
if (t) e.call(r, n, i, o);else for (var s = e.length, a = y(e, s), l = 0; l < s; ++l) a[l].call(r, n, i, o);
}(r, u, this, arguments[1], arguments[2], arguments[3]);
break;
default:
for (i = new Array(n - 1), o = 1; o < n; o++) i[o - 1] = arguments[o];
!function (e, t, r, n) {
if (t) e.apply(r, n);else for (var i = e.length, o = y(e, i), s = 0; s < i; ++s) o[s].apply(r, n);
}(r, u, this, i);
}
return !0;
}, s.prototype.addListener = function (e, t) {
return h(this, e, t, !1);
}, s.prototype.on = s.prototype.addListener, s.prototype.prependListener = function (e, t) {
return h(this, e, t, !0);
}, s.prototype.once = function (e, t) {
if ("function" != typeof t) throw new TypeError('"listener" argument must be a function');
return this.on(e, p(this, e, t)), this;
}, s.prototype.prependOnceListener = function (e, t) {
if ("function" != typeof t) throw new TypeError('"listener" argument must be a function');
return this.prependListener(e, p(this, e, t)), this;
}, s.prototype.removeListener = function (e, t) {
var r, i, o, s, a;
if ("function" != typeof t) throw new TypeError('"listener" argument must be a function');
if (!(i = this._events)) return this;
if (!(r = i[e])) return this;
if (r === t || r.listener === t) 0 == --this._eventsCount ? this._events = n(null) : (delete i[e], i.removeListener && this.emit("removeListener", e, r.listener || t));else if ("function" != typeof r) {
for (o = -1, s = r.length - 1; s >= 0; s--) if (r[s] === t || r[s].listener === t) {
a = r[s].listener, o = s;
break;
}
if (o < 0) return this;
0 === o ? r.shift() : function (e, t) {
for (var r = t, n = r + 1, i = e.length; n < i; r += 1, n += 1) e[r] = e[n];
e.pop();
}(r, o), 1 === r.length && (i[e] = r[0]), i.removeListener && this.emit("removeListener", e, a || t);
}
return this;
}, s.prototype.removeAllListeners = function (e) {
var t, r, o;
if (!(r = this._events)) return this;
if (!r.removeListener) return 0 === arguments.length ? (this._events = n(null), this._eventsCount = 0) : r[e] && (0 == --this._eventsCount ? this._events = n(null) : delete r[e]), this;
if (0 === arguments.length) {
var s,
a = i(r);
for (o = 0; o < a.length; ++o) "removeListener" !== (s = a[o]) && this.removeAllListeners(s);
return this.removeAllListeners("removeListener"), this._events = n(null), this._eventsCount = 0, this;
}
if ("function" == typeof (t = r[e])) this.removeListener(e, t);else if (t) for (o = t.length - 1; o >= 0; o--) this.removeListener(e, t[o]);
return this;
}, s.prototype.listeners = function (e) {
return d(this, e, !0);
}, s.prototype.rawListeners = function (e) {
return d(this, e, !1);
}, s.listenerCount = function (e, t) {
return "function" == typeof e.listenerCount ? e.listenerCount(t) : g.call(e, t);
}, s.prototype.listenerCount = g, s.prototype.eventNames = function () {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
};
}, {}],
23: [function (e, t, r) {
r.read = function (e, t, r, n, i) {
var o,
s,
a = 8 * i - n - 1,
l = (1 << a) - 1,
u = l >> 1,
c = -7,
h = r ? i - 1 : 0,
f = r ? -1 : 1,
p = e[t + h];
for (h += f, o = p & (1 << -c) - 1, p >>= -c, c += a; c > 0; o = 256 * o + e[t + h], h += f, c -= 8);
for (s = o & (1 << -c) - 1, o >>= -c, c += n; c > 0; s = 256 * s + e[t + h], h += f, c -= 8);
if (0 === o) o = 1 - u;else {
if (o === l) return s ? NaN : 1 / 0 * (p ? -1 : 1);
s += Math.pow(2, n), o -= u;
}
return (p ? -1 : 1) * s * Math.pow(2, o - n);
}, r.write = function (e, t, r, n, i, o) {
var s,
a,
l,
u = 8 * o - i - 1,
c = (1 << u) - 1,
h = c >> 1,
f = 23 === i ? Math.pow(2, -24) - Math.pow(2, -77) : 0,
p = n ? 0 : o - 1,
d = n ? 1 : -1,
g = t < 0 || 0 === t && 1 / t < 0 ? 1 : 0;
for (t = Math.abs(t), isNaN(t) || t === 1 / 0 ? (a = isNaN(t) ? 1 : 0, s = c) : (s = Math.floor(Math.log(t) / Math.LN2), t * (l = Math.pow(2, -s)) < 1 && (s--, l *= 2), (t += s + h >= 1 ? f / l : f * Math.pow(2, 1 - h)) * l >= 2 && (s++, l /= 2), s + h >= c ? (a = 0, s = c) : s + h >= 1 ? (a = (t * l - 1) * Math.pow(2, i), s += h) : (a = t * Math.pow(2, h - 1) * Math.pow(2, i), s = 0)); i >= 8; e[r + p] = 255 & a, p += d, a /= 256, i -= 8);
for (s = s << i | a, u += i; u > 0; e[r + p] = 255 & s, p += d, s /= 256, u -= 8);
e[r + p - d] |= 128 * g;
};
}, {}],
24: [function (e, t, r) {
"function" == typeof Object.create ? t.exports = function (e, t) {
t && (e.super_ = t, e.prototype = Object.create(t.prototype, {
constructor: {
value: e,
enumerable: !1,
writable: !0,
configurable: !0
}
}));
} : t.exports = function (e, t) {
if (t) {
e.super_ = t;
var r = function () {};
r.prototype = t.prototype, e.prototype = new r(), e.prototype.constructor = e;
}
};
}, {}],
25: [function (e, t, r) {
Object.defineProperty(r, "__esModule", {
value: !0
});
var n = function () {
function e(e, t) {
this.color = !0, this.key = void 0, this.value = void 0, this.parent = void 0, this.brother = void 0, this.leftChild = void 0, this.rightChild = void 0, this.key = e, this.value = t;
}
return e.prototype.rotateLeft = function () {
var e = this.parent,
t = this.brother,
r = this.leftChild,
n = this.rightChild;
if (!n) throw new Error("unknown error");
var i = n.leftChild,
o = n.rightChild;
return e && (e.leftChild === this ? e.leftChild = n : e.rightChild === this && (e.rightChild = n)), n.parent = e, n.brother = t, n.leftChild = this, n.rightChild = o, t && (t.brother = n), this.parent = n, this.brother = o, this.leftChild = r, this.rightChild = i, o && (o.parent = n, o.brother = this), r && (r.parent = this, r.brother = i), i && (i.parent = this, i.brother = r), n;
}, e.prototype.rotateRight = function () {
var e = this.parent,
t = this.brother,
r = this.leftChild;
if (!r) throw new Error("unknown error");
var n = this.rightChild,
i = r.leftChild,
o = r.rightChild;
return e && (e.leftChild === this ? e.leftChild = r : e.rightChild === this && (e.rightChild = r)), r.parent = e, r.brother = t, r.leftChild = i, r.rightChild = this, t && (t.brother = r), i && (i.parent = r, i.brother = this), this.parent = r, this.brother = i, this.leftChild = o, this.rightChild = n, o && (o.parent = this, o.brother = n), n && (n.parent = this, n.brother = o), r;
}, e.prototype.remove = function () {
if (this.leftChild || this.rightChild) throw new Error("can only remove leaf node");
this.parent && (this === this.parent.leftChild ? this.parent.leftChild = void 0 : this === this.parent.rightChild && (this.parent.rightChild = void 0)), this.brother && (this.brother.brother = void 0), this.key = void 0, this.value = void 0, this.parent = void 0, this.brother = void 0;
}, e.TreeNodeColorType = {
red: !0,
black: !1
}, e;
}();
Object.freeze(n), r.default = n;
}, {}],
26: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
};
function i(e) {
var t = this;
void 0 === e && (e = []);
var r = [],
o = 0,
s = 0,
a = 0,
l = 0,
u = 0,
c = 0;
this.size = function () {
return c;
}, this.empty = function () {
return 0 === c;
}, this.clear = function () {
o = a = s = l = u = c = 0, f.call(this, i.bucketSize), c = 0;
}, this.front = function () {
return r[o][s];
}, this.back = function () {
return r[a][l];
}, this.forEach = function (e) {
if (!this.empty()) {
var t = 0;
if (o !== a) {
for (u = s; u < i.bucketSize; ++u) e(r[o][u], t++);
for (u = o + 1; u < a; ++u) for (var n = 0; n < i.bucketSize; ++n) e(r[u][n], t++);
for (u = 0; u <= l; ++u) e(r[a][u], t++);
} else for (var u = s; u <= l; ++u) e(r[o][u], t++);
}
};
var h = function (e) {
var t = o * i.bucketSize + s,
r = t + e,
n = a * i.bucketSize + l;
if (r < t || r > n) throw new Error("pos should more than 0 and less than queue's size");
return {
curNodeBucketIndex: Math.floor(r / i.bucketSize),
curNodePointerIndex: r % i.bucketSize
};
};
this.getElementByPos = function (e) {
var t = h(e),
n = t.curNodeBucketIndex,
i = t.curNodePointerIndex;
return r[n][i];
}, this.eraseElementByPos = function (e) {
var t = this;
if (e < 0 || e > c) throw new Error("pos should more than 0 and less than queue's size");
if (0 === e) this.popFront();else if (e === this.size()) this.popBack();else {
for (var r = [], n = e + 1; n < c; ++n) r.push(this.getElementByPos(n));
this.cut(e), this.popBack(), r.forEach(function (e) {
return t.pushBack(e);
});
}
}, this.eraseElementByValue = function (e) {
if (!this.empty()) {
var t = [];
this.forEach(function (r) {
r !== e && t.push(r);
});
for (var r = t.length, n = 0; n < r; ++n) this.setElementByPos(n, t[n]);
this.cut(r - 1);
}
};
var f = function (e) {
for (var t = [], n = e * i.sigma, h = Math.max(Math.ceil(n / i.bucketSize), 2), f = 0; f < h; ++f) t.push(new Array(i.bucketSize));
var p = Math.ceil(e / i.bucketSize),
d = Math.floor(h / 2) - Math.floor(p / 2),
g = d,
y = 0;
if (this.size()) for (f = 0; f < p; ++f) {
for (var b = 0; b < i.bucketSize; ++b) if (t[d + f][b] = this.front(), this.popFront(), this.empty()) {
g = d + f, y = b;
break;
}
if (this.empty()) break;
}
r = t, o = d, s = 0, a = g, l = y, u = h, c = e;
};
this.pushBack = function (e) {
this.empty() || (a === u - 1 && l === i.bucketSize - 1 && f.call(this, this.size()), l < i.bucketSize - 1 ? ++l : a < u - 1 && (++a, l = 0)), ++c, r[a][l] = e;
}, this.popBack = function () {
this.empty() || (1 !== this.size() && (l > 0 ? --l : o < a && (--a, l = i.bucketSize - 1)), c > 0 && --c);
}, this.setElementByPos = function (e, t) {
var n = h(e),
i = n.curNodeBucketIndex,
o = n.curNodePointerIndex;
r[i][o] = t;
}, this.insert = function (e, t, r) {
var n = this;
if (void 0 === r && (r = 1), 0 === e) for (; r--;) this.pushFront(t);else if (e === this.size()) for (; r--;) this.pushBack(t);else {
for (var i = [], o = e; o < c; ++o) i.push(this.getElementByPos(o));
this.cut(e - 1);
for (o = 0; o < r; ++o) this.pushBack(t);
i.forEach(function (e) {
return n.pushBack(e);
});
}
}, this.find = function (e) {
if (o === a) {
for (var t = s; t <= l; ++t) if (r[o][t] === e) return !0;
return !1;
}
for (t = s; t < i.bucketSize; ++t) if (r[o][t] === e) return !0;
for (t = o + 1; t < a; ++t) for (var n = 0; n < i.bucketSize; ++n) if (r[t][n] === e) return !0;
for (t = 0; t <= l; ++t) if (r[a][t] === e) return !0;
return !1;
}, this.reverse = function () {
for (var e = 0, t = c - 1; e < t;) {
var r = this.getElementByPos(e);
this.setElementByPos(e, this.getElementByPos(t)), this.setElementByPos(t, r), ++e, --t;
}
}, this.unique = function () {
if (!this.empty()) {
var e = [],
t = this.front();
this.forEach(function (r, n) {
0 !== n && r === t || (e.push(r), t = r);
});
for (var r = 0; r < c; ++r) this.setElementByPos(r, e[r]);
this.cut(e.length - 1);
}
}, this.sort = function (e) {
var t = [];
this.forEach(function (e) {
t.push(e);
}), t.sort(e);
for (var r = 0; r < c; ++r) this.setElementByPos(r, t[r]);
}, this.pushFront = function (e) {
this.empty() || (0 === o && 0 === s && f.call(this, this.size()), s > 0 ? --s : o > 0 && (--o, s = i.bucketSize - 1)), ++c, r[o][s] = e;
}, this.popFront = function () {
this.empty() || (1 !== this.size() && (s < i.bucketSize - 1 ? ++s : o < a && (++o, s = 0)), c > 0 && --c);
}, this.shrinkToFit = function () {
var e = this,
t = [];
this.forEach(function (e) {
t.push(e);
});
var n = t.length;
r = [];
for (var o = Math.ceil(n / i.bucketSize), s = 0; s < o; ++s) r.push(new Array(i.bucketSize));
this.clear(), t.forEach(function (t) {
return e.pushBack(t);
});
}, this.cut = function (e) {
if (e < 0) this.clear();else {
var t = h(e),
r = t.curNodeBucketIndex,
n = t.curNodePointerIndex;
a = r, l = n, c = e + 1;
}
}, this[Symbol.iterator] = function () {
return function () {
var e, t;
return n(this, function (n) {
switch (n.label) {
case 0:
if (0 === c) return [2];
if (o !== a) return [3, 5];
t = s, n.label = 1;
case 1:
return t <= l ? [4, r[o][t]] : [3, 4];
case 2:
n.sent(), n.label = 3;
case 3:
return ++t, [3, 1];
case 4:
return [2];
case 5:
t = s, n.label = 6;
case 6:
return t < i.bucketSize ? [4, r[o][t]] : [3, 9];
case 7:
n.sent(), n.label = 8;
case 8:
return ++t, [3, 6];
case 9:
t = o + 1, n.label = 10;
case 10:
if (!(t < a)) return [3, 15];
e = 0, n.label = 11;
case 11:
return e < i.bucketSize ? [4, r[t][e]] : [3, 14];
case 12:
n.sent(), n.label = 13;
case 13:
return ++e, [3, 11];
case 14:
return ++t, [3, 10];
case 15:
t = 0, n.label = 16;
case 16:
return t <= l ? [4, r[a][t]] : [3, 19];
case 17:
n.sent(), n.label = 18;
case 18:
return ++t, [3, 16];
case 19:
return [2];
}
});
}();
}, function () {
var n = i.bucketSize;
e.size ? n = e.size() : e.length && (n = e.length);
var s = n * i.sigma;
u = Math.ceil(s / i.bucketSize), u = Math.max(u, 3);
for (var l = 0; l < u; ++l) r.push(new Array(i.bucketSize));
var c = Math.ceil(n / i.bucketSize);
o = Math.floor(u / 2) - Math.floor(c / 2), a = o, e.forEach(function (e) {
return t.pushBack(e);
});
}(), Object.freeze(this);
}
Object.defineProperty(r, "__esModule", {
value: !0
}), i.sigma = 3, i.bucketSize = 5e3, Object.freeze(i), r.default = i;
}, {}],
27: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
},
i = this && this.__values || function (e) {
var t = "function" == typeof Symbol && Symbol.iterator,
r = t && e[t],
n = 0;
if (r) return r.call(e);
if (e && "number" == typeof e.length) return {
next: function () {
return e && n >= e.length && (e = void 0), {
value: e && e[n++],
done: !e
};
}
};
throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(r, "__esModule", {
value: !0
});
var o = e("../LinkList/LinkList"),
s = e("../Map/Map");
function a(e, t, r) {
var l = this;
if (void 0 === e && (e = []), void 0 === t && (t = a.initSize), r = r || function (e) {
var t,
r,
n = 0,
o = "";
if ("number" == typeof e) n = ((n = Math.floor(e)) << 5) - n, n &= n;else {
o = "string" != typeof e ? JSON.stringify(e) : e;
try {
for (var s = i(o), a = s.next(); !a.done; a = s.next()) {
n = (n << 5) - n + a.value.charCodeAt(0), n &= n;
}
} catch (e) {
t = {
error: e
};
} finally {
try {
a && !a.done && (r = s.return) && r.call(s);
} finally {
if (t) throw t.error;
}
}
}
return n ^= n >>> 16;
}, 0 != (t & t - 1)) throw new Error("initBucketNum must be 2 to the power of n");
var u = 0,
c = [],
h = Math.max(a.initSize, Math.min(a.maxSize, t));
this.size = function () {
return u;
}, this.empty = function () {
return 0 === u;
}, this.clear = function () {
u = 0, h = t, c = [];
}, this.forEach = function (e) {
var t = 0;
c.forEach(function (r) {
r.forEach(function (r) {
e(r, t++);
});
});
};
this.setElement = function (e, t) {
var n, l;
if (null === e || void 0 === e) throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
if (null !== t && void 0 !== t) {
var f = r(e) & h - 1;
if (c[f]) {
var p = c[f].size();
if (c[f] instanceof o.default) {
try {
for (var d = i(c[f]), g = d.next(); !g.done; g = d.next()) {
var y = g.value;
if (y.key === e) return void (y.value = t);
}
} catch (e) {
n = {
error: e
};
} finally {
try {
g && !g.done && (l = d.return) && l.call(d);
} finally {
if (n) throw n.error;
}
}
c[f].pushBack({
key: e,
value: t
}), c[f].size() >= a.treeifyThreshold && (c[f] = new s.default(c[f]));
} else c[f].setElement(e, t);
var b = c[f].size();
u += b - p;
} else ++u, c[f] = new o.default([{
key: e,
value: t
}]);
u > h * a.sigma && function (e) {
if (!(e >= a.maxSize)) {
h = 2 * e;
var t = [];
c.forEach(function (n, i) {
if (!n.empty()) {
if (n instanceof o.default && 1 === n.size()) {
var l = n.front(),
u = l.key,
f = l.value;
t[r(u) & h - 1] = new o.default([{
key: u,
value: f
}]);
} else if (n instanceof s.default) {
var p = new o.default(),
d = new o.default();
n.forEach(function (t) {
0 == (r(t.key) & e) ? p.pushBack(t) : d.pushBack(t);
}), p.size() > a.untreeifyThreshold ? t[i] = new s.default(p) : p.size() && (t[i] = p), d.size() > a.untreeifyThreshold ? t[i + e] = new s.default(d) : d.size() && (t[i + e] = d);
} else {
var g = new o.default(),
y = new o.default();
n.forEach(function (t) {
0 == (r(t.key) & e) ? g.pushBack(t) : y.pushBack(t);
}), g.size() && (t[i] = g), y.size() && (t[i + e] = y);
}
c[i].clear();
}
}), c = t;
}
}.call(this, h);
} else this.eraseElementByKey(e);
}, this.getElementByKey = function (e) {
var t,
n,
o = r(e) & h - 1;
if (c[o]) {
if (c[o] instanceof s.default) return c[o].getElementByKey(e);
try {
for (var a = i(c[o]), l = a.next(); !l.done; l = a.next()) {
var u = l.value;
if (u.key === e) return u.value;
}
} catch (e) {
t = {
error: e
};
} finally {
try {
l && !l.done && (n = a.return) && n.call(a);
} finally {
if (t) throw t.error;
}
}
}
}, this.eraseElementByKey = function (e) {
var t,
n,
l = r(e) & h - 1;
if (c[l]) {
var f = c[l].size();
if (c[l] instanceof s.default) c[l].eraseElementByKey(e), c[l].size() <= a.untreeifyThreshold && (c[l] = new o.default(c[l]));else {
var p = -1;
try {
for (var d = i(c[l]), g = d.next(); !g.done; g = d.next()) {
if (++p, g.value.key === e) {
c[l].eraseElementByPos(p);
break;
}
}
} catch (e) {
t = {
error: e
};
} finally {
try {
g && !g.done && (n = d.return) && n.call(d);
} finally {
if (t) throw t.error;
}
}
}
var y = c[l].size();
u += y - f;
}
}, this.find = function (e) {
var t,
n,
o = r(e) & h - 1;
if (!c[o]) return !1;
if (c[o] instanceof s.default) return c[o].find(e);
try {
for (var a = i(c[o]), l = a.next(); !l.done; l = a.next()) {
if (l.value.key === e) return !0;
}
} catch (e) {
t = {
error: e
};
} finally {
try {
l && !l.done && (n = a.return) && n.call(a);
} finally {
if (t) throw t.error;
}
}
return !1;
}, this[Symbol.iterator] = function () {
return function () {
var e, t, r, o, s, a;
return n(this, function (n) {
switch (n.label) {
case 0:
e = 0, n.label = 1;
case 1:
if (!(e < h)) return [3, 10];
for (; e < h && !c[e];) ++e;
if (e >= h) return [3, 10];
n.label = 2;
case 2:
n.trys.push([2, 7, 8, 9]), s = void 0, t = i(c[e]), r = t.next(), n.label = 3;
case 3:
return r.done ? [3, 6] : [4, r.value];
case 4:
n.sent(), n.label = 5;
case 5:
return r = t.next(), [3, 3];
case 6:
return [3, 9];
case 7:
return o = n.sent(), s = {
error: o
}, [3, 9];
case 8:
try {
r && !r.done && (a = t.return) && a.call(t);
} finally {
if (s) throw s.error;
}
return [7];
case 9:
return ++e, [3, 1];
case 10:
return [2];
}
});
}();
}, e.forEach(function (e) {
var t = e.key,
r = e.value;
return l.setElement(t, r);
}), Object.freeze(this);
}
a.initSize = 16, a.maxSize = 1 << 30, a.sigma = .75, a.treeifyThreshold = 8, a.untreeifyThreshold = 6, a.minTreeifySize = 64, Object.freeze(a), r.default = a;
}, {
"../LinkList/LinkList": 29,
"../Map/Map": 30
}],
28: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
},
i = this && this.__values || function (e) {
var t = "function" == typeof Symbol && Symbol.iterator,
r = t && e[t],
n = 0;
if (r) return r.call(e);
if (e && "number" == typeof e.length) return {
next: function () {
return e && n >= e.length && (e = void 0), {
value: e && e[n++],
done: !e
};
}
};
throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(r, "__esModule", {
value: !0
});
var o = e("../Set/Set"),
s = e("../LinkList/LinkList");
function a(e, t, r) {
var l = this;
if (void 0 === e && (e = []), void 0 === t && (t = a.initSize), r = r || function (e) {
var t = 0,
r = "";
if ("number" == typeof e) t = ((t = Math.floor(e)) << 5) - t, t &= t;else {
r = "string" != typeof e ? JSON.stringify(e) : e;
for (var n = 0; n < r.length; n++) {
t = (t << 5) - t + r.charCodeAt(n), t &= t;
}
}
return t ^= t >>> 16;
}, 0 != (t & t - 1)) throw new Error("initBucketNum must be 2 to the power of n");
var u = 0,
c = [],
h = Math.max(a.initSize, Math.min(a.maxSize, t));
this.size = function () {
return u;
}, this.empty = function () {
return 0 === u;
}, this.clear = function () {
u = 0, h = t, c = [];
}, this.forEach = function (e) {
var t = 0;
c.forEach(function (r) {
r.forEach(function (r) {
e(r, t++);
});
});
};
this.insert = function (e) {
if (null === e || void 0 === e) throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
var t = r(e) & h - 1;
if (c[t]) {
var n = c[t].size();
if (c[t] instanceof s.default) {
if (c[t].find(e)) return;
c[t].pushBack(e), c[t].size() >= a.treeifyThreshold && (c[t] = new o.default(c[t]));
} else c[t].insert(e);
var i = c[t].size();
u += i - n;
} else c[t] = new s.default([e]), ++u;
u > h * a.sigma && function (e) {
if (!(e >= a.maxSize)) {
h = 2 * e;
var t = [];
c.forEach(function (n, i) {
if (!n.empty()) {
if (n instanceof s.default && 1 === n.size()) {
var l = n.front();
if (void 0 === l) throw new Error("unknown error");
t[r(l) & h - 1] = new s.default([l]);
} else if (n instanceof o.default) {
var u = new s.default(),
f = new s.default();
n.forEach(function (t) {
0 == (r(t) & e) ? u.pushBack(t) : f.pushBack(t);
}), u.size() > a.untreeifyThreshold ? t[i] = new o.default(u) : u.size() && (t[i] = u), f.size() > a.untreeifyThreshold ? t[i + e] = new o.default(f) : f.size() && (t[i + e] = f);
} else {
var p = new s.default(),
d = new s.default();
n.forEach(function (t) {
0 == (r(t) & e) ? p.pushBack(t) : d.pushBack(t);
}), p.size() && (t[i] = p), d.size() && (t[i + e] = d);
}
c[i].clear();
}
}), c = t;
}
}.call(this, h);
}, this.eraseElementByValue = function (e) {
var t = r(e) & h - 1;
if (c[t]) {
var n = c[t].size();
c[t].eraseElementByValue(e), c[t] instanceof o.default && c[t].size() <= a.untreeifyThreshold && (c[t] = new s.default(c[t]));
var i = c[t].size();
u += i - n;
}
}, this.find = function (e) {
var t = r(e) & h - 1;
return !!c[t] && c[t].find(e);
}, this[Symbol.iterator] = function () {
return function () {
var e, t, r, o, s, a;
return n(this, function (n) {
switch (n.label) {
case 0:
e = 0, n.label = 1;
case 1:
if (!(e < h)) return [3, 10];
for (; e < h && !c[e];) ++e;
if (e >= h) return [3, 10];
n.label = 2;
case 2:
n.trys.push([2, 7, 8, 9]), s = void 0, t = i(c[e]), r = t.next(), n.label = 3;
case 3:
return r.done ? [3, 6] : [4, r.value];
case 4:
n.sent(), n.label = 5;
case 5:
return r = t.next(), [3, 3];
case 6:
return [3, 9];
case 7:
return o = n.sent(), s = {
error: o
}, [3, 9];
case 8:
try {
r && !r.done && (a = t.return) && a.call(t);
} finally {
if (s) throw s.error;
}
return [7];
case 9:
return ++e, [3, 1];
case 10:
return [2];
}
});
}();
}, e.forEach(function (e) {
return l.insert(e);
}), Object.freeze(this);
}
a.initSize = 16, a.maxSize = 1 << 30, a.sigma = .75, a.treeifyThreshold = 8, a.untreeifyThreshold = 6, a.minTreeifySize = 64, Object.freeze(a), r.default = a;
}, {
"../LinkList/LinkList": 29,
"../Set/Set": 33
}],
29: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
};
Object.defineProperty(r, "__esModule", {
value: !0
});
var i = function () {
return function (e) {
this.value = void 0, this.pre = void 0, this.next = void 0, this.value = e;
};
}();
function o(e) {
var t = this;
void 0 === e && (e = []);
var r = 0,
o = void 0,
s = void 0;
this.size = function () {
return r;
}, this.empty = function () {
return 0 === r;
}, this.clear = function () {
o = s = void 0, r = 0;
}, this.front = function () {
return null === o || void 0 === o ? void 0 : o.value;
}, this.back = function () {
return null === s || void 0 === s ? void 0 : s.value;
}, this.forEach = function (e) {
for (var t = o, r = 0; t;) {
if (void 0 === t.value) throw new Error("unknown error");
e(t.value, r++), t = t.next;
}
}, this.getElementByPos = function (e) {
if (e < 0 || e >= r) throw new Error("pos must more then 0 and less then the list length");
for (var t = o; e-- && t;) t = t.next;
if (!t || void 0 === t.value) throw new Error("unknown error");
return t.value;
}, this.eraseElementByPos = function (e) {
if (e < 0 || e >= r) throw new Error("erase pos must more then 0 and less then the list length");
if (0 === e) this.popFront();else if (e === r - 1) this.popBack();else {
for (var t = o; e--;) {
if (!(null === t || void 0 === t ? void 0 : t.next)) throw new Error("unknown error");
t = t.next;
}
if (!t || !t.pre || !t.next) throw new Error("unknown error");
var n = t.pre,
i = t.next;
i.pre = n, n.next = i, r > 0 && --r;
}
}, this.eraseElementByValue = function (e) {
for (; o && o.value === e;) this.popFront();
for (; s && s.value === e;) this.popBack();
if (o) for (var t = o; t;) {
if (t.value === e) {
var n = t.pre,
i = t.next;
i && (i.pre = n), n && (n.next = i), r > 0 && --r;
}
t = t.next;
}
}, this.pushBack = function (e) {
if (null === e || void 0 === e) throw new Error("you can't push null or undefined here");
++r;
var t = new i(e);
s ? (s.next = t, t.pre = s, s = t) : o = s = t;
}, this.popBack = function () {
s && (r > 0 && --r, s && (o === s ? o = s = void 0 : (s = s.pre) && (s.next = void 0)));
}, this.setElementByPos = function (e, t) {
if (null === t || void 0 === t) throw new Error("you can't set null or undefined here");
if (e < 0 || e >= r) throw new Error("pos must more then 0 and less then the list length");
for (var n = o; e--;) {
if (!n) throw new Error("unknown error");
n = n.next;
}
n && (n.value = t);
}, this.insert = function (e, t, n) {
if (void 0 === n && (n = 1), null === t || void 0 === t) throw new Error("you can't insert null or undefined here");
if (e < 0 || e > r) throw new Error("insert pos must more then 0 and less then or equal to the list length");
if (n < 0) throw new Error("insert size must more than 0");
if (0 === e) for (; n--;) this.pushFront(t);else if (e === r) for (; n--;) this.pushBack(t);else {
for (var s = o, a = 1; a < e; ++a) {
if (!(null === s || void 0 === s ? void 0 : s.next)) throw new Error("unknown error");
s = null === s || void 0 === s ? void 0 : s.next;
}
if (!s) throw new Error("unknown error");
var l = s.next;
for (r += n; n--;) s.next = new i(t), s.next.pre = s, s = s.next;
s.next = l, l && (l.pre = s);
}
}, this.find = function (e) {
for (var t = o; t;) {
if (t.value === e) return !0;
t = t.next;
}
return !1;
}, this.reverse = function () {
for (var e = o, t = s, n = 0; e && t && 2 * n < r;) {
var i = e.value;
e.value = t.value, t.value = i, e = e.next, t = t.pre, ++n;
}
}, this.unique = function () {
for (var e = o; e;) {
for (var t = e; t && t.next && t.value === t.next.value;) t = t.next, r > 0 && --r;
e.next = t.next, e.next && (e.next.pre = e), e = e.next;
}
}, this.sort = function (e) {
var t = [];
this.forEach(function (e) {
t.push(e);
}), t.sort(e);
var r = o;
t.forEach(function (e) {
r && (r.value = e, r = r.next);
});
}, this.pushFront = function (e) {
if (null === e || void 0 === e) throw new Error("you can't push null or undefined here");
++r;
var t = new i(e);
o ? (t.next = o, o.pre = t, o = t) : o = s = t;
}, this.popFront = function () {
o && (r > 0 && --r, o && (o === s ? o = s = void 0 : (o = o.next) && (o.pre = void 0)));
}, this.merge = function (e) {
var t = this,
n = o;
e.forEach(function (e) {
for (; n && void 0 !== n.value && n.value <= e;) n = n.next;
if (void 0 === n) t.pushBack(e), n = s;else if (n === o) t.pushFront(e), n = o;else {
++r;
var a = n.pre;
a && (a.next = new i(e), a.next.pre = a, a.next.next = n, n && (n.pre = a.next));
}
});
}, this[Symbol.iterator] = function () {
return function () {
var e;
return n(this, function (t) {
switch (t.label) {
case 0:
e = o, t.label = 1;
case 1:
if (void 0 === e) return [3, 3];
if (!e.value) throw new Error("unknown error");
return [4, e.value];
case 2:
return t.sent(), e = e.next, [3, 1];
case 3:
return [2];
}
});
}();
}, e.forEach(function (e) {
return t.pushBack(e);
}), Object.freeze(this);
}
Object.freeze(o), r.default = o;
}, {}],
30: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
},
i = this && this.__values || function (e) {
var t = "function" == typeof Symbol && Symbol.iterator,
r = t && e[t],
n = 0;
if (r) return r.call(e);
if (e && "number" == typeof e.length) return {
next: function () {
return e && n >= e.length && (e = void 0), {
value: e && e[n++],
done: !e
};
}
};
throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(r, "__esModule", {
value: !0
});
var o = e("../Base/TreeNode");
function s(e, t) {
var r = this;
void 0 === e && (e = []), t = t || function (e, t) {
return e < t ? -1 : e > t ? 1 : 0;
};
var s = 0,
a = new o.default();
a.color = o.default.TreeNodeColorType.black, this.size = function () {
return s;
}, this.empty = function () {
return 0 === s;
}, this.clear = function () {
s = 0, a.key = a.value = void 0, a.leftChild = a.rightChild = a.brother = void 0;
};
var l = function (e) {
if (!e || void 0 === e.key) throw new Error("unknown error");
return e.leftChild ? l(e.leftChild) : e;
},
u = function (e) {
if (!e || void 0 === e.key) throw new Error("unknown error");
return e.rightChild ? u(e.rightChild) : e;
};
this.front = function () {
if (!this.empty()) {
var e = l(a);
if (void 0 === e.key || void 0 === e.value) throw new Error("unknown error");
return {
key: e.key,
value: e.value
};
}
}, this.back = function () {
if (!this.empty()) {
var e = u(a);
if (void 0 === e.key || void 0 === e.value) throw new Error("unknown error");
return {
key: e.key,
value: e.value
};
}
}, this.forEach = function (e) {
var t,
r,
n = 0;
try {
for (var o = i(this), s = o.next(); !s.done; s = o.next()) {
e(s.value, n++);
}
} catch (e) {
t = {
error: e
};
} finally {
try {
s && !s.done && (r = o.return) && r.call(o);
} finally {
if (t) throw t.error;
}
}
}, this.getElementByPos = function (e) {
var t, r;
if (e < 0 || e >= this.size()) throw new Error("pos must more than 0 and less than set's size");
var n = 0;
try {
for (var o = i(this), s = o.next(); !s.done; s = o.next()) {
var a = s.value;
if (n === e) return a;
++n;
}
} catch (e) {
t = {
error: e
};
} finally {
try {
s && !s.done && (r = o.return) && r.call(o);
} finally {
if (t) throw t.error;
}
}
throw new Error("unknown Error");
};
var c = function (e, r) {
if (e && void 0 !== e.key && void 0 !== e.value) {
var n = t(e.key, r);
return 0 === n ? {
key: e.key,
value: e.value
} : n < 0 ? c(e.rightChild, r) : c(e.leftChild, r) || {
key: e.key,
value: e.value
};
}
};
this.lowerBound = function (e) {
return c(a, e);
};
var h = function (e, r) {
if (e && void 0 !== e.key && void 0 !== e.value) return t(e.key, r) <= 0 ? h(e.rightChild, r) : h(e.leftChild, r) || {
key: e.key,
value: e.value
};
};
this.upperBound = function (e) {
return h(a, e);
};
var f = function (e, r) {
if (e && void 0 !== e.key && void 0 !== e.value) {
var n = t(e.key, r);
return 0 === n ? {
key: e.key,
value: e.value
} : n > 0 ? f(e.leftChild, r) : f(e.rightChild, r) || {
key: e.key,
value: e.value
};
}
};
this.reverseLowerBound = function (e) {
return f(a, e);
};
var p = function (e, r) {
if (e && void 0 !== e.key && void 0 !== e.value) return t(e.key, r) >= 0 ? p(e.leftChild, r) : p(e.rightChild, r) || {
key: e.key,
value: e.value
};
};
this.reverseUpperBound = function (e) {
return p(a, e);
};
var d = function (e) {
var t = e.parent;
if (!t) {
if (e === a) return;
throw new Error("unknown error");
}
if (e.color !== o.default.TreeNodeColorType.red) {
var r = e.brother;
if (!r) throw new Error("unknown error");
if (e === t.leftChild) {
if (r.color === o.default.TreeNodeColorType.red) {
r.color = o.default.TreeNodeColorType.black, t.color = o.default.TreeNodeColorType.red;
var n = t.rotateLeft();
a === t && (a = n), d(e);
} else if (r.color === o.default.TreeNodeColorType.black) if (r.rightChild && r.rightChild.color === o.default.TreeNodeColorType.red) {
r.color = t.color, t.color = o.default.TreeNodeColorType.black, r.rightChild && (r.rightChild.color = o.default.TreeNodeColorType.black);
n = t.rotateLeft();
a === t && (a = n), e.color = o.default.TreeNodeColorType.black;
} else if (r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || !r.leftChild || r.leftChild.color !== o.default.TreeNodeColorType.red) r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || (r.color = o.default.TreeNodeColorType.red, d(t));else {
r.color = o.default.TreeNodeColorType.red, r.leftChild && (r.leftChild.color = o.default.TreeNodeColorType.black);
n = r.rotateRight();
a === r && (a = n), d(e);
}
} else if (e === t.rightChild) if (r.color === o.default.TreeNodeColorType.red) {
r.color = o.default.TreeNodeColorType.black, t.color = o.default.TreeNodeColorType.red;
n = t.rotateRight();
a === t && (a = n), d(e);
} else if (r.color === o.default.TreeNodeColorType.black) if (r.leftChild && r.leftChild.color === o.default.TreeNodeColorType.red) {
r.color = t.color, t.color = o.default.TreeNodeColorType.black, r.leftChild && (r.leftChild.color = o.default.TreeNodeColorType.black);
n = t.rotateRight();
a === t && (a = n), e.color = o.default.TreeNodeColorType.black;
} else if (r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || !r.rightChild || r.rightChild.color !== o.default.TreeNodeColorType.red) r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || (r.color = o.default.TreeNodeColorType.red, d(t));else {
r.color = o.default.TreeNodeColorType.red, r.rightChild && (r.rightChild.color = o.default.TreeNodeColorType.black);
n = r.rotateLeft();
a === r && (a = n), d(e);
}
} else e.color = o.default.TreeNodeColorType.black;
},
g = function (e) {
for (var t = e; t.leftChild || t.rightChild;) {
if (t.rightChild) {
t = l(t.rightChild);
var r = e.key;
e.key = t.key, t.key = r;
var n = e.value;
e.value = t.value, t.value = n, e = t;
}
if (t.leftChild) {
t = u(t.leftChild);
r = e.key;
e.key = t.key, t.key = r;
n = e.value;
e.value = t.value, t.value = n, e = t;
}
}
d(t), t && t.remove(), --s, a.color = o.default.TreeNodeColorType.black;
},
y = function (e, t) {
return !(!e || void 0 === e.key) && (!!y(e.leftChild, t) || !!t(e) || y(e.rightChild, t));
};
this.eraseElementByPos = function (e) {
if (e < 0 || e >= s) throw new Error("pos must more than 0 and less than set's size");
var t = 0;
y(a, function (r) {
return e === t ? (g(r), !0) : (++t, !1);
});
}, this.eraseElementByKey = function (e) {
if (!this.empty()) {
var r = v(a, e);
void 0 !== r && void 0 !== r.key && 0 === t(r.key, e) && g(r);
}
};
var b = function (e, r) {
if (!e || void 0 === e.key) throw new Error("unknown error");
var n = t(r, e.key);
return n < 0 ? e.leftChild ? b(e.leftChild, r) : (e.leftChild = new o.default(), e.leftChild.parent = e, e.leftChild.brother = e.rightChild, e.rightChild && (e.rightChild.brother = e.leftChild), e.leftChild) : n > 0 ? e.rightChild ? b(e.rightChild, r) : (e.rightChild = new o.default(), e.rightChild.parent = e, e.rightChild.brother = e.leftChild, e.leftChild && (e.leftChild.brother = e.rightChild), e.rightChild) : e;
},
m = function (e) {
var t = e.parent;
if (!t) {
if (e === a) return;
throw new Error("unknown error");
}
if (t.color !== o.default.TreeNodeColorType.black && t.color === o.default.TreeNodeColorType.red) {
var r = t.brother,
n = t.parent;
if (!n) throw new Error("unknown error");
if (r && r.color === o.default.TreeNodeColorType.red) r.color = t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red, m(n);else if (!r || r.color === o.default.TreeNodeColorType.black) if (t === n.leftChild) {
if (e === t.leftChild) {
t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red;
var i = n.rotateRight();
n === a && (a = i);
} else if (e === t.rightChild) {
i = t.rotateLeft();
n === a && (a = i), m(t);
}
} else if (t === n.rightChild) if (e === t.leftChild) {
i = t.rotateRight();
n === a && (a = i), m(t);
} else if (e === t.rightChild) {
t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red;
i = n.rotateLeft();
n === a && (a = i);
}
}
};
this.setElement = function (e, r) {
if (null === e || void 0 === e) throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
if (null !== r && void 0 !== r) {
if (this.empty()) return ++s, a.key = e, a.value = r, void (a.color = o.default.TreeNodeColorType.black);
var n = b(a, e);
void 0 === n.key || 0 !== t(n.key, e) ? (++s, n.key = e, n.value = r, m(n), a.color = o.default.TreeNodeColorType.black) : n.value = r;
} else this.eraseElementByKey(e);
};
var v = function (e, r) {
if (e && void 0 !== e.key) {
var n = t(r, e.key);
return n < 0 ? v(e.leftChild, r) : n > 0 ? v(e.rightChild, r) : e;
}
};
this.find = function (e) {
return !!v(a, e);
}, this.getElementByKey = function (e) {
var t = v(a, e);
if (void 0 === (null === t || void 0 === t ? void 0 : t.key) || void 0 === (null === t || void 0 === t ? void 0 : t.value)) throw new Error("unknown error");
return t.value;
}, this.union = function (e) {
var t = this;
e.forEach(function (e) {
var r = e.key,
n = e.value;
return t.setElement(r, n);
});
}, this.getHeight = function () {
if (this.empty()) return 0;
var e = function (t) {
return t ? Math.max(e(t.leftChild), e(t.rightChild)) + 1 : 1;
};
return e(a);
};
var w = function (e) {
return n(this, function (t) {
switch (t.label) {
case 0:
return e && void 0 !== e.key && void 0 !== e.value ? [5, i(w(e.leftChild))] : [2];
case 1:
return t.sent(), [4, {
key: e.key,
value: e.value
}];
case 2:
return t.sent(), [5, i(w(e.rightChild))];
case 3:
return t.sent(), [2];
}
});
};
this[Symbol.iterator] = function () {
return w(a);
}, e.forEach(function (e) {
var t = e.key,
n = e.value;
return r.setElement(t, n);
}), Object.freeze(this);
}
Object.freeze(s), r.default = s;
}, {
"../Base/TreeNode": 25
}],
31: [function (e, t, r) {
function n(e, t) {
void 0 === e && (e = []), t = t || function (e, t) {
return e > t ? -1 : e < t ? 1 : 0;
};
var r = [];
e.forEach(function (e) {
return r.push(e);
});
var n = r.length,
i = function (e, t) {
if (e < 0 || e >= n) throw new Error("unknown error");
if (t < 0 || t >= n) throw new Error("unknown error");
var i = r[e];
r[e] = r[t], r[t] = i;
},
o = function (e) {
if (e < 0 || e >= n) throw new Error("unknown error");
var o = 2 * e + 1,
s = 2 * e + 2;
o < n && t(r[e], r[o]) > 0 && i(e, o), s < n && t(r[e], r[s]) > 0 && i(e, s);
};
!function () {
for (var e = Math.floor((n - 1) / 2); e >= 0; --e) for (var o = e, s = 2 * o + 1; s < n;) {
var a = s + 1,
l = s;
if (a < n && t(r[s], r[a]) > 0 && (l = a), t(r[o], r[l]) <= 0) break;
i(o, l), s = 2 * (o = l) + 1;
}
}(), this.size = function () {
return n;
}, this.empty = function () {
return 0 === n;
}, this.clear = function () {
n = 0, r.length = 0;
}, this.push = function (e) {
if (r.push(e), 1 !== ++n) for (var i = n - 1; i > 0;) {
var s = Math.floor((i - 1) / 2);
if (t(r[s], e) <= 0) break;
o(s), i = s;
}
}, this.pop = function () {
if (!this.empty()) if (1 !== this.size()) {
var e = r[n - 1];
--n;
for (var i = 0; i < this.size();) {
var o = 2 * i + 1,
s = 2 * i + 2;
if (o >= this.size()) break;
var a = o;
if (s < this.size() && t(r[o], r[s]) > 0 && (a = s), t(r[a], e) >= 0) break;
r[i] = r[a], i = a;
}
r[i] = e;
} else --n;
}, this.top = function () {
return r[0];
}, Object.freeze(this);
}
Object.defineProperty(r, "__esModule", {
value: !0
}), Object.freeze(n), r.default = n;
}, {}],
32: [function (e, t, r) {
Object.defineProperty(r, "__esModule", {
value: !0
});
var n = e("../LinkList/LinkList");
function i(e) {
void 0 === e && (e = []);
var t = new n.default(e);
this.size = function () {
return t.size();
}, this.empty = function () {
return t.empty();
}, this.clear = function () {
t.clear();
}, this.push = function (e) {
t.pushBack(e);
}, this.pop = function () {
t.popFront();
}, this.front = function () {
return t.front();
}, Object.freeze(this);
}
Object.freeze(i), r.default = i;
}, {
"../LinkList/LinkList": 29
}],
33: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
},
i = this && this.__values || function (e) {
var t = "function" == typeof Symbol && Symbol.iterator,
r = t && e[t],
n = 0;
if (r) return r.call(e);
if (e && "number" == typeof e.length) return {
next: function () {
return e && n >= e.length && (e = void 0), {
value: e && e[n++],
done: !e
};
}
};
throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(r, "__esModule", {
value: !0
});
var o = e("../Base/TreeNode");
function s(e, t) {
var r = this;
void 0 === e && (e = []), t = t || function (e, t) {
return e < t ? -1 : e > t ? 1 : 0;
};
var s = 0,
a = new o.default();
a.color = o.default.TreeNodeColorType.black, this.size = function () {
return s;
}, this.empty = function () {
return 0 === s;
}, this.clear = function () {
s = 0, a.key = void 0, a.leftChild = a.rightChild = a.brother = a.parent = void 0, a.color = o.default.TreeNodeColorType.black;
};
var l = function (e) {
if (!e || void 0 === e.key) throw new Error("unknown error");
return e.leftChild ? l(e.leftChild) : e;
},
u = function (e) {
if (!e || void 0 === e.key) throw new Error("unknown error");
return e.rightChild ? u(e.rightChild) : e;
};
this.front = function () {
if (!this.empty()) return l(a).key;
}, this.back = function () {
if (!this.empty()) return u(a).key;
}, this.forEach = function (e) {
var t,
r,
n = 0;
try {
for (var o = i(this), s = o.next(); !s.done; s = o.next()) {
e(s.value, n++);
}
} catch (e) {
t = {
error: e
};
} finally {
try {
s && !s.done && (r = o.return) && r.call(o);
} finally {
if (t) throw t.error;
}
}
}, this.getElementByPos = function (e) {
var t, r;
if (e < 0 || e >= this.size()) throw new Error("pos must more than 0 and less than set's size");
var n = 0;
try {
for (var o = i(this), s = o.next(); !s.done; s = o.next()) {
var a = s.value;
if (n === e) return a;
++n;
}
} catch (e) {
t = {
error: e
};
} finally {
try {
s && !s.done && (r = o.return) && r.call(o);
} finally {
if (t) throw t.error;
}
}
throw new Error("unknown error");
};
var c = function (e) {
var t = e.parent;
if (!t) {
if (e === a) return;
throw new Error("unknown error");
}
if (e.color !== o.default.TreeNodeColorType.red) {
var r = e.brother;
if (!r) throw new Error("unknown error");
if (e === t.leftChild) {
if (r.color === o.default.TreeNodeColorType.red) {
r.color = o.default.TreeNodeColorType.black, t.color = o.default.TreeNodeColorType.red;
var n = t.rotateLeft();
a === t && (a = n), c(e);
} else if (r.color === o.default.TreeNodeColorType.black) if (r.rightChild && r.rightChild.color === o.default.TreeNodeColorType.red) {
r.color = t.color, t.color = o.default.TreeNodeColorType.black, r.rightChild && (r.rightChild.color = o.default.TreeNodeColorType.black);
n = t.rotateLeft();
a === t && (a = n), e.color = o.default.TreeNodeColorType.black;
} else if (r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || !r.leftChild || r.leftChild.color !== o.default.TreeNodeColorType.red) r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || (r.color = o.default.TreeNodeColorType.red, c(t));else {
r.color = o.default.TreeNodeColorType.red, r.leftChild && (r.leftChild.color = o.default.TreeNodeColorType.black);
n = r.rotateRight();
a === r && (a = n), c(e);
}
} else if (e === t.rightChild) if (r.color === o.default.TreeNodeColorType.red) {
r.color = o.default.TreeNodeColorType.black, t.color = o.default.TreeNodeColorType.red;
n = t.rotateRight();
a === t && (a = n), c(e);
} else if (r.color === o.default.TreeNodeColorType.black) if (r.leftChild && r.leftChild.color === o.default.TreeNodeColorType.red) {
r.color = t.color, t.color = o.default.TreeNodeColorType.black, r.leftChild && (r.leftChild.color = o.default.TreeNodeColorType.black);
n = t.rotateRight();
a === t && (a = n), e.color = o.default.TreeNodeColorType.black;
} else if (r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || !r.rightChild || r.rightChild.color !== o.default.TreeNodeColorType.red) r.leftChild && r.leftChild.color !== o.default.TreeNodeColorType.black || r.rightChild && r.rightChild.color !== o.default.TreeNodeColorType.black || (r.color = o.default.TreeNodeColorType.red, c(t));else {
r.color = o.default.TreeNodeColorType.red, r.rightChild && (r.rightChild.color = o.default.TreeNodeColorType.black);
n = r.rotateLeft();
a === r && (a = n), c(e);
}
} else e.color = o.default.TreeNodeColorType.black;
},
h = function (e) {
for (var t = e; t.leftChild || t.rightChild;) {
if (t.rightChild) {
t = l(t.rightChild);
var r = e.key;
e.key = t.key, t.key = r, e = t;
}
if (t.leftChild) {
t = u(t.leftChild);
r = e.key;
e.key = t.key, t.key = r, e = t;
}
}
c(t), t && t.remove(), --s, a.color = o.default.TreeNodeColorType.black;
},
f = function (e, t) {
return !(!e || void 0 === e.key) && (!!f(e.leftChild, t) || !!t(e) || f(e.rightChild, t));
};
this.eraseElementByPos = function (e) {
if (e < 0 || e >= s) throw new Error("pos must more than 0 and less than set's size");
var t = 0;
f(a, function (r) {
return e === t ? (h(r), !0) : (++t, !1);
});
}, this.eraseElementByValue = function (e) {
if (!this.empty()) {
var r = g(a, e);
void 0 !== r && void 0 !== r.key && 0 === t(r.key, e) && h(r);
}
};
var p = function (e, r) {
if (!e || void 0 === e.key) throw new Error("unknown error");
var n = t(r, e.key);
return n < 0 ? e.leftChild ? p(e.leftChild, r) : (e.leftChild = new o.default(), e.leftChild.parent = e, e.leftChild.brother = e.rightChild, e.rightChild && (e.rightChild.brother = e.leftChild), e.leftChild) : n > 0 ? e.rightChild ? p(e.rightChild, r) : (e.rightChild = new o.default(), e.rightChild.parent = e, e.rightChild.brother = e.leftChild, e.leftChild && (e.leftChild.brother = e.rightChild), e.rightChild) : e;
},
d = function (e) {
var t = e.parent;
if (!t) {
if (e === a) return;
throw new Error("unknown error");
}
if (t.color !== o.default.TreeNodeColorType.black && t.color === o.default.TreeNodeColorType.red) {
var r = t.brother,
n = t.parent;
if (!n) throw new Error("unknown error");
if (r && r.color === o.default.TreeNodeColorType.red) r.color = t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red, d(n);else if (!r || r.color === o.default.TreeNodeColorType.black) if (t === n.leftChild) {
if (e === t.leftChild) {
t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red;
var i = n.rotateRight();
n === a && (a = i);
} else if (e === t.rightChild) {
i = t.rotateLeft();
n === a && (a = i), d(t);
}
} else if (t === n.rightChild) if (e === t.leftChild) {
i = t.rotateRight();
n === a && (a = i), d(t);
} else if (e === t.rightChild) {
t.color = o.default.TreeNodeColorType.black, n.color = o.default.TreeNodeColorType.red;
i = n.rotateLeft();
n === a && (a = i);
}
}
};
this.insert = function (e) {
if (null === e || void 0 === e) throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
if (this.empty()) return ++s, a.key = e, void (a.color = o.default.TreeNodeColorType.black);
var r = p(a, e);
void 0 !== r.key && 0 === t(r.key, e) || (++s, r.key = e, d(r), a.color = o.default.TreeNodeColorType.black);
};
var g = function (e, r) {
if (e && void 0 !== e.key) {
var n = t(r, e.key);
return n < 0 ? g(e.leftChild, r) : n > 0 ? g(e.rightChild, r) : e;
}
};
this.find = function (e) {
var r = g(a, e);
return void 0 !== r && void 0 !== r.key && 0 === t(r.key, e);
};
var y = function (e, r) {
if (e && void 0 !== e.key) {
var n = t(e.key, r);
if (0 === n) return e.key;
if (n < 0) return y(e.rightChild, r);
var i = y(e.leftChild, r);
return void 0 !== i ? i : e.key;
}
};
this.lowerBound = function (e) {
return y(a, e);
};
var b = function (e, r) {
if (e && void 0 !== e.key) {
if (t(e.key, r) <= 0) return b(e.rightChild, r);
var n = b(e.leftChild, r);
return void 0 !== n ? n : e.key;
}
};
this.upperBound = function (e) {
return b(a, e);
};
var m = function (e, r) {
if (e && void 0 !== e.key) {
var n = t(e.key, r);
if (0 === n) return e.key;
if (n > 0) return m(e.leftChild, r);
var i = m(e.rightChild, r);
return void 0 !== i ? i : e.key;
}
};
this.reverseLowerBound = function (e) {
return m(a, e);
};
var v = function (e, r) {
if (e && void 0 !== e.key) {
if (t(e.key, r) >= 0) return v(e.leftChild, r);
var n = v(e.rightChild, r);
return void 0 !== n ? n : e.key;
}
};
this.reverseUpperBound = function (e) {
return v(a, e);
}, this.union = function (e) {
var t = this;
e.forEach(function (e) {
return t.insert(e);
});
}, this.getHeight = function () {
if (this.empty()) return 0;
var e = function (t) {
return t ? Math.max(e(t.leftChild), e(t.rightChild)) + 1 : 1;
};
return e(a);
};
var w = function (e) {
return n(this, function (t) {
switch (t.label) {
case 0:
return e && void 0 !== e.key ? [5, i(w(e.leftChild))] : [2];
case 1:
return t.sent(), [4, e.key];
case 2:
return t.sent(), [5, i(w(e.rightChild))];
case 3:
return t.sent(), [2];
}
});
};
this[Symbol.iterator] = function () {
return w(a);
}, e.forEach(function (e) {
return r.insert(e);
}), Object.freeze(this);
}
Object.freeze(s), r.default = s;
}, {
"../Base/TreeNode": 25
}],
34: [function (e, t, r) {
function n(e) {
var t = this;
void 0 === e && (e = []);
var r = 0,
n = [];
this.size = function () {
return r;
}, this.empty = function () {
return 0 === r;
}, this.clear = function () {
r = 0, n.length = 0;
}, this.push = function (e) {
n.push(e), ++r;
}, this.pop = function () {
n.pop(), r > 0 && --r;
}, this.top = function () {
return n[r - 1];
}, e.forEach(function (e) {
return t.push(e);
}), Object.freeze(this);
}
Object.defineProperty(r, "__esModule", {
value: !0
}), Object.freeze(n), r.default = n;
}, {}],
35: [function (e, t, r) {
var n = this && this.__generator || function (e, t) {
var r,
n,
i,
o,
s = {
label: 0,
sent: function () {
if (1 & i[0]) throw i[1];
return i[1];
},
trys: [],
ops: []
};
return o = {
next: a(0),
throw: a(1),
return: a(2)
}, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
return this;
}), o;
function a(o) {
return function (a) {
return function (o) {
if (r) throw new TypeError("Generator is already executing.");
for (; s;) try {
if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;
switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {
case 0:
case 1:
i = o;
break;
case 4:
return s.label++, {
value: o[1],
done: !1
};
case 5:
s.label++, n = o[1], o = [0];
continue;
case 7:
o = s.ops.pop(), s.trys.pop();
continue;
default:
if (!(i = (i = s.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
s = 0;
continue;
}
if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
s.label = o[1];
break;
}
if (6 === o[0] && s.label < i[1]) {
s.label = i[1], i = o;
break;
}
if (i && s.label < i[2]) {
s.label = i[2], s.ops.push(o);
break;
}
i[2] && s.ops.pop(), s.trys.pop();
continue;
}
o = t.call(e, s);
} catch (e) {
o = [6, e], n = 0;
} finally {
r = i = 0;
}
if (5 & o[0]) throw o[1];
return {
value: o[0] ? o[1] : void 0,
done: !0
};
}([o, a]);
};
}
},
i = this && this.__read || function (e, t) {
var r = "function" == typeof Symbol && e[Symbol.iterator];
if (!r) return e;
var n,
i,
o = r.call(e),
s = [];
try {
for (; (void 0 === t || t-- > 0) && !(n = o.next()).done;) s.push(n.value);
} catch (e) {
i = {
error: e
};
} finally {
try {
n && !n.done && (r = o.return) && r.call(o);
} finally {
if (i) throw i.error;
}
}
return s;
},
o = this && this.__spreadArray || function (e, t, r) {
if (r || 2 === arguments.length) for (var n, i = 0, o = t.length; i < o; i++) !n && i in t || (n || (n = Array.prototype.slice.call(t, 0, i)), n[i] = t[i]);
return e.concat(n || Array.prototype.slice.call(t));
},
s = this && this.__values || function (e) {
var t = "function" == typeof Symbol && Symbol.iterator,
r = t && e[t],
n = 0;
if (r) return r.call(e);
if (e && "number" == typeof e.length) return {
next: function () {
return e && n >= e.length && (e = void 0), {
value: e && e[n++],
done: !e
};
}
};
throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
function a(e) {
var t = this;
void 0 === e && (e = []);
var r = 0,
a = [];
this.size = function () {
return r;
}, this.empty = function () {
return 0 === r;
}, this.clear = function () {
r = 0, a.length = 0;
}, this.front = function () {
if (!this.empty()) return a[0];
}, this.back = function () {
if (!this.empty()) return a[r - 1];
}, this.forEach = function (e) {
a.forEach(e);
}, this.getElementByPos = function (e) {
if (e < 0 || e >= r) throw new Error("pos must more than 0 and less than vector's size");
return a[e];
}, this.eraseElementByPos = function (e) {
if (e < 0 || e >= r) throw new Error("pos must more than 0 and less than vector's size");
for (var t = e; t < r - 1; ++t) a[t] = a[t + 1];
this.popBack();
}, this.eraseElementByValue = function (e) {
var t = [];
this.forEach(function (r) {
r !== e && t.push(r);
}), t.forEach(function (e, t) {
a[t] = e;
});
for (var n = t.length; r > n;) this.popBack();
}, this.pushBack = function (e) {
a.push(e), ++r;
}, this.popBack = function () {
a.pop(), r > 0 && --r;
}, this.setElementByPos = function (e, t) {
if (e < 0 || e >= r) throw new Error("pos must more than 0 and less than vector's size");
a[e] = t;
}, this.insert = function (e, t, n) {
if (void 0 === n && (n = 1), e < 0 || e > r) throw new Error("pos must more than 0 and less than or equal to vector's size");
a.splice.apply(a, o([e, 0], i(new Array(n).fill(t)), !1)), r += n;
}, this.find = function (e) {
return a.includes(e);
}, this.reverse = function () {
a.reverse();
}, this.unique = function () {
var e,
t = [];
this.forEach(function (r, n) {
0 !== n && r === e || (t.push(r), e = r);
}), t.forEach(function (e, t) {
a[t] = e;
});
for (var n = t.length; r > n;) this.popBack();
}, this.sort = function (e) {
a.sort(e);
}, this[Symbol.iterator] = function () {
return function () {
return n(this, function (e) {
switch (e.label) {
case 0:
return [5, s(a)];
case 1:
return [2, e.sent()];
}
});
}();
}, e.forEach(function (e) {
return t.pushBack(e);
}), Object.freeze(this);
}
Object.defineProperty(r, "__esModule", {
value: !0
}), Object.freeze(a), r.default = a;
}, {}],
36: [function (e, t, r) {
Object.defineProperty(r, "__esModule", {
value: !0
}), r.HashMap = r.HashSet = r.Map = r.Set = r.PriorityQueue = r.Deque = r.LinkList = r.Queue = r.Stack = r.Vector = void 0;
var n = e("./Vector/Vector");
r.Vector = n.default;
var i = e("./Stack/Stack");
r.Stack = i.default;
var o = e("./Queue/Queue");
r.Queue = o.default;
var s = e("./LinkList/LinkList");
r.LinkList = s.default;
var a = e("./Deque/Deque");
r.Deque = a.default;
var l = e("./PriorityQueue/PriorityQueue");
r.PriorityQueue = l.default;
var u = e("./Set/Set");
r.Set = u.default;
var c = e("./Map/Map");
r.Map = c.default;
var h = e("./HashSet/HashSet");
r.HashSet = h.default;
var f = e("./HashMap/HashMap");
r.HashMap = f.default;
}, {
"./Deque/Deque": 26,
"./HashMap/HashMap": 27,
"./HashSet/HashSet": 28,
"./LinkList/LinkList": 29,
"./Map/Map": 30,
"./PriorityQueue/PriorityQueue": 31,
"./Queue/Queue": 32,
"./Set/Set": 33,
"./Stack/Stack": 34,
"./Vector/Vector": 35
}],
37: [function (e, t, r) {
const n = e("yallist"),
i = Symbol("max"),
o = Symbol("length"),
s = Symbol("lengthCalculator"),
a = Symbol("allowStale"),
l = Symbol("maxAge"),
u = Symbol("dispose"),
c = Symbol("noDisposeOnSet"),
h = Symbol("lruList"),
f = Symbol("cache"),
p = Symbol("updateAgeOnGet"),
d = () => 1;
const g = (e, t, r) => {
const n = e[f].get(t);
if (n) {
const t = n.value;
if (y(e, t)) {
if (m(e, n), !e[a]) return;
} else r && (e[p] && (n.value.now = Date.now()), e[h].unshiftNode(n));
return t.value;
}
},
y = (e, t) => {
if (!t || !t.maxAge && !e[l]) return !1;
const r = Date.now() - t.now;
return t.maxAge ? r > t.maxAge : e[l] && r > e[l];
},
b = e => {
if (e[o] > e[i]) for (let t = e[h].tail; e[o] > e[i] && null !== t;) {
const r = t.prev;
m(e, t), t = r;
}
},
m = (e, t) => {
if (t) {
const r = t.value;
e[u] && e[u](r.key, r.value), e[o] -= r.length, e[f].delete(r.key), e[h].removeNode(t);
}
};
class v {
constructor(e, t, r, n, i) {
this.key = e, this.value = t, this.length = r, this.now = n, this.maxAge = i || 0;
}
}
const w = (e, t, r, n) => {
let i = r.value;
y(e, i) && (m(e, r), e[a] || (i = void 0)), i && t.call(n, i.value, i.key, e);
};
t.exports = class {
constructor(e) {
if ("number" == typeof e && (e = {
max: e
}), e || (e = {}), e.max && ("number" != typeof e.max || e.max < 0)) throw new TypeError("max must be a non-negative number");
this[i] = e.max || 1 / 0;
const t = e.length || d;
if (this[s] = "function" != typeof t ? d : t, this[a] = e.stale || !1, e.maxAge && "number" != typeof e.maxAge) throw new TypeError("maxAge must be a number");
this[l] = e.maxAge || 0, this[u] = e.dispose, this[c] = e.noDisposeOnSet || !1, this[p] = e.updateAgeOnGet || !1, this.reset();
}
set max(e) {
if ("number" != typeof e || e < 0) throw new TypeError("max must be a non-negative number");
this[i] = e || 1 / 0, b(this);
}
get max() {
return this[i];
}
set allowStale(e) {
this[a] = !!e;
}
get allowStale() {
return this[a];
}
set maxAge(e) {
if ("number" != typeof e) throw new TypeError("maxAge must be a non-negative number");
this[l] = e, b(this);
}
get maxAge() {
return this[l];
}
set lengthCalculator(e) {
"function" != typeof e && (e = d), e !== this[s] && (this[s] = e, this[o] = 0, this[h].forEach(e => {
e.length = this[s](e.value, e.key), this[o] += e.length;
})), b(this);
}
get lengthCalculator() {
return this[s];
}
get length() {
return this[o];
}
get itemCount() {
return this[h].length;
}
rforEach(e, t) {
t = t || this;
for (let r = this[h].tail; null !== r;) {
const n = r.prev;
w(this, e, r, t), r = n;
}
}
forEach(e, t) {
t = t || this;
for (let r = this[h].head; null !== r;) {
const n = r.next;
w(this, e, r, t), r = n;
}
}
keys() {
return this[h].toArray().map(e => e.key);
}
values() {
return this[h].toArray().map(e => e.value);
}
reset() {
this[u] && this[h] && this[h].length && this[h].forEach(e => this[u](e.key, e.value)), this[f] = new Map(), this[h] = new n(), this[o] = 0;
}
dump() {
return this[h].map(e => !y(this, e) && {
k: e.key,
v: e.value,
e: e.now + (e.maxAge || 0)
}).toArray().filter(e => e);
}
dumpLru() {
return this[h];
}
set(e, t, r) {
if ((r = r || this[l]) && "number" != typeof r) throw new TypeError("maxAge must be a number");
const n = r ? Date.now() : 0,
a = this[s](t, e);
if (this[f].has(e)) {
if (a > this[i]) return m(this, this[f].get(e)), !1;
const s = this[f].get(e).value;
return this[u] && (this[c] || this[u](e, s.value)), s.now = n, s.maxAge = r, s.value = t, this[o] += a - s.length, s.length = a, this.get(e), b(this), !0;
}
const p = new v(e, t, a, n, r);
return p.length > this[i] ? (this[u] && this[u](e, t), !1) : (this[o] += p.length, this[h].unshift(p), this[f].set(e, this[h].head), b(this), !0);
}
has(e) {
if (!this[f].has(e)) return !1;
const t = this[f].get(e).value;
return !y(this, t);
}
get(e) {
return g(this, e, !0);
}
peek(e) {
return g(this, e, !1);
}
pop() {
const e = this[h].tail;
return e ? (m(this, e), e.value) : null;
}
del(e) {
m(this, this[f].get(e));
}
load(e) {
this.reset();
const t = Date.now();
for (let r = e.length - 1; r >= 0; r--) {
const n = e[r],
i = n.e || 0;
if (0 === i) this.set(n.k, n.v);else {
const e = i - t;
e > 0 && this.set(n.k, n.v, e);
}
}
}
prune() {
this[f].forEach((e, t) => g(this, t, !1));
}
};
}, {
yallist: 83
}],
38: [function (e, t, r) {
(function (e) {
(function () {
const r = t.exports;
r.types = {
0: "reserved",
1: "connect",
2: "connack",
3: "publish",
4: "puback",
5: "pubrec",
6: "pubrel",
7: "pubcomp",
8: "subscribe",
9: "suback",
10: "unsubscribe",
11: "unsuback",
12: "pingreq",
13: "pingresp",
14: "disconnect",
15: "auth"
}, r.codes = {};
for (const e in r.types) {
const t = r.types[e];
r.codes[t] = e;
}
r.CMD_SHIFT = 4, r.CMD_MASK = 240, r.DUP_MASK = 8, r.QOS_MASK = 3, r.QOS_SHIFT = 1, r.RETAIN_MASK = 1, r.VARBYTEINT_MASK = 127, r.VARBYTEINT_FIN_MASK = 128, r.VARBYTEINT_MAX = 268435455, r.SESSIONPRESENT_MASK = 1, r.SESSIONPRESENT_HEADER = e.from([r.SESSIONPRESENT_MASK]), r.CONNACK_HEADER = e.from([r.codes.connack << r.CMD_SHIFT]), r.USERNAME_MASK = 128, r.PASSWORD_MASK = 64, r.WILL_RETAIN_MASK = 32, r.WILL_QOS_MASK = 24, r.WILL_QOS_SHIFT = 3, r.WILL_FLAG_MASK = 4, r.CLEAN_SESSION_MASK = 2, r.CONNECT_HEADER = e.from([r.codes.connect << r.CMD_SHIFT]), r.properties = {
sessionExpiryInterval: 17,
willDelayInterval: 24,
receiveMaximum: 33,
maximumPacketSize: 39,
topicAliasMaximum: 34,
requestResponseInformation: 25,
requestProblemInformation: 23,
userProperties: 38,
authenticationMethod: 21,
authenticationData: 22,
payloadFormatIndicator: 1,
messageExpiryInterval: 2,
contentType: 3,
responseTopic: 8,
correlationData: 9,
maximumQoS: 36,
retainAvailable: 37,
assignedClientIdentifier: 18,
reasonString: 31,
wildcardSubscriptionAvailable: 40,
subscriptionIdentifiersAvailable: 41,
sharedSubscriptionAvailable: 42,
serverKeepAlive: 19,
responseInformation: 26,
serverReference: 28,
topicAlias: 35,
subscriptionIdentifier: 11
}, r.propertiesCodes = {};
for (const e in r.properties) {
const t = r.properties[e];
r.propertiesCodes[t] = e;
}
function n(t) {
return [0, 1, 2].map(n => [0, 1].map(i => [0, 1].map(o => {
const s = e.alloc(1);
return s.writeUInt8(r.codes[t] << r.CMD_SHIFT | (i ? r.DUP_MASK : 0) | n << r.QOS_SHIFT | o, 0, !0), s;
})));
}
r.propertiesTypes = {
sessionExpiryInterval: "int32",
willDelayInterval: "int32",
receiveMaximum: "int16",
maximumPacketSize: "int32",
topicAliasMaximum: "int16",
requestResponseInformation: "byte",
requestProblemInformation: "byte",
userProperties: "pair",
authenticationMethod: "string",
authenticationData: "binary",
payloadFormatIndicator: "byte",
messageExpiryInterval: "int32",
contentType: "string",
responseTopic: "string",
correlationData: "binary",
maximumQoS: "int8",
retainAvailable: "byte",
assignedClientIdentifier: "string",
reasonString: "string",
wildcardSubscriptionAvailable: "byte",
subscriptionIdentifiersAvailable: "byte",
sharedSubscriptionAvailable: "byte",
serverKeepAlive: "int16",
responseInformation: "string",
serverReference: "string",
topicAlias: "int16",
subscriptionIdentifier: "var"
}, r.PUBLISH_HEADER = n("publish"), r.SUBSCRIBE_HEADER = n("subscribe"), r.SUBSCRIBE_OPTIONS_QOS_MASK = 3, r.SUBSCRIBE_OPTIONS_NL_MASK = 1, r.SUBSCRIBE_OPTIONS_NL_SHIFT = 2, r.SUBSCRIBE_OPTIONS_RAP_MASK = 1, r.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3, r.SUBSCRIBE_OPTIONS_RH_MASK = 3, r.SUBSCRIBE_OPTIONS_RH_SHIFT = 4, r.SUBSCRIBE_OPTIONS_RH = [0, 16, 32], r.SUBSCRIBE_OPTIONS_NL = 4, r.SUBSCRIBE_OPTIONS_RAP = 8, r.SUBSCRIBE_OPTIONS_QOS = [0, 1, 2], r.UNSUBSCRIBE_HEADER = n("unsubscribe"), r.ACKS = {
unsuback: n("unsuback"),
puback: n("puback"),
pubcomp: n("pubcomp"),
pubrel: n("pubrel"),
pubrec: n("pubrec")
}, r.SUBACK_HEADER = e.from([r.codes.suback << r.CMD_SHIFT]), r.VERSION3 = e.from([3]), r.VERSION4 = e.from([4]), r.VERSION5 = e.from([5]), r.VERSION131 = e.from([131]), r.VERSION132 = e.from([132]), r.QOS = [0, 1, 2].map(t => e.from([t])), r.EMPTY = {
pingreq: e.from([r.codes.pingreq << 4, 0]),
pingresp: e.from([r.codes.pingresp << 4, 0]),
disconnect: e.from([r.codes.disconnect << 4, 0])
};
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
buffer: 17
}],
39: [function (e, t, r) {
(function (r) {
(function () {
const n = e("./writeToStream"),
i = e("events");
class o extends i {
constructor() {
super(), this._array = new Array(20), this._i = 0;
}
write(e) {
return this._array[this._i++] = e, !0;
}
concat() {
let e = 0;
const t = new Array(this._array.length),
n = this._array;
let i,
o = 0;
for (i = 0; i < n.length && void 0 !== n[i]; i++) "string" != typeof n[i] ? t[i] = n[i].length : t[i] = r.byteLength(n[i]), e += t[i];
const s = r.allocUnsafe(e);
for (i = 0; i < n.length && void 0 !== n[i]; i++) "string" != typeof n[i] ? (n[i].copy(s, o), o += t[i]) : (s.write(n[i], o), o += t[i]);
return s;
}
}
t.exports = function (e, t) {
const r = new o();
return n(e, r, t), r.concat();
};
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
"./writeToStream": 44,
buffer: 17,
events: 22
}],
40: [function (e, t, r) {
r.parser = e("./parser").parser, r.generate = e("./generate"), r.writeToStream = e("./writeToStream");
}, {
"./generate": 39,
"./parser": 43,
"./writeToStream": 44
}],
41: [function (e, t, r) {
(function (e) {
(function () {
const r = 65536,
n = {},
i = e.isBuffer(e.from([1, 2]).subarray(0, 1));
function o(t) {
const r = e.allocUnsafe(2);
return r.writeUInt8(t >> 8, 0), r.writeUInt8(255 & t, 1), r;
}
t.exports = {
cache: n,
generateCache: function () {
for (let e = 0; e < r; e++) n[e] = o(e);
},
generateNumber: o,
genBufVariableByteInt: function (t) {
let r = 0,
n = 0;
const o = e.allocUnsafe(4);
do {
r = t % 128 | 0, (t = t / 128 | 0) > 0 && (r |= 128), o.writeUInt8(r, n++);
} while (t > 0 && n < 4);
return t > 0 && (n = 0), i ? o.subarray(0, n) : o.slice(0, n);
},
generate4ByteBuffer: function (t) {
const r = e.allocUnsafe(4);
return r.writeUInt32BE(t, 0), r;
}
};
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
buffer: 17
}],
42: [function (e, t, r) {
t.exports = class {
constructor() {
this.cmd = null, this.retain = !1, this.qos = 0, this.dup = !1, this.length = -1, this.topic = null, this.payload = null;
}
};
}, {}],
43: [function (e, t, r) {
const n = e("bl"),
i = e("events"),
o = e("./packet"),
s = e("./constants"),
a = e("debug")("mqtt-packet:parser");
class l extends i {
constructor() {
super(), this.parser = this.constructor.parser;
}
static parser(e) {
return this instanceof l ? (this.settings = e || {}, this._states = ["_parseHeader", "_parseLength", "_parsePayload", "_newPacket"], this._resetState(), this) : new l().parser(e);
}
_resetState() {
a("_resetState: resetting packet, error, _list, and _stateCounter"), this.packet = new o(), this.error = null, this._list = n(), this._stateCounter = 0;
}
parse(e) {
for (this.error && this._resetState(), this._list.append(e), a("parse: current state: %s", this._states[this._stateCounter]); (-1 !== this.packet.length || this._list.length > 0) && this[this._states[this._stateCounter]]() && !this.error;) this._stateCounter++, a("parse: state complete. _stateCounter is now: %d", this._stateCounter), a("parse: packet.length: %d, buffer list length: %d", this.packet.length, this._list.length), this._stateCounter >= this._states.length && (this._stateCounter = 0);
return a("parse: exited while loop. packet: %d, buffer list length: %d", this.packet.length, this._list.length), this._list.length;
}
_parseHeader() {
const e = this._list.readUInt8(0);
return this.packet.cmd = s.types[e >> s.CMD_SHIFT], this.packet.retain = 0 != (e & s.RETAIN_MASK), this.packet.qos = e >> s.QOS_SHIFT & s.QOS_MASK, this.packet.dup = 0 != (e & s.DUP_MASK), a("_parseHeader: packet: %o", this.packet), this._list.consume(1), !0;
}
_parseLength() {
const e = this._parseVarByteNum(!0);
return e && (this.packet.length = e.value, this._list.consume(e.bytes)), a("_parseLength %d", e.value), !!e;
}
_parsePayload() {
a("_parsePayload: payload %O", this._list);
let e = !1;
if (0 === this.packet.length || this._list.length >= this.packet.length) {
switch (this._pos = 0, this.packet.cmd) {
case "connect":
this._parseConnect();
break;
case "connack":
this._parseConnack();
break;
case "publish":
this._parsePublish();
break;
case "puback":
case "pubrec":
case "pubrel":
case "pubcomp":
this._parseConfirmation();
break;
case "subscribe":
this._parseSubscribe();
break;
case "suback":
this._parseSuback();
break;
case "unsubscribe":
this._parseUnsubscribe();
break;
case "unsuback":
this._parseUnsuback();
break;
case "pingreq":
case "pingresp":
break;
case "disconnect":
this._parseDisconnect();
break;
case "auth":
this._parseAuth();
break;
default:
this._emitError(new Error("Not supported"));
}
e = !0;
}
return a("_parsePayload complete result: %s", e), e;
}
_parseConnect() {
let e, t, r, n;
a("_parseConnect");
const i = {},
o = this.packet,
l = this._parseString();
if (null === l) return this._emitError(new Error("Cannot parse protocolId"));
if ("MQTT" !== l && "MQIsdp" !== l) return this._emitError(new Error("Invalid protocolId"));
if (o.protocolId = l, this._pos >= this._list.length) return this._emitError(new Error("Packet too short"));
if (o.protocolVersion = this._list.readUInt8(this._pos), o.protocolVersion >= 128 && (o.bridgeMode = !0, o.protocolVersion = o.protocolVersion - 128), 3 !== o.protocolVersion && 4 !== o.protocolVersion && 5 !== o.protocolVersion) return this._emitError(new Error("Invalid protocol version"));
if (this._pos++, this._pos >= this._list.length) return this._emitError(new Error("Packet too short"));
if (i.username = this._list.readUInt8(this._pos) & s.USERNAME_MASK, i.password = this._list.readUInt8(this._pos) & s.PASSWORD_MASK, i.will = this._list.readUInt8(this._pos) & s.WILL_FLAG_MASK, i.will && (o.will = {}, o.will.retain = 0 != (this._list.readUInt8(this._pos) & s.WILL_RETAIN_MASK), o.will.qos = (this._list.readUInt8(this._pos) & s.WILL_QOS_MASK) >> s.WILL_QOS_SHIFT), o.clean = 0 != (this._list.readUInt8(this._pos) & s.CLEAN_SESSION_MASK), this._pos++, o.keepalive = this._parseNum(), -1 === o.keepalive) return this._emitError(new Error("Packet too short"));
if (5 === o.protocolVersion) {
const e = this._parseProperties();
Object.getOwnPropertyNames(e).length && (o.properties = e);
}
const u = this._parseString();
if (null === u) return this._emitError(new Error("Packet too short"));
if (o.clientId = u, a("_parseConnect: packet.clientId: %s", o.clientId), i.will) {
if (5 === o.protocolVersion) {
const e = this._parseProperties();
Object.getOwnPropertyNames(e).length && (o.will.properties = e);
}
if (null === (e = this._parseString())) return this._emitError(new Error("Cannot parse will topic"));
if (o.will.topic = e, a("_parseConnect: packet.will.topic: %s", o.will.topic), null === (t = this._parseBuffer())) return this._emitError(new Error("Cannot parse will payload"));
o.will.payload = t, a("_parseConnect: packet.will.paylaod: %s", o.will.payload);
}
if (i.username) {
if (null === (n = this._parseString())) return this._emitError(new Error("Cannot parse username"));
o.username = n, a("_parseConnect: packet.username: %s", o.username);
}
if (i.password) {
if (null === (r = this._parseBuffer())) return this._emitError(new Error("Cannot parse password"));
o.password = r;
}
return this.settings = o, a("_parseConnect: complete"), o;
}
_parseConnack() {
a("_parseConnack");
const e = this.packet;
if (this._list.length < 1) return null;
if (e.sessionPresent = !!(this._list.readUInt8(this._pos++) & s.SESSIONPRESENT_MASK), 5 === this.settings.protocolVersion) this._list.length >= 2 ? e.reasonCode = this._list.readUInt8(this._pos++) : e.reasonCode = 0;else {
if (this._list.length < 2) return null;
e.returnCode = this._list.readUInt8(this._pos++);
}
if (-1 === e.returnCode || -1 === e.reasonCode) return this._emitError(new Error("Cannot parse return code"));
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
a("_parseConnack: complete");
}
_parsePublish() {
a("_parsePublish");
const e = this.packet;
if (e.topic = this._parseString(), null === e.topic) return this._emitError(new Error("Cannot parse topic"));
if (!(e.qos > 0) || this._parseMessageId()) {
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
e.payload = this._list.slice(this._pos, e.length), a("_parsePublish: payload from buffer list: %o", e.payload);
}
}
_parseSubscribe() {
a("_parseSubscribe");
const e = this.packet;
let t, r, n, i, o, l, u;
if (1 !== e.qos) return this._emitError(new Error("Wrong subscribe header"));
if (e.subscriptions = [], this._parseMessageId()) {
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
for (; this._pos < e.length;) {
if (null === (t = this._parseString())) return this._emitError(new Error("Cannot parse topic"));
if (this._pos >= e.length) return this._emitError(new Error("Malformed Subscribe Payload"));
n = (r = this._parseByte()) & s.SUBSCRIBE_OPTIONS_QOS_MASK, l = 0 != (r >> s.SUBSCRIBE_OPTIONS_NL_SHIFT & s.SUBSCRIBE_OPTIONS_NL_MASK), o = 0 != (r >> s.SUBSCRIBE_OPTIONS_RAP_SHIFT & s.SUBSCRIBE_OPTIONS_RAP_MASK), i = r >> s.SUBSCRIBE_OPTIONS_RH_SHIFT & s.SUBSCRIBE_OPTIONS_RH_MASK, u = {
topic: t,
qos: n
}, 5 === this.settings.protocolVersion ? (u.nl = l, u.rap = o, u.rh = i) : this.settings.bridgeMode && (u.rh = 0, u.rap = !0, u.nl = !0), a("_parseSubscribe: push subscription `%s` to subscription", u), e.subscriptions.push(u);
}
}
}
_parseSuback() {
a("_parseSuback");
const e = this.packet;
if (this.packet.granted = [], this._parseMessageId()) {
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
for (; this._pos < this.packet.length;) this.packet.granted.push(this._list.readUInt8(this._pos++));
}
}
_parseUnsubscribe() {
a("_parseUnsubscribe");
const e = this.packet;
if (e.unsubscriptions = [], this._parseMessageId()) {
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
for (; this._pos < e.length;) {
const t = this._parseString();
if (null === t) return this._emitError(new Error("Cannot parse topic"));
a("_parseUnsubscribe: push topic `%s` to unsubscriptions", t), e.unsubscriptions.push(t);
}
}
}
_parseUnsuback() {
a("_parseUnsuback");
const e = this.packet;
if (!this._parseMessageId()) return this._emitError(new Error("Cannot parse messageId"));
if (5 === this.settings.protocolVersion) {
const t = this._parseProperties();
for (Object.getOwnPropertyNames(t).length && (e.properties = t), e.granted = []; this._pos < this.packet.length;) this.packet.granted.push(this._list.readUInt8(this._pos++));
}
}
_parseConfirmation() {
a("_parseConfirmation: packet.cmd: `%s`", this.packet.cmd);
const e = this.packet;
if (this._parseMessageId(), 5 === this.settings.protocolVersion && (e.length > 2 ? (e.reasonCode = this._parseByte(), a("_parseConfirmation: packet.reasonCode `%d`", e.reasonCode)) : e.reasonCode = 0, e.length > 3)) {
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
return !0;
}
_parseDisconnect() {
const e = this.packet;
if (a("_parseDisconnect"), 5 === this.settings.protocolVersion) {
this._list.length > 0 ? e.reasonCode = this._parseByte() : e.reasonCode = 0;
const t = this._parseProperties();
Object.getOwnPropertyNames(t).length && (e.properties = t);
}
return a("_parseDisconnect result: true"), !0;
}
_parseAuth() {
a("_parseAuth");
const e = this.packet;
if (5 !== this.settings.protocolVersion) return this._emitError(new Error("Not supported auth packet for this version MQTT"));
e.reasonCode = this._parseByte();
const t = this._parseProperties();
return Object.getOwnPropertyNames(t).length && (e.properties = t), a("_parseAuth: result: true"), !0;
}
_parseMessageId() {
const e = this.packet;
return e.messageId = this._parseNum(), null === e.messageId ? (this._emitError(new Error("Cannot parse messageId")), !1) : (a("_parseMessageId: packet.messageId %d", e.messageId), !0);
}
_parseString(e) {
const t = this._parseNum(),
r = t + this._pos;
if (-1 === t || r > this._list.length || r > this.packet.length) return null;
const n = this._list.toString("utf8", this._pos, r);
return this._pos += t, a("_parseString: result: %s", n), n;
}
_parseStringPair() {
return a("_parseStringPair"), {
name: this._parseString(),
value: this._parseString()
};
}
_parseBuffer() {
const e = this._parseNum(),
t = e + this._pos;
if (-1 === e || t > this._list.length || t > this.packet.length) return null;
const r = this._list.slice(this._pos, t);
return this._pos += e, a("_parseBuffer: result: %o", r), r;
}
_parseNum() {
if (this._list.length - this._pos < 2) return -1;
const e = this._list.readUInt16BE(this._pos);
return this._pos += 2, a("_parseNum: result: %s", e), e;
}
_parse4ByteNum() {
if (this._list.length - this._pos < 4) return -1;
const e = this._list.readUInt32BE(this._pos);
return this._pos += 4, a("_parse4ByteNum: result: %s", e), e;
}
_parseVarByteNum(e) {
a("_parseVarByteNum");
let t,
r = 0,
n = 1,
i = 0,
o = !1;
const l = this._pos ? this._pos : 0;
for (; r < 4 && l + r < this._list.length;) {
if (i += n * ((t = this._list.readUInt8(l + r++)) & s.VARBYTEINT_MASK), n *= 128, 0 == (t & s.VARBYTEINT_FIN_MASK)) {
o = !0;
break;
}
if (this._list.length <= r) break;
}
return !o && 4 === r && this._list.length >= r && this._emitError(new Error("Invalid variable byte integer")), l && (this._pos += r), a("_parseVarByteNum: result: %o", o = !!o && (e ? {
bytes: r,
value: i
} : i)), o;
}
_parseByte() {
let e;
return this._pos < this._list.length && (e = this._list.readUInt8(this._pos), this._pos++), a("_parseByte: result: %o", e), e;
}
_parseByType(e) {
switch (a("_parseByType: type: %s", e), e) {
case "byte":
return 0 !== this._parseByte();
case "int8":
return this._parseByte();
case "int16":
return this._parseNum();
case "int32":
return this._parse4ByteNum();
case "var":
return this._parseVarByteNum();
case "string":
return this._parseString();
case "pair":
return this._parseStringPair();
case "binary":
return this._parseBuffer();
}
}
_parseProperties() {
a("_parseProperties");
const e = this._parseVarByteNum(),
t = this._pos + e,
r = {};
for (; this._pos < t;) {
const e = this._parseByte();
if (!e) return this._emitError(new Error("Cannot parse property code type")), !1;
const t = s.propertiesCodes[e];
if (!t) return this._emitError(new Error("Unknown property")), !1;
if ("userProperties" !== t) r[t] ? Array.isArray(r[t]) ? r[t].push(this._parseByType(s.propertiesTypes[t])) : (r[t] = [r[t]], r[t].push(this._parseByType(s.propertiesTypes[t]))) : r[t] = this._parseByType(s.propertiesTypes[t]);else {
r[t] || (r[t] = Object.create(null));
const e = this._parseByType(s.propertiesTypes[t]);
if (r[t][e.name]) {
if (Array.isArray(r[t][e.name])) r[t][e.name].push(e.value);else {
const n = r[t][e.name];
r[t][e.name] = [n], r[t][e.name].push(e.value);
}
} else r[t][e.name] = e.value;
}
}
return r;
}
_newPacket() {
return a("_newPacket"), this.packet && (this._list.consume(this.packet.length), a("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d", this.packet.cmd, this.packet.payload, this.packet.length), this.emit("packet", this.packet)), a("_newPacket: new packet"), this.packet = new o(), this._pos = 0, !0;
}
_emitError(e) {
a("_emitError"), this.error = e, this.emit("error", e);
}
}
t.exports = l;
}, {
"./constants": 38,
"./packet": 42,
bl: 15,
debug: 18,
events: 22
}],
44: [function (e, t, r) {
(function (r) {
(function () {
const n = e("./constants"),
i = r.allocUnsafe(0),
o = r.from([0]),
s = e("./numbers"),
a = e("process-nextick-args").nextTick,
l = e("debug")("mqtt-packet:writeToStream"),
u = s.cache,
c = s.generateNumber,
h = s.generateCache,
f = s.genBufVariableByteInt,
p = s.generate4ByteBuffer;
let d = k,
g = !0;
function y(e, t, s) {
switch (l("generate called"), t.cork && (t.cork(), a(b, t)), g && (g = !1, h()), l("generate: packet.cmd: %s", e.cmd), e.cmd) {
case "connect":
return function (e, t, i) {
const o = e || {},
s = o.protocolId || "MQTT";
let a = o.protocolVersion || 4;
const l = o.will;
let u = o.clean;
const c = o.keepalive || 0,
h = o.clientId || "",
f = o.username,
p = o.password,
g = o.properties;
void 0 === u && (u = !0);
let y = 0;
if (!s || "string" != typeof s && !r.isBuffer(s)) return t.emit("error", new Error("Invalid protocolId")), !1;
y += s.length + 2;
if (3 !== a && 4 !== a && 5 !== a) return t.emit("error", new Error("Invalid protocol version")), !1;
y += 1;
if (("string" == typeof h || r.isBuffer(h)) && (h || a >= 4) && (h || u)) y += r.byteLength(h) + 2;else {
if (a < 4) return t.emit("error", new Error("clientId must be supplied before 3.1.1")), !1;
if (1 * u == 0) return t.emit("error", new Error("clientId must be given if cleanSession set to 0")), !1;
}
if ("number" != typeof c || c < 0 || c > 65535 || c % 1 != 0) return t.emit("error", new Error("Invalid keepalive")), !1;
y += 2;
if (y += 1, 5 === a) {
var b = C(t, g);
if (!b) return !1;
y += b.length;
}
if (l) {
if ("object" != typeof l) return t.emit("error", new Error("Invalid will")), !1;
if (!l.topic || "string" != typeof l.topic) return t.emit("error", new Error("Invalid will topic")), !1;
if (y += r.byteLength(l.topic) + 2, y += 2, l.payload) {
if (!(l.payload.length >= 0)) return t.emit("error", new Error("Invalid will payload")), !1;
"string" == typeof l.payload ? y += r.byteLength(l.payload) : y += l.payload.length;
}
var m = {};
if (5 === a) {
if (!(m = C(t, l.properties))) return !1;
y += m.length;
}
}
let _ = !1;
if (null != f) {
if (!P(f)) return t.emit("error", new Error("Invalid username")), !1;
_ = !0, y += r.byteLength(f) + 2;
}
if (null != p) {
if (!_) return t.emit("error", new Error("Username is required to use password")), !1;
if (!P(p)) return t.emit("error", new Error("Invalid password")), !1;
y += I(p) + 2;
}
t.write(n.CONNECT_HEADER), v(t, y), E(t, s), o.bridgeMode && (a += 128);
t.write(131 === a ? n.VERSION131 : 132 === a ? n.VERSION132 : 4 === a ? n.VERSION4 : 5 === a ? n.VERSION5 : n.VERSION3);
let k = 0;
k |= null != f ? n.USERNAME_MASK : 0, k |= null != p ? n.PASSWORD_MASK : 0, k |= l && l.retain ? n.WILL_RETAIN_MASK : 0, k |= l && l.qos ? l.qos << n.WILL_QOS_SHIFT : 0, k |= l ? n.WILL_FLAG_MASK : 0, k |= u ? n.CLEAN_SESSION_MASK : 0, t.write(r.from([k])), d(t, c), 5 === a && b.write();
E(t, h), l && (5 === a && m.write(), w(t, l.topic), E(t, l.payload));
null != f && E(t, f);
null != p && E(t, p);
return !0;
}(e, t);
case "connack":
return function (e, t, i) {
const s = i ? i.protocolVersion : 4,
a = e || {},
l = 5 === s ? a.reasonCode : a.returnCode,
u = a.properties;
let c = 2;
if ("number" != typeof l) return t.emit("error", new Error("Invalid return code")), !1;
let h = null;
if (5 === s) {
if (!(h = C(t, u))) return !1;
c += h.length;
}
t.write(n.CONNACK_HEADER), v(t, c), t.write(a.sessionPresent ? n.SESSIONPRESENT_HEADER : o), t.write(r.from([l])), null != h && h.write();
return !0;
}(e, t, s);
case "publish":
return function (e, t, o) {
l("publish: packet: %o", e);
const s = o ? o.protocolVersion : 4,
a = e || {},
u = a.qos || 0,
c = a.retain ? n.RETAIN_MASK : 0,
h = a.topic,
f = a.payload || i,
p = a.messageId,
g = a.properties;
let y = 0;
if ("string" == typeof h) y += r.byteLength(h) + 2;else {
if (!r.isBuffer(h)) return t.emit("error", new Error("Invalid topic")), !1;
y += h.length + 2;
}
r.isBuffer(f) ? y += f.length : y += r.byteLength(f);
if (u && "number" != typeof p) return t.emit("error", new Error("Invalid messageId")), !1;
u && (y += 2);
let b = null;
if (5 === s) {
if (!(b = C(t, g))) return !1;
y += b.length;
}
t.write(n.PUBLISH_HEADER[u][a.dup ? 1 : 0][c ? 1 : 0]), v(t, y), d(t, I(h)), t.write(h), u > 0 && d(t, p);
null != b && b.write();
return l("publish: payload: %o", f), t.write(f);
}(e, t, s);
case "puback":
case "pubrec":
case "pubrel":
case "pubcomp":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.cmd || "puback",
l = s.messageId,
u = s.dup && "pubrel" === a ? n.DUP_MASK : 0;
let c = 0;
const h = s.reasonCode,
f = s.properties;
let p = 5 === o ? 3 : 2;
"pubrel" === a && (c = 1);
if ("number" != typeof l) return t.emit("error", new Error("Invalid messageId")), !1;
let g = null;
if (5 === o && "object" == typeof f) {
if (!(g = T(t, f, i, p))) return !1;
p += g.length;
}
t.write(n.ACKS[a][c][u][0]), v(t, p), d(t, l), 5 === o && t.write(r.from([h]));
null !== g && g.write();
return !0;
}(e, t, s);
case "subscribe":
return function (e, t, i) {
l("subscribe: packet: ");
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.dup ? n.DUP_MASK : 0,
u = s.messageId,
c = s.subscriptions,
h = s.properties;
let f = 0;
if ("number" != typeof u) return t.emit("error", new Error("Invalid messageId")), !1;
f += 2;
let p = null;
if (5 === o) {
if (!(p = C(t, h))) return !1;
f += p.length;
}
if ("object" != typeof c || !c.length) return t.emit("error", new Error("Invalid subscriptions")), !1;
for (let e = 0; e < c.length; e += 1) {
const n = c[e].topic,
i = c[e].qos;
if ("string" != typeof n) return t.emit("error", new Error("Invalid subscriptions - invalid topic")), !1;
if ("number" != typeof i) return t.emit("error", new Error("Invalid subscriptions - invalid qos")), !1;
if (5 === o) {
const r = c[e].nl || !1;
if ("boolean" != typeof r) return t.emit("error", new Error("Invalid subscriptions - invalid No Local")), !1;
const n = c[e].rap || !1;
if ("boolean" != typeof n) return t.emit("error", new Error("Invalid subscriptions - invalid Retain as Published")), !1;
const i = c[e].rh || 0;
if ("number" != typeof i || i > 2) return t.emit("error", new Error("Invalid subscriptions - invalid Retain Handling")), !1;
}
f += r.byteLength(n) + 2 + 1;
}
l("subscribe: writing to stream: %o", n.SUBSCRIBE_HEADER), t.write(n.SUBSCRIBE_HEADER[1][a ? 1 : 0][0]), v(t, f), d(t, u), null !== p && p.write();
let g = !0;
for (const e of c) {
const i = e.topic,
s = e.qos,
a = +e.nl,
l = +e.rap,
u = e.rh;
let c;
w(t, i), c = n.SUBSCRIBE_OPTIONS_QOS[s], 5 === o && (c |= a ? n.SUBSCRIBE_OPTIONS_NL : 0, c |= l ? n.SUBSCRIBE_OPTIONS_RAP : 0, c |= u ? n.SUBSCRIBE_OPTIONS_RH[u] : 0), g = t.write(r.from([c]));
}
return g;
}(e, t, s);
case "suback":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.messageId,
l = s.granted,
u = s.properties;
let c = 0;
if ("number" != typeof a) return t.emit("error", new Error("Invalid messageId")), !1;
c += 2;
if ("object" != typeof l || !l.length) return t.emit("error", new Error("Invalid qos vector")), !1;
for (let e = 0; e < l.length; e += 1) {
if ("number" != typeof l[e]) return t.emit("error", new Error("Invalid qos vector")), !1;
c += 1;
}
let h = null;
if (5 === o) {
if (!(h = T(t, u, i, c))) return !1;
c += h.length;
}
t.write(n.SUBACK_HEADER), v(t, c), d(t, a), null !== h && h.write();
return t.write(r.from(l));
}(e, t, s);
case "unsubscribe":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.messageId,
l = s.dup ? n.DUP_MASK : 0,
u = s.unsubscriptions,
c = s.properties;
let h = 0;
if ("number" != typeof a) return t.emit("error", new Error("Invalid messageId")), !1;
h += 2;
if ("object" != typeof u || !u.length) return t.emit("error", new Error("Invalid unsubscriptions")), !1;
for (let e = 0; e < u.length; e += 1) {
if ("string" != typeof u[e]) return t.emit("error", new Error("Invalid unsubscriptions")), !1;
h += r.byteLength(u[e]) + 2;
}
let f = null;
if (5 === o) {
if (!(f = C(t, c))) return !1;
h += f.length;
}
t.write(n.UNSUBSCRIBE_HEADER[1][l ? 1 : 0][0]), v(t, h), d(t, a), null !== f && f.write();
let p = !0;
for (let e = 0; e < u.length; e++) p = w(t, u[e]);
return p;
}(e, t, s);
case "unsuback":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.messageId,
l = s.dup ? n.DUP_MASK : 0,
u = s.granted,
c = s.properties,
h = s.cmd;
let f = 2;
if ("number" != typeof a) return t.emit("error", new Error("Invalid messageId")), !1;
if (5 === o) {
if ("object" != typeof u || !u.length) return t.emit("error", new Error("Invalid qos vector")), !1;
for (let e = 0; e < u.length; e += 1) {
if ("number" != typeof u[e]) return t.emit("error", new Error("Invalid qos vector")), !1;
f += 1;
}
}
let p = null;
if (5 === o) {
if (!(p = T(t, c, i, f))) return !1;
f += p.length;
}
t.write(n.ACKS[h][0][l][0]), v(t, f), d(t, a), null !== p && p.write();
5 === o && t.write(r.from(u));
return !0;
}(e, t, s);
case "pingreq":
case "pingresp":
return function (e, t, r) {
return t.write(n.EMPTY[e.cmd]);
}(e, t);
case "disconnect":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.reasonCode,
l = s.properties;
let u = 5 === o ? 1 : 0,
c = null;
if (5 === o) {
if (!(c = T(t, l, i, u))) return !1;
u += c.length;
}
t.write(r.from([n.codes.disconnect << 4])), v(t, u), 5 === o && t.write(r.from([a]));
null !== c && c.write();
return !0;
}(e, t, s);
case "auth":
return function (e, t, i) {
const o = i ? i.protocolVersion : 4,
s = e || {},
a = s.reasonCode,
l = s.properties;
let u = 5 === o ? 1 : 0;
5 !== o && t.emit("error", new Error("Invalid mqtt version for auth packet"));
const c = T(t, l, i, u);
if (!c) return !1;
u += c.length, t.write(r.from([n.codes.auth << 4])), v(t, u), t.write(r.from([a])), null !== c && c.write();
return !0;
}(e, t, s);
default:
return t.emit("error", new Error("Unknown command")), !1;
}
}
function b(e) {
e.uncork();
}
Object.defineProperty(y, "cacheNumbers", {
get: () => d === k,
set(e) {
e ? (u && 0 !== Object.keys(u).length || (g = !0), d = k) : (g = !1, d = S);
}
});
const m = {};
function v(e, t) {
if (t > n.VARBYTEINT_MAX) return e.emit("error", new Error(`Invalid variable byte integer: ${t}`)), !1;
let r = m[t];
return r || (r = f(t), t < 16384 && (m[t] = r)), l("writeVarByteInt: writing to stream: %o", r), e.write(r);
}
function w(e, t) {
const n = r.byteLength(t);
return d(e, n), l("writeString: %s", t), e.write(t, "utf8");
}
function _(e, t, r) {
w(e, t), w(e, r);
}
function k(e, t) {
return l("writeNumberCached: number: %d", t), l("writeNumberCached: %o", u[t]), e.write(u[t]);
}
function S(e, t) {
const r = c(t);
return l("writeNumberGenerated: %o", r), e.write(r);
}
function E(e, t) {
"string" == typeof t ? w(e, t) : t ? (d(e, t.length), e.write(t)) : d(e, 0);
}
function C(e, t) {
if ("object" != typeof t || null != t.length) return {
length: 1,
write() {
A(e, {}, 0);
}
};
let i = 0;
function o(t, i) {
let o = 0;
switch (n.propertiesTypes[t]) {
case "byte":
if ("boolean" != typeof i) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 2;
break;
case "int8":
if ("number" != typeof i || i < 0 || i > 255) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 2;
break;
case "binary":
if (i && null === i) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 1 + r.byteLength(i) + 2;
break;
case "int16":
if ("number" != typeof i || i < 0 || i > 65535) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 3;
break;
case "int32":
if ("number" != typeof i || i < 0 || i > 4294967295) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 5;
break;
case "var":
if ("number" != typeof i || i < 0 || i > 268435455) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 1 + r.byteLength(f(i));
break;
case "string":
if ("string" != typeof i) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += 3 + r.byteLength(i.toString());
break;
case "pair":
if ("object" != typeof i) return e.emit("error", new Error(`Invalid ${t}: ${i}`)), !1;
o += Object.getOwnPropertyNames(i).reduce((e, t) => {
const n = i[t];
return Array.isArray(n) ? e += n.reduce((e, n) => e += 3 + r.byteLength(t.toString()) + 2 + r.byteLength(n.toString()), 0) : e += 3 + r.byteLength(t.toString()) + 2 + r.byteLength(i[t].toString()), e;
}, 0);
break;
default:
return e.emit("error", new Error(`Invalid property ${t}: ${i}`)), !1;
}
return o;
}
if (t) for (const e in t) {
let r = 0,
n = 0;
const s = t[e];
if (Array.isArray(s)) for (let t = 0; t < s.length; t++) {
if (!(n = o(e, s[t]))) return !1;
r += n;
} else {
if (!(n = o(e, s))) return !1;
r = n;
}
if (!r) return !1;
i += r;
}
return {
length: r.byteLength(f(i)) + i,
write() {
A(e, t, i);
}
};
}
function T(e, t, r, n) {
const i = ["reasonString", "userProperties"],
o = r && r.properties && r.properties.maximumPacketSize ? r.properties.maximumPacketSize : 0;
let s = C(e, t);
if (o) for (; n + s.length > o;) {
const r = i.shift();
if (!r || !t[r]) return !1;
delete t[r], s = C(e, t);
}
return s;
}
function x(e, t, i) {
switch (n.propertiesTypes[t]) {
case "byte":
e.write(r.from([n.properties[t]])), e.write(r.from([+i]));
break;
case "int8":
e.write(r.from([n.properties[t]])), e.write(r.from([i]));
break;
case "binary":
e.write(r.from([n.properties[t]])), E(e, i);
break;
case "int16":
e.write(r.from([n.properties[t]])), d(e, i);
break;
case "int32":
e.write(r.from([n.properties[t]])), function (e, t) {
const r = p(t);
l("write4ByteNumber: %o", r), e.write(r);
}(e, i);
break;
case "var":
e.write(r.from([n.properties[t]])), v(e, i);
break;
case "string":
e.write(r.from([n.properties[t]])), w(e, i);
break;
case "pair":
Object.getOwnPropertyNames(i).forEach(o => {
const s = i[o];
Array.isArray(s) ? s.forEach(i => {
e.write(r.from([n.properties[t]])), _(e, o.toString(), i.toString());
}) : (e.write(r.from([n.properties[t]])), _(e, o.toString(), s.toString()));
});
break;
default:
return e.emit("error", new Error(`Invalid property ${t} value: ${i}`)), !1;
}
}
function A(e, t, r) {
v(e, r);
for (const r in t) if (Object.prototype.hasOwnProperty.call(t, r) && null !== t[r]) {
const n = t[r];
if (Array.isArray(n)) for (let t = 0; t < n.length; t++) x(e, r, n[t]);else x(e, r, n);
}
}
function I(e) {
return e ? e instanceof r ? e.length : r.byteLength(e) : 0;
}
function P(e) {
return "string" == typeof e || e instanceof r;
}
t.exports = y;
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
"./constants": 38,
"./numbers": 41,
buffer: 17,
debug: 18,
"process-nextick-args": 49
}],
45: [function (e, t, r) {
var n = 1e3,
i = 60 * n,
o = 60 * i,
s = 24 * o,
a = 7 * s,
l = 365.25 * s;
function u(e, t, r, n) {
var i = t >= 1.5 * r;
return Math.round(e / r) + " " + n + (i ? "s" : "");
}
t.exports = function (e, t) {
t = t || {};
var r = typeof e;
if ("string" === r && e.length > 0) return function (e) {
if ((e = String(e)).length > 100) return;
var t = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);
if (!t) return;
var r = parseFloat(t[1]);
switch ((t[2] || "ms").toLowerCase()) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return r * l;
case "weeks":
case "week":
case "w":
return r * a;
case "days":
case "day":
case "d":
return r * s;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return r * o;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return r * i;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return r * n;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return r;
default:
return;
}
}(e);
if ("number" === r && isFinite(e)) return t.long ? function (e) {
var t = Math.abs(e);
if (t >= s) return u(e, t, s, "day");
if (t >= o) return u(e, t, o, "hour");
if (t >= i) return u(e, t, i, "minute");
if (t >= n) return u(e, t, n, "second");
return e + " ms";
}(e) : function (e) {
var t = Math.abs(e);
if (t >= s) return Math.round(e / s) + "d";
if (t >= o) return Math.round(e / o) + "h";
if (t >= i) return Math.round(e / i) + "m";
if (t >= n) return Math.round(e / n) + "s";
return e + "ms";
}(e);
throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(e));
};
}, {}],
46: [function (e, t, r) {
const n = e("./lib/number-allocator.js");
t.exports.NumberAllocator = n;
}, {
"./lib/number-allocator.js": 47
}],
47: [function (e, t, r) {
const n = e("js-sdsl").Set,
i = e("debug")("number-allocator:trace"),
o = e("debug")("number-allocator:error");
function s(e, t) {
this.low = e, this.high = t;
}
function a(e, t) {
if (!(this instanceof a)) return new a(e, t);
this.min = e, this.max = t, this.ss = new n([], (e, t) => e.compare(t)), i("Create"), this.clear();
}
s.prototype.equals = function (e) {
return this.low === e.low && this.high === e.high;
}, s.prototype.compare = function (e) {
return this.low < e.low && this.high < e.low ? -1 : e.low < this.low && e.high < this.low ? 1 : 0;
}, a.prototype.firstVacant = function () {
return 0 === this.ss.size() ? null : this.ss.front().low;
}, a.prototype.alloc = function () {
if (0 === this.ss.size()) return i("alloc():empty"), null;
const e = this.ss.front(),
t = e.low;
return t + 1 <= e.high ? ++e.low : this.ss.eraseElementByPos(0), i("alloc():" + t), t;
}, a.prototype.use = function (e) {
const t = new s(e, e),
r = this.ss.lowerBound(t);
if (r) {
if (r.equals(t)) return this.ss.eraseElementByValue(r), i("use():" + e), !0;
if (r.low > e) return !1;
if (r.low === e) return ++r.low, i("use():" + e), !0;
if (r.high === e) return --r.high, i("use():" + e), !0;
const n = r.low;
return r.low = e + 1, this.ss.insert(new s(n, e - 1)), i("use():" + e), !0;
}
return i("use():failed"), !1;
}, a.prototype.free = function (e) {
if (e < this.min || e > this.max) return void o("free():" + e + " is out of range");
const t = new s(e, e),
r = this.ss.lowerBound(t);
if (r) {
if (r.low <= e && e <= r.high) return void o("free():" + e + " has already been vacant");
if (r === this.ss.front()) e + 1 === r.low ? --r.low : this.ss.insert(t);else {
const n = this.ss.reverseLowerBound(t);
n.high + 1 === e ? e + 1 === r.low ? (this.ss.eraseElementByValue(n), r.low = n.low) : n.high = e : e + 1 === r.low ? r.low = e : this.ss.insert(t);
}
} else {
if (r === this.ss.front()) return void this.ss.insert(t);
const n = this.ss.reverseLowerBound(t);
n.high + 1 === e ? n.high = e : this.ss.insert(t);
}
i("free():" + e);
}, a.prototype.clear = function () {
i("clear()"), this.ss.clear(), this.ss.insert(new s(this.min, this.max));
}, a.prototype.intervalCount = function () {
return this.ss.size();
}, a.prototype.dump = function () {
console.log("length:" + this.ss.size());
for (const e of this.ss) console.log(e);
}, t.exports = a;
}, {
debug: 18,
"js-sdsl": 36
}],
48: [function (e, t, r) {
var n = e("wrappy");
function i(e) {
var t = function () {
return t.called ? t.value : (t.called = !0, t.value = e.apply(this, arguments));
};
return t.called = !1, t;
}
function o(e) {
var t = function () {
if (t.called) throw new Error(t.onceError);
return t.called = !0, t.value = e.apply(this, arguments);
},
r = e.name || "Function wrapped with `once`";
return t.onceError = r + " shouldn't be called more than once", t.called = !1, t;
}
t.exports = n(i), t.exports.strict = n(o), i.proto = i(function () {
Object.defineProperty(Function.prototype, "once", {
value: function () {
return i(this);
},
configurable: !0
}), Object.defineProperty(Function.prototype, "onceStrict", {
value: function () {
return o(this);
},
configurable: !0
});
});
}, {
wrappy: 79
}],
49: [function (e, t, r) {
(function (e) {
(function () {
void 0 === e || !e.version || 0 === e.version.indexOf("v0.") || 0 === e.version.indexOf("v1.") && 0 !== e.version.indexOf("v1.8.") ? t.exports = {
nextTick: function (t, r, n, i) {
if ("function" != typeof t) throw new TypeError('"callback" argument must be a function');
var o,
s,
a = arguments.length;
switch (a) {
case 0:
case 1:
return e.nextTick(t);
case 2:
return e.nextTick(function () {
t.call(null, r);
});
case 3:
return e.nextTick(function () {
t.call(null, r, n);
});
case 4:
return e.nextTick(function () {
t.call(null, r, n, i);
});
default:
for (o = new Array(a - 1), s = 0; s < o.length;) o[s++] = arguments[s];
return e.nextTick(function () {
t.apply(null, o);
});
}
}
} : t.exports = e;
}).call(this);
}).call(this, e("_process"));
}, {
_process: 50
}],
50: [function (e, t, r) {
var n,
i,
o = t.exports = {};
function s() {
throw new Error("setTimeout has not been defined");
}
function a() {
throw new Error("clearTimeout has not been defined");
}
function l(e) {
if (n === setTimeout) return setTimeout(e, 0);
if ((n === s || !n) && setTimeout) return n = setTimeout, setTimeout(e, 0);
try {
return n(e, 0);
} catch (t) {
try {
return n.call(null, e, 0);
} catch (t) {
return n.call(this, e, 0);
}
}
}
!function () {
try {
n = "function" == typeof setTimeout ? setTimeout : s;
} catch (e) {
n = s;
}
try {
i = "function" == typeof clearTimeout ? clearTimeout : a;
} catch (e) {
i = a;
}
}();
var u,
c = [],
h = !1,
f = -1;
function p() {
h && u && (h = !1, u.length ? c = u.concat(c) : f = -1, c.length && d());
}
function d() {
if (!h) {
var e = l(p);
h = !0;
for (var t = c.length; t;) {
for (u = c, c = []; ++f < t;) u && u[f].run();
f = -1, t = c.length;
}
u = null, h = !1, function (e) {
if (i === clearTimeout) return clearTimeout(e);
if ((i === a || !i) && clearTimeout) return i = clearTimeout, clearTimeout(e);
try {
i(e);
} catch (t) {
try {
return i.call(null, e);
} catch (t) {
return i.call(this, e);
}
}
}(e);
}
}
function g(e, t) {
this.fun = e, this.array = t;
}
function y() {}
o.nextTick = function (e) {
var t = new Array(arguments.length - 1);
if (arguments.length > 1) for (var r = 1; r < arguments.length; r++) t[r - 1] = arguments[r];
c.push(new g(e, t)), 1 !== c.length || h || l(d);
}, g.prototype.run = function () {
this.fun.apply(null, this.array);
}, o.title = "browser", o.browser = !0, o.env = {}, o.argv = [], o.version = "", o.versions = {}, o.on = y, o.addListener = y, o.once = y, o.off = y, o.removeListener = y, o.removeAllListeners = y, o.emit = y, o.prependListener = y, o.prependOnceListener = y, o.listeners = function (e) {
return [];
}, o.binding = function (e) {
throw new Error("process.binding is not supported");
}, o.cwd = function () {
return "/";
}, o.chdir = function (e) {
throw new Error("process.chdir is not supported");
}, o.umask = function () {
return 0;
};
}, {}],
51: [function (e, t, r) {
(function (e) {
(function () {
!function (n) {
var i = "object" == typeof r && r && !r.nodeType && r,
o = "object" == typeof t && t && !t.nodeType && t,
s = "object" == typeof e && e;
s.global !== s && s.window !== s && s.self !== s || (n = s);
var a,
l,
u = 2147483647,
c = 36,
h = 1,
f = 26,
p = 38,
d = 700,
g = 72,
y = 128,
b = "-",
m = /^xn--/,
v = /[^\x20-\x7E]/,
w = /[\x2E\u3002\uFF0E\uFF61]/g,
_ = {
overflow: "Overflow: input needs wider integers to process",
"not-basic": "Illegal input >= 0x80 (not a basic code point)",
"invalid-input": "Invalid input"
},
k = c - h,
S = Math.floor,
E = String.fromCharCode;
function C(e) {
throw new RangeError(_[e]);
}
function T(e, t) {
for (var r = e.length, n = []; r--;) n[r] = t(e[r]);
return n;
}
function x(e, t) {
var r = e.split("@"),
n = "";
return r.length > 1 && (n = r[0] + "@", e = r[1]), n + T((e = e.replace(w, ".")).split("."), t).join(".");
}
function A(e) {
for (var t, r, n = [], i = 0, o = e.length; i < o;) (t = e.charCodeAt(i++)) >= 55296 && t <= 56319 && i < o ? 56320 == (64512 & (r = e.charCodeAt(i++))) ? n.push(((1023 & t) << 10) + (1023 & r) + 65536) : (n.push(t), i--) : n.push(t);
return n;
}
function I(e) {
return T(e, function (e) {
var t = "";
return e > 65535 && (t += E((e -= 65536) >>> 10 & 1023 | 55296), e = 56320 | 1023 & e), t += E(e);
}).join("");
}
function P(e, t) {
return e + 22 + 75 * (e < 26) - ((0 != t) << 5);
}
function O(e, t, r) {
var n = 0;
for (e = r ? S(e / d) : e >> 1, e += S(e / t); e > k * f >> 1; n += c) e = S(e / k);
return S(n + (k + 1) * e / (e + p));
}
function B(e) {
var t,
r,
n,
i,
o,
s,
a,
l,
p,
d,
m,
v = [],
w = e.length,
_ = 0,
k = y,
E = g;
for ((r = e.lastIndexOf(b)) < 0 && (r = 0), n = 0; n < r; ++n) e.charCodeAt(n) >= 128 && C("not-basic"), v.push(e.charCodeAt(n));
for (i = r > 0 ? r + 1 : 0; i < w;) {
for (o = _, s = 1, a = c; i >= w && C("invalid-input"), ((l = (m = e.charCodeAt(i++)) - 48 < 10 ? m - 22 : m - 65 < 26 ? m - 65 : m - 97 < 26 ? m - 97 : c) >= c || l > S((u - _) / s)) && C("overflow"), _ += l * s, !(l < (p = a <= E ? h : a >= E + f ? f : a - E)); a += c) s > S(u / (d = c - p)) && C("overflow"), s *= d;
E = O(_ - o, t = v.length + 1, 0 == o), S(_ / t) > u - k && C("overflow"), k += S(_ / t), _ %= t, v.splice(_++, 0, k);
}
return I(v);
}
function R(e) {
var t,
r,
n,
i,
o,
s,
a,
l,
p,
d,
m,
v,
w,
_,
k,
T = [];
for (v = (e = A(e)).length, t = y, r = 0, o = g, s = 0; s < v; ++s) (m = e[s]) < 128 && T.push(E(m));
for (n = i = T.length, i && T.push(b); n < v;) {
for (a = u, s = 0; s < v; ++s) (m = e[s]) >= t && m < a && (a = m);
for (a - t > S((u - r) / (w = n + 1)) && C("overflow"), r += (a - t) * w, t = a, s = 0; s < v; ++s) if ((m = e[s]) < t && ++r > u && C("overflow"), m == t) {
for (l = r, p = c; !(l < (d = p <= o ? h : p >= o + f ? f : p - o)); p += c) k = l - d, _ = c - d, T.push(E(P(d + k % _, 0))), l = S(k / _);
T.push(E(P(l, 0))), o = O(r, w, n == i), r = 0, ++n;
}
++r, ++t;
}
return T.join("");
}
if (a = {
version: "1.4.1",
ucs2: {
decode: A,
encode: I
},
decode: B,
encode: R,
toASCII: function (e) {
return x(e, function (e) {
return v.test(e) ? "xn--" + R(e) : e;
});
},
toUnicode: function (e) {
return x(e, function (e) {
return m.test(e) ? B(e.slice(4).toLowerCase()) : e;
});
}
}, i && o) {
if (t.exports == i) o.exports = a;else for (l in a) a.hasOwnProperty(l) && (i[l] = a[l]);
} else n.punycode = a;
}(this);
}).call(this);
}).call(this, "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}],
52: [function (e, t, r) {
function n(e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
}
t.exports = function (e, t, r, o) {
t = t || "&", r = r || "=";
var s = {};
if ("string" != typeof e || 0 === e.length) return s;
var a = /\+/g;
e = e.split(t);
var l = 1e3;
o && "number" == typeof o.maxKeys && (l = o.maxKeys);
var u = e.length;
l > 0 && u > l && (u = l);
for (var c = 0; c < u; ++c) {
var h,
f,
p,
d,
g = e[c].replace(a, "%20"),
y = g.indexOf(r);
y >= 0 ? (h = g.substr(0, y), f = g.substr(y + 1)) : (h = g, f = ""), p = decodeURIComponent(h), d = decodeURIComponent(f), n(s, p) ? i(s[p]) ? s[p].push(d) : s[p] = [s[p], d] : s[p] = d;
}
return s;
};
var i = Array.isArray || function (e) {
return "[object Array]" === Object.prototype.toString.call(e);
};
}, {}],
53: [function (e, t, r) {
var n = function (e) {
switch (typeof e) {
case "string":
return e;
case "boolean":
return e ? "true" : "false";
case "number":
return isFinite(e) ? e : "";
default:
return "";
}
};
t.exports = function (e, t, r, a) {
return t = t || "&", r = r || "=", null === e && (e = void 0), "object" == typeof e ? o(s(e), function (s) {
var a = encodeURIComponent(n(s)) + r;
return i(e[s]) ? o(e[s], function (e) {
return a + encodeURIComponent(n(e));
}).join(t) : a + encodeURIComponent(n(e[s]));
}).join(t) : a ? encodeURIComponent(n(a)) + r + encodeURIComponent(n(e)) : "";
};
var i = Array.isArray || function (e) {
return "[object Array]" === Object.prototype.toString.call(e);
};
function o(e, t) {
if (e.map) return e.map(t);
for (var r = [], n = 0; n < e.length; n++) r.push(t(e[n], n));
return r;
}
var s = Object.keys || function (e) {
var t = [];
for (var r in e) Object.prototype.hasOwnProperty.call(e, r) && t.push(r);
return t;
};
}, {}],
54: [function (e, t, r) {
r.decode = r.parse = e("./decode"), r.encode = r.stringify = e("./encode");
}, {
"./decode": 52,
"./encode": 53
}],
55: [function (e, t, r) {
var n = {};
function i(e, t, r) {
r || (r = Error);
var i = function (e) {
var r, n;
function i(r, n, i) {
return e.call(this, function (e, r, n) {
return "string" == typeof t ? t : t(e, r, n);
}(r, n, i)) || this;
}
return n = e, (r = i).prototype = Object.create(n.prototype), r.prototype.constructor = r, r.__proto__ = n, i;
}(r);
i.prototype.name = r.name, i.prototype.code = e, n[e] = i;
}
function o(e, t) {
if (Array.isArray(e)) {
var r = e.length;
return e = e.map(function (e) {
return String(e);
}), r > 2 ? "one of ".concat(t, " ").concat(e.slice(0, r - 1).join(", "), ", or ") + e[r - 1] : 2 === r ? "one of ".concat(t, " ").concat(e[0], " or ").concat(e[1]) : "of ".concat(t, " ").concat(e[0]);
}
return "of ".concat(t, " ").concat(String(e));
}
i("ERR_INVALID_OPT_VALUE", function (e, t) {
return 'The value "' + t + '" is invalid for option "' + e + '"';
}, TypeError), i("ERR_INVALID_ARG_TYPE", function (e, t, r) {
var n, i, a;
if ("string" == typeof t && (i = "not ", t.substr(0 , i.length) === i) ? (n = "must not be", t = t.replace(/^not /, "")) : n = "must be", function (e, t, r) {
return (void 0 === r || r > e.length) && (r = e.length), e.substring(r - t.length, r) === t;
}(e, " argument")) a = "The ".concat(e, " ").concat(n, " ").concat(o(t, "type"));else {
var l = function (e, t, r) {
return "number" != typeof r && (r = 0), !(r + t.length > e.length) && -1 !== e.indexOf(t, r);
}(e, ".") ? "property" : "argument";
a = 'The "'.concat(e, '" ').concat(l, " ").concat(n, " ").concat(o(t, "type"));
}
return a += ". Received type ".concat(typeof r);
}, TypeError), i("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"), i("ERR_METHOD_NOT_IMPLEMENTED", function (e) {
return "The " + e + " method is not implemented";
}), i("ERR_STREAM_PREMATURE_CLOSE", "Premature close"), i("ERR_STREAM_DESTROYED", function (e) {
return "Cannot call " + e + " after a stream was destroyed";
}), i("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"), i("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"), i("ERR_STREAM_WRITE_AFTER_END", "write after end"), i("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError), i("ERR_UNKNOWN_ENCODING", function (e) {
return "Unknown encoding: " + e;
}, TypeError), i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"), t.exports.codes = n;
}, {}],
56: [function (e, t, r) {
(function (r) {
(function () {
var n = Object.keys || function (e) {
var t = [];
for (var r in e) t.push(r);
return t;
};
t.exports = u;
var i = e("./_stream_readable"),
o = e("./_stream_writable");
e("inherits")(u, i);
for (var s = n(o.prototype), a = 0; a < s.length; a++) {
var l = s[a];
u.prototype[l] || (u.prototype[l] = o.prototype[l]);
}
function u(e) {
if (!(this instanceof u)) return new u(e);
i.call(this, e), o.call(this, e), this.allowHalfOpen = !0, e && (!1 === e.readable && (this.readable = !1), !1 === e.writable && (this.writable = !1), !1 === e.allowHalfOpen && (this.allowHalfOpen = !1, this.once("end", c)));
}
function c() {
this._writableState.ended || r.nextTick(h, this);
}
function h(e) {
e.end();
}
Object.defineProperty(u.prototype, "writableHighWaterMark", {
enumerable: !1,
get: function () {
return this._writableState.highWaterMark;
}
}), Object.defineProperty(u.prototype, "writableBuffer", {
enumerable: !1,
get: function () {
return this._writableState && this._writableState.getBuffer();
}
}), Object.defineProperty(u.prototype, "writableLength", {
enumerable: !1,
get: function () {
return this._writableState.length;
}
}), Object.defineProperty(u.prototype, "destroyed", {
enumerable: !1,
get: function () {
return void 0 !== this._readableState && void 0 !== this._writableState && this._readableState.destroyed && this._writableState.destroyed;
},
set: function (e) {
void 0 !== this._readableState && void 0 !== this._writableState && (this._readableState.destroyed = e, this._writableState.destroyed = e);
}
});
}).call(this);
}).call(this, e("_process"));
}, {
"./_stream_readable": 58,
"./_stream_writable": 60,
_process: 50,
inherits: 24
}],
57: [function (e, t, r) {
t.exports = i;
var n = e("./_stream_transform");
function i(e) {
if (!(this instanceof i)) return new i(e);
n.call(this, e);
}
e("inherits")(i, n), i.prototype._transform = function (e, t, r) {
r(null, e);
};
}, {
"./_stream_transform": 59,
inherits: 24
}],
58: [function (e, t, r) {
(function (r, n) {
(function () {
var i;
t.exports = C, C.ReadableState = E;
e("events").EventEmitter;
var o = function (e, t) {
return e.listeners(t).length;
},
s = e("./internal/streams/stream"),
a = e("buffer").Buffer,
l = n.Uint8Array || function () {};
var u,
c = e("util");
u = c && c.debuglog ? c.debuglog("stream") : function () {};
var h,
f,
p,
d = e("./internal/streams/buffer_list"),
g = e("./internal/streams/destroy"),
y = e("./internal/streams/state").getHighWaterMark,
b = e("../errors").codes,
m = b.ERR_INVALID_ARG_TYPE,
v = b.ERR_STREAM_PUSH_AFTER_EOF,
w = b.ERR_METHOD_NOT_IMPLEMENTED,
_ = b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
e("inherits")(C, s);
var k = g.errorOrDestroy,
S = ["error", "close", "destroy", "pause", "resume"];
function E(t, r, n) {
i = i || e("./_stream_duplex"), t = t || {}, "boolean" != typeof n && (n = r instanceof i), this.objectMode = !!t.objectMode, n && (this.objectMode = this.objectMode || !!t.readableObjectMode), this.highWaterMark = y(this, t, "readableHighWaterMark", n), this.buffer = new d(), this.length = 0, this.pipes = null, this.pipesCount = 0, this.flowing = null, this.ended = !1, this.endEmitted = !1, this.reading = !1, this.sync = !0, this.needReadable = !1, this.emittedReadable = !1, this.readableListening = !1, this.resumeScheduled = !1, this.paused = !0, this.emitClose = !1 !== t.emitClose, this.autoDestroy = !!t.autoDestroy, this.destroyed = !1, this.defaultEncoding = t.defaultEncoding || "utf8", this.awaitDrain = 0, this.readingMore = !1, this.decoder = null, this.encoding = null, t.encoding && (h || (h = e("string_decoder/").StringDecoder), this.decoder = new h(t.encoding), this.encoding = t.encoding);
}
function C(t) {
if (i = i || e("./_stream_duplex"), !(this instanceof C)) return new C(t);
var r = this instanceof i;
this._readableState = new E(t, this, r), this.readable = !0, t && ("function" == typeof t.read && (this._read = t.read), "function" == typeof t.destroy && (this._destroy = t.destroy)), s.call(this);
}
function T(e, t, r, n, i) {
u("readableAddChunk", t);
var o,
s = e._readableState;
if (null === t) s.reading = !1, function (e, t) {
if (u("onEofChunk"), t.ended) return;
if (t.decoder) {
var r = t.decoder.end();
r && r.length && (t.buffer.push(r), t.length += t.objectMode ? 1 : r.length);
}
t.ended = !0, t.sync ? P(e) : (t.needReadable = !1, t.emittedReadable || (t.emittedReadable = !0, O(e)));
}(e, s);else if (i || (o = function (e, t) {
var r;
n = t, a.isBuffer(n) || n instanceof l || "string" == typeof t || void 0 === t || e.objectMode || (r = new m("chunk", ["string", "Buffer", "Uint8Array"], t));
var n;
return r;
}(s, t)), o) k(e, o);else if (s.objectMode || t && t.length > 0) {
if ("string" == typeof t || s.objectMode || Object.getPrototypeOf(t) === a.prototype || (t = function (e) {
return a.from(e);
}(t)), n) s.endEmitted ? k(e, new _()) : x(e, s, t, !0);else if (s.ended) k(e, new v());else {
if (s.destroyed) return !1;
s.reading = !1, s.decoder && !r ? (t = s.decoder.write(t), s.objectMode || 0 !== t.length ? x(e, s, t, !1) : B(e, s)) : x(e, s, t, !1);
}
} else n || (s.reading = !1, B(e, s));
return !s.ended && (s.length < s.highWaterMark || 0 === s.length);
}
function x(e, t, r, n) {
t.flowing && 0 === t.length && !t.sync ? (t.awaitDrain = 0, e.emit("data", r)) : (t.length += t.objectMode ? 1 : r.length, n ? t.buffer.unshift(r) : t.buffer.push(r), t.needReadable && P(e)), B(e, t);
}
Object.defineProperty(C.prototype, "destroyed", {
enumerable: !1,
get: function () {
return void 0 !== this._readableState && this._readableState.destroyed;
},
set: function (e) {
this._readableState && (this._readableState.destroyed = e);
}
}), C.prototype.destroy = g.destroy, C.prototype._undestroy = g.undestroy, C.prototype._destroy = function (e, t) {
t(e);
}, C.prototype.push = function (e, t) {
var r,
n = this._readableState;
return n.objectMode ? r = !0 : "string" == typeof e && ((t = t || n.defaultEncoding) !== n.encoding && (e = a.from(e, t), t = ""), r = !0), T(this, e, t, !1, r);
}, C.prototype.unshift = function (e) {
return T(this, e, null, !0, !1);
}, C.prototype.isPaused = function () {
return !1 === this._readableState.flowing;
}, C.prototype.setEncoding = function (t) {
h || (h = e("string_decoder/").StringDecoder);
var r = new h(t);
this._readableState.decoder = r, this._readableState.encoding = this._readableState.decoder.encoding;
for (var n = this._readableState.buffer.head, i = ""; null !== n;) i += r.write(n.data), n = n.next;
return this._readableState.buffer.clear(), "" !== i && this._readableState.buffer.push(i), this._readableState.length = i.length, this;
};
var A = 1073741824;
function I(e, t) {
return e <= 0 || 0 === t.length && t.ended ? 0 : t.objectMode ? 1 : e != e ? t.flowing && t.length ? t.buffer.head.data.length : t.length : (e > t.highWaterMark && (t.highWaterMark = function (e) {
return e >= A ? e = A : (e--, e |= e >>> 1, e |= e >>> 2, e |= e >>> 4, e |= e >>> 8, e |= e >>> 16, e++), e;
}(e)), e <= t.length ? e : t.ended ? t.length : (t.needReadable = !0, 0));
}
function P(e) {
var t = e._readableState;
u("emitReadable", t.needReadable, t.emittedReadable), t.needReadable = !1, t.emittedReadable || (u("emitReadable", t.flowing), t.emittedReadable = !0, r.nextTick(O, e));
}
function O(e) {
var t = e._readableState;
u("emitReadable_", t.destroyed, t.length, t.ended), t.destroyed || !t.length && !t.ended || (e.emit("readable"), t.emittedReadable = !1), t.needReadable = !t.flowing && !t.ended && t.length <= t.highWaterMark, j(e);
}
function B(e, t) {
t.readingMore || (t.readingMore = !0, r.nextTick(R, e, t));
}
function R(e, t) {
for (; !t.reading && !t.ended && (t.length < t.highWaterMark || t.flowing && 0 === t.length);) {
var r = t.length;
if (u("maybeReadMore read 0"), e.read(0), r === t.length) break;
}
t.readingMore = !1;
}
function M(e) {
var t = e._readableState;
t.readableListening = e.listenerCount("readable") > 0, t.resumeScheduled && !t.paused ? t.flowing = !0 : e.listenerCount("data") > 0 && e.resume();
}
function N(e) {
u("readable nexttick read 0"), e.read(0);
}
function L(e, t) {
u("resume", t.reading), t.reading || e.read(0), t.resumeScheduled = !1, e.emit("resume"), j(e), t.flowing && !t.reading && e.read(0);
}
function j(e) {
var t = e._readableState;
for (u("flow", t.flowing); t.flowing && null !== e.read(););
}
function U(e, t) {
return 0 === t.length ? null : (t.objectMode ? r = t.buffer.shift() : !e || e >= t.length ? (r = t.decoder ? t.buffer.join("") : 1 === t.buffer.length ? t.buffer.first() : t.buffer.concat(t.length), t.buffer.clear()) : r = t.buffer.consume(e, t.decoder), r);
var r;
}
function q(e) {
var t = e._readableState;
u("endReadable", t.endEmitted), t.endEmitted || (t.ended = !0, r.nextTick(D, t, e));
}
function D(e, t) {
if (u("endReadableNT", e.endEmitted, e.length), !e.endEmitted && 0 === e.length && (e.endEmitted = !0, t.readable = !1, t.emit("end"), e.autoDestroy)) {
var r = t._writableState;
(!r || r.autoDestroy && r.finished) && t.destroy();
}
}
function z(e, t) {
for (var r = 0, n = e.length; r < n; r++) if (e[r] === t) return r;
return -1;
}
C.prototype.read = function (e) {
u("read", e), e = parseInt(e, 10);
var t = this._readableState,
r = e;
if (0 !== e && (t.emittedReadable = !1), 0 === e && t.needReadable && ((0 !== t.highWaterMark ? t.length >= t.highWaterMark : t.length > 0) || t.ended)) return u("read: emitReadable", t.length, t.ended), 0 === t.length && t.ended ? q(this) : P(this), null;
if (0 === (e = I(e, t)) && t.ended) return 0 === t.length && q(this), null;
var n,
i = t.needReadable;
return u("need readable", i), (0 === t.length || t.length - e < t.highWaterMark) && u("length less than watermark", i = !0), t.ended || t.reading ? u("reading or ended", i = !1) : i && (u("do read"), t.reading = !0, t.sync = !0, 0 === t.length && (t.needReadable = !0), this._read(t.highWaterMark), t.sync = !1, t.reading || (e = I(r, t))), null === (n = e > 0 ? U(e, t) : null) ? (t.needReadable = t.length <= t.highWaterMark, e = 0) : (t.length -= e, t.awaitDrain = 0), 0 === t.length && (t.ended || (t.needReadable = !0), r !== e && t.ended && q(this)), null !== n && this.emit("data", n), n;
}, C.prototype._read = function (e) {
k(this, new w("_read()"));
}, C.prototype.pipe = function (e, t) {
var n = this,
i = this._readableState;
switch (i.pipesCount) {
case 0:
i.pipes = e;
break;
case 1:
i.pipes = [i.pipes, e];
break;
default:
i.pipes.push(e);
}
i.pipesCount += 1, u("pipe count=%d opts=%j", i.pipesCount, t);
var s = (!t || !1 !== t.end) && e !== r.stdout && e !== r.stderr ? l : y;
function a(t, r) {
u("onunpipe"), t === n && r && !1 === r.hasUnpiped && (r.hasUnpiped = !0, u("cleanup"), e.removeListener("close", d), e.removeListener("finish", g), e.removeListener("drain", c), e.removeListener("error", p), e.removeListener("unpipe", a), n.removeListener("end", l), n.removeListener("end", y), n.removeListener("data", f), h = !0, !i.awaitDrain || e._writableState && !e._writableState.needDrain || c());
}
function l() {
u("onend"), e.end();
}
i.endEmitted ? r.nextTick(s) : n.once("end", s), e.on("unpipe", a);
var c = function (e) {
return function () {
var t = e._readableState;
u("pipeOnDrain", t.awaitDrain), t.awaitDrain && t.awaitDrain--, 0 === t.awaitDrain && o(e, "data") && (t.flowing = !0, j(e));
};
}(n);
e.on("drain", c);
var h = !1;
function f(t) {
u("ondata");
var r = e.write(t);
u("dest.write", r), !1 === r && ((1 === i.pipesCount && i.pipes === e || i.pipesCount > 1 && -1 !== z(i.pipes, e)) && !h && (u("false write response, pause", i.awaitDrain), i.awaitDrain++), n.pause());
}
function p(t) {
u("onerror", t), y(), e.removeListener("error", p), 0 === o(e, "error") && k(e, t);
}
function d() {
e.removeListener("finish", g), y();
}
function g() {
u("onfinish"), e.removeListener("close", d), y();
}
function y() {
u("unpipe"), n.unpipe(e);
}
return n.on("data", f), function (e, t, r) {
if ("function" == typeof e.prependListener) return e.prependListener(t, r);
e._events && e._events[t] ? Array.isArray(e._events[t]) ? e._events[t].unshift(r) : e._events[t] = [r, e._events[t]] : e.on(t, r);
}(e, "error", p), e.once("close", d), e.once("finish", g), e.emit("pipe", n), i.flowing || (u("pipe resume"), n.resume()), e;
}, C.prototype.unpipe = function (e) {
var t = this._readableState,
r = {
hasUnpiped: !1
};
if (0 === t.pipesCount) return this;
if (1 === t.pipesCount) return e && e !== t.pipes ? this : (e || (e = t.pipes), t.pipes = null, t.pipesCount = 0, t.flowing = !1, e && e.emit("unpipe", this, r), this);
if (!e) {
var n = t.pipes,
i = t.pipesCount;
t.pipes = null, t.pipesCount = 0, t.flowing = !1;
for (var o = 0; o < i; o++) n[o].emit("unpipe", this, {
hasUnpiped: !1
});
return this;
}
var s = z(t.pipes, e);
return -1 === s ? this : (t.pipes.splice(s, 1), t.pipesCount -= 1, 1 === t.pipesCount && (t.pipes = t.pipes[0]), e.emit("unpipe", this, r), this);
}, C.prototype.on = function (e, t) {
var n = s.prototype.on.call(this, e, t),
i = this._readableState;
return "data" === e ? (i.readableListening = this.listenerCount("readable") > 0, !1 !== i.flowing && this.resume()) : "readable" === e && (i.endEmitted || i.readableListening || (i.readableListening = i.needReadable = !0, i.flowing = !1, i.emittedReadable = !1, u("on readable", i.length, i.reading), i.length ? P(this) : i.reading || r.nextTick(N, this))), n;
}, C.prototype.addListener = C.prototype.on, C.prototype.removeListener = function (e, t) {
var n = s.prototype.removeListener.call(this, e, t);
return "readable" === e && r.nextTick(M, this), n;
}, C.prototype.removeAllListeners = function (e) {
var t = s.prototype.removeAllListeners.apply(this, arguments);
return "readable" !== e && void 0 !== e || r.nextTick(M, this), t;
}, C.prototype.resume = function () {
var e = this._readableState;
return e.flowing || (u("resume"), e.flowing = !e.readableListening, function (e, t) {
t.resumeScheduled || (t.resumeScheduled = !0, r.nextTick(L, e, t));
}(this, e)), e.paused = !1, this;
}, C.prototype.pause = function () {
return u("call pause flowing=%j", this._readableState.flowing), !1 !== this._readableState.flowing && (u("pause"), this._readableState.flowing = !1, this.emit("pause")), this._readableState.paused = !0, this;
}, C.prototype.wrap = function (e) {
var t = this,
r = this._readableState,
n = !1;
for (var i in e.on("end", function () {
if (u("wrapped end"), r.decoder && !r.ended) {
var e = r.decoder.end();
e && e.length && t.push(e);
}
t.push(null);
}), e.on("data", function (i) {
(u("wrapped data"), r.decoder && (i = r.decoder.write(i)), !r.objectMode || null !== i && void 0 !== i) && (r.objectMode || i && i.length) && (t.push(i) || (n = !0, e.pause()));
}), e) void 0 === this[i] && "function" == typeof e[i] && (this[i] = function (t) {
return function () {
return e[t].apply(e, arguments);
};
}(i));
for (var o = 0; o < S.length; o++) e.on(S[o], this.emit.bind(this, S[o]));
return this._read = function (t) {
u("wrapped _read", t), n && (n = !1, e.resume());
}, this;
}, "function" == typeof Symbol && (C.prototype[Symbol.asyncIterator] = function () {
return void 0 === f && (f = e("./internal/streams/async_iterator")), f(this);
}), Object.defineProperty(C.prototype, "readableHighWaterMark", {
enumerable: !1,
get: function () {
return this._readableState.highWaterMark;
}
}), Object.defineProperty(C.prototype, "readableBuffer", {
enumerable: !1,
get: function () {
return this._readableState && this._readableState.buffer;
}
}), Object.defineProperty(C.prototype, "readableFlowing", {
enumerable: !1,
get: function () {
return this._readableState.flowing;
},
set: function (e) {
this._readableState && (this._readableState.flowing = e);
}
}), C._fromList = U, Object.defineProperty(C.prototype, "readableLength", {
enumerable: !1,
get: function () {
return this._readableState.length;
}
}), "function" == typeof Symbol && (C.from = function (t, r) {
return void 0 === p && (p = e("./internal/streams/from")), p(C, t, r);
});
}).call(this);
}).call(this, e("_process"), "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {
"../errors": 55,
"./_stream_duplex": 56,
"./internal/streams/async_iterator": 61,
"./internal/streams/buffer_list": 62,
"./internal/streams/destroy": 63,
"./internal/streams/from": 65,
"./internal/streams/state": 67,
"./internal/streams/stream": 68,
_process: 50,
buffer: 17,
events: 22,
inherits: 24,
"string_decoder/": 75,
util: 16
}],
59: [function (e, t, r) {
t.exports = u;
var n = e("../errors").codes,
i = n.ERR_METHOD_NOT_IMPLEMENTED,
o = n.ERR_MULTIPLE_CALLBACK,
s = n.ERR_TRANSFORM_ALREADY_TRANSFORMING,
a = n.ERR_TRANSFORM_WITH_LENGTH_0,
l = e("./_stream_duplex");
function u(e) {
if (!(this instanceof u)) return new u(e);
l.call(this, e), this._transformState = {
afterTransform: function (e, t) {
var r = this._transformState;
r.transforming = !1;
var n = r.writecb;
if (null === n) return this.emit("error", new o());
r.writechunk = null, r.writecb = null, null != t && this.push(t), n(e);
var i = this._readableState;
i.reading = !1, (i.needReadable || i.length < i.highWaterMark) && this._read(i.highWaterMark);
}.bind(this),
needTransform: !1,
transforming: !1,
writecb: null,
writechunk: null,
writeencoding: null
}, this._readableState.needReadable = !0, this._readableState.sync = !1, e && ("function" == typeof e.transform && (this._transform = e.transform), "function" == typeof e.flush && (this._flush = e.flush)), this.on("prefinish", c);
}
function c() {
var e = this;
"function" != typeof this._flush || this._readableState.destroyed ? h(this, null, null) : this._flush(function (t, r) {
h(e, t, r);
});
}
function h(e, t, r) {
if (t) return e.emit("error", t);
if (null != r && e.push(r), e._writableState.length) throw new a();
if (e._transformState.transforming) throw new s();
return e.push(null);
}
e("inherits")(u, l), u.prototype.push = function (e, t) {
return this._transformState.needTransform = !1, l.prototype.push.call(this, e, t);
}, u.prototype._transform = function (e, t, r) {
r(new i("_transform()"));
}, u.prototype._write = function (e, t, r) {
var n = this._transformState;
if (n.writecb = r, n.writechunk = e, n.writeencoding = t, !n.transforming) {
var i = this._readableState;
(n.needTransform || i.needReadable || i.length < i.highWaterMark) && this._read(i.highWaterMark);
}
}, u.prototype._read = function (e) {
var t = this._transformState;
null === t.writechunk || t.transforming ? t.needTransform = !0 : (t.transforming = !0, this._transform(t.writechunk, t.writeencoding, t.afterTransform));
}, u.prototype._destroy = function (e, t) {
l.prototype._destroy.call(this, e, function (e) {
t(e);
});
};
}, {
"../errors": 55,
"./_stream_duplex": 56,
inherits: 24
}],
60: [function (e, t, r) {
(function (r, n) {
(function () {
function i(e) {
var t = this;
this.next = null, this.entry = null, this.finish = function () {
!function (e, t, r) {
var n = e.entry;
e.entry = null;
for (; n;) {
var i = n.callback;
t.pendingcb--, i(r), n = n.next;
}
t.corkedRequestsFree.next = e;
}(t, e);
};
}
var o;
t.exports = C, C.WritableState = E;
var s = {
deprecate: e("util-deprecate")
},
a = e("./internal/streams/stream"),
l = e("buffer").Buffer,
u = n.Uint8Array || function () {};
var c,
h = e("./internal/streams/destroy"),
f = e("./internal/streams/state").getHighWaterMark,
p = e("../errors").codes,
d = p.ERR_INVALID_ARG_TYPE,
g = p.ERR_METHOD_NOT_IMPLEMENTED,
y = p.ERR_MULTIPLE_CALLBACK,
b = p.ERR_STREAM_CANNOT_PIPE,
m = p.ERR_STREAM_DESTROYED,
v = p.ERR_STREAM_NULL_VALUES,
w = p.ERR_STREAM_WRITE_AFTER_END,
_ = p.ERR_UNKNOWN_ENCODING,
k = h.errorOrDestroy;
function S() {}
function E(t, n, s) {
o = o || e("./_stream_duplex"), t = t || {}, "boolean" != typeof s && (s = n instanceof o), this.objectMode = !!t.objectMode, s && (this.objectMode = this.objectMode || !!t.writableObjectMode), this.highWaterMark = f(this, t, "writableHighWaterMark", s), this.finalCalled = !1, this.needDrain = !1, this.ending = !1, this.ended = !1, this.finished = !1, this.destroyed = !1;
var a = !1 === t.decodeStrings;
this.decodeStrings = !a, this.defaultEncoding = t.defaultEncoding || "utf8", this.length = 0, this.writing = !1, this.corked = 0, this.sync = !0, this.bufferProcessing = !1, this.onwrite = function (e) {
!function (e, t) {
var n = e._writableState,
i = n.sync,
o = n.writecb;
if ("function" != typeof o) throw new y();
if (function (e) {
e.writing = !1, e.writecb = null, e.length -= e.writelen, e.writelen = 0;
}(n), t) !function (e, t, n, i, o) {
--t.pendingcb, n ? (r.nextTick(o, i), r.nextTick(O, e, t), e._writableState.errorEmitted = !0, k(e, i)) : (o(i), e._writableState.errorEmitted = !0, k(e, i), O(e, t));
}(e, n, i, t, o);else {
var s = I(n) || e.destroyed;
s || n.corked || n.bufferProcessing || !n.bufferedRequest || A(e, n), i ? r.nextTick(x, e, n, s, o) : x(e, n, s, o);
}
}(n, e);
}, this.writecb = null, this.writelen = 0, this.bufferedRequest = null, this.lastBufferedRequest = null, this.pendingcb = 0, this.prefinished = !1, this.errorEmitted = !1, this.emitClose = !1 !== t.emitClose, this.autoDestroy = !!t.autoDestroy, this.bufferedRequestCount = 0, this.corkedRequestsFree = new i(this);
}
function C(t) {
var r = this instanceof (o = o || e("./_stream_duplex"));
if (!r && !c.call(C, this)) return new C(t);
this._writableState = new E(t, this, r), this.writable = !0, t && ("function" == typeof t.write && (this._write = t.write), "function" == typeof t.writev && (this._writev = t.writev), "function" == typeof t.destroy && (this._destroy = t.destroy), "function" == typeof t.final && (this._final = t.final)), a.call(this);
}
function T(e, t, r, n, i, o, s) {
t.writelen = n, t.writecb = s, t.writing = !0, t.sync = !0, t.destroyed ? t.onwrite(new m("write")) : r ? e._writev(i, t.onwrite) : e._write(i, o, t.onwrite), t.sync = !1;
}
function x(e, t, r, n) {
r || function (e, t) {
0 === t.length && t.needDrain && (t.needDrain = !1, e.emit("drain"));
}(e, t), t.pendingcb--, n(), O(e, t);
}
function A(e, t) {
t.bufferProcessing = !0;
var r = t.bufferedRequest;
if (e._writev && r && r.next) {
var n = t.bufferedRequestCount,
o = new Array(n),
s = t.corkedRequestsFree;
s.entry = r;
for (var a = 0, l = !0; r;) o[a] = r, r.isBuf || (l = !1), r = r.next, a += 1;
o.allBuffers = l, T(e, t, !0, t.length, o, "", s.finish), t.pendingcb++, t.lastBufferedRequest = null, s.next ? (t.corkedRequestsFree = s.next, s.next = null) : t.corkedRequestsFree = new i(t), t.bufferedRequestCount = 0;
} else {
for (; r;) {
var u = r.chunk,
c = r.encoding,
h = r.callback;
if (T(e, t, !1, t.objectMode ? 1 : u.length, u, c, h), r = r.next, t.bufferedRequestCount--, t.writing) break;
}
null === r && (t.lastBufferedRequest = null);
}
t.bufferedRequest = r, t.bufferProcessing = !1;
}
function I(e) {
return e.ending && 0 === e.length && null === e.bufferedRequest && !e.finished && !e.writing;
}
function P(e, t) {
e._final(function (r) {
t.pendingcb--, r && k(e, r), t.prefinished = !0, e.emit("prefinish"), O(e, t);
});
}
function O(e, t) {
var n = I(t);
if (n && (function (e, t) {
t.prefinished || t.finalCalled || ("function" != typeof e._final || t.destroyed ? (t.prefinished = !0, e.emit("prefinish")) : (t.pendingcb++, t.finalCalled = !0, r.nextTick(P, e, t)));
}(e, t), 0 === t.pendingcb && (t.finished = !0, e.emit("finish"), t.autoDestroy))) {
var i = e._readableState;
(!i || i.autoDestroy && i.endEmitted) && e.destroy();
}
return n;
}
e("inherits")(C, a), E.prototype.getBuffer = function () {
for (var e = this.bufferedRequest, t = []; e;) t.push(e), e = e.next;
return t;
}, function () {
try {
Object.defineProperty(E.prototype, "buffer", {
get: s.deprecate(function () {
return this.getBuffer();
}, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003")
});
} catch (e) {}
}(), "function" == typeof Symbol && Symbol.hasInstance && "function" == typeof Function.prototype[Symbol.hasInstance] ? (c = Function.prototype[Symbol.hasInstance], Object.defineProperty(C, Symbol.hasInstance, {
value: function (e) {
return !!c.call(this, e) || this === C && e && e._writableState instanceof E;
}
})) : c = function (e) {
return e instanceof this;
}, C.prototype.pipe = function () {
k(this, new b());
}, C.prototype.write = function (e, t, n) {
var i,
o = this._writableState,
s = !1,
a = !o.objectMode && (i = e, l.isBuffer(i) || i instanceof u);
return a && !l.isBuffer(e) && (e = function (e) {
return l.from(e);
}(e)), "function" == typeof t && (n = t, t = null), a ? t = "buffer" : t || (t = o.defaultEncoding), "function" != typeof n && (n = S), o.ending ? function (e, t) {
var n = new w();
k(e, n), r.nextTick(t, n);
}(this, n) : (a || function (e, t, n, i) {
var o;
return null === n ? o = new v() : "string" == typeof n || t.objectMode || (o = new d("chunk", ["string", "Buffer"], n)), !o || (k(e, o), r.nextTick(i, o), !1);
}(this, o, e, n)) && (o.pendingcb++, s = function (e, t, r, n, i, o) {
if (!r) {
var s = function (e, t, r) {
e.objectMode || !1 === e.decodeStrings || "string" != typeof t || (t = l.from(t, r));
return t;
}(t, n, i);
n !== s && (r = !0, i = "buffer", n = s);
}
var a = t.objectMode ? 1 : n.length;
t.length += a;
var u = t.length < t.highWaterMark;
u || (t.needDrain = !0);
if (t.writing || t.corked) {
var c = t.lastBufferedRequest;
t.lastBufferedRequest = {
chunk: n,
encoding: i,
isBuf: r,
callback: o,
next: null
}, c ? c.next = t.lastBufferedRequest : t.bufferedRequest = t.lastBufferedRequest, t.bufferedRequestCount += 1;
} else T(e, t, !1, a, n, i, o);
return u;
}(this, o, a, e, t, n)), s;
}, C.prototype.cork = function () {
this._writableState.corked++;
}, C.prototype.uncork = function () {
var e = this._writableState;
e.corked && (e.corked--, e.writing || e.corked || e.bufferProcessing || !e.bufferedRequest || A(this, e));
}, C.prototype.setDefaultEncoding = function (e) {
if ("string" == typeof e && (e = e.toLowerCase()), !(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((e + "").toLowerCase()) > -1)) throw new _(e);
return this._writableState.defaultEncoding = e, this;
}, Object.defineProperty(C.prototype, "writableBuffer", {
enumerable: !1,
get: function () {
return this._writableState && this._writableState.getBuffer();
}
}), Object.defineProperty(C.prototype, "writableHighWaterMark", {
enumerable: !1,
get: function () {
return this._writableState.highWaterMark;
}
}), C.prototype._write = function (e, t, r) {
r(new g("_write()"));
}, C.prototype._writev = null, C.prototype.end = function (e, t, n) {
var i = this._writableState;
return "function" == typeof e ? (n = e, e = null, t = null) : "function" == typeof t && (n = t, t = null), null !== e && void 0 !== e && this.write(e, t), i.corked && (i.corked = 1, this.uncork()), i.ending || function (e, t, n) {
t.ending = !0, O(e, t), n && (t.finished ? r.nextTick(n) : e.once("finish", n));
t.ended = !0, e.writable = !1;
}(this, i, n), this;
}, Object.defineProperty(C.prototype, "writableLength", {
enumerable: !1,
get: function () {
return this._writableState.length;
}
}), Object.defineProperty(C.prototype, "destroyed", {
enumerable: !1,
get: function () {
return void 0 !== this._writableState && this._writableState.destroyed;
},
set: function (e) {
this._writableState && (this._writableState.destroyed = e);
}
}), C.prototype.destroy = h.destroy, C.prototype._undestroy = h.undestroy, C.prototype._destroy = function (e, t) {
t(e);
};
}).call(this);
}).call(this, e("_process"), "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {
"../errors": 55,
"./_stream_duplex": 56,
"./internal/streams/destroy": 63,
"./internal/streams/state": 67,
"./internal/streams/stream": 68,
_process: 50,
buffer: 17,
inherits: 24,
"util-deprecate": 78
}],
61: [function (e, t, r) {
(function (r) {
(function () {
var n;
function i(e, t, r) {
return t in e ? Object.defineProperty(e, t, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = r, e;
}
var o = e("./end-of-stream"),
s = Symbol("lastResolve"),
a = Symbol("lastReject"),
l = Symbol("error"),
u = Symbol("ended"),
c = Symbol("lastPromise"),
h = Symbol("handlePromise"),
f = Symbol("stream");
function p(e, t) {
return {
value: e,
done: t
};
}
function d(e) {
var t = e[s];
if (null !== t) {
var r = e[f].read();
null !== r && (e[c] = null, e[s] = null, e[a] = null, t(p(r, !1)));
}
}
var g = Object.getPrototypeOf(function () {}),
y = Object.setPrototypeOf((i(n = {
get stream() {
return this[f];
},
next: function () {
var e = this,
t = this[l];
if (null !== t) return Promise.reject(t);
if (this[u]) return Promise.resolve(p(void 0, !0));
if (this[f].destroyed) return new Promise(function (t, n) {
r.nextTick(function () {
e[l] ? n(e[l]) : t(p(void 0, !0));
});
});
var n,
i = this[c];
if (i) n = new Promise(function (e, t) {
return function (r, n) {
e.then(function () {
t[u] ? r(p(void 0, !0)) : t[h](r, n);
}, n);
};
}(i, this));else {
var o = this[f].read();
if (null !== o) return Promise.resolve(p(o, !1));
n = new Promise(this[h]);
}
return this[c] = n, n;
}
}, Symbol.asyncIterator, function () {
return this;
}), i(n, "return", function () {
var e = this;
return new Promise(function (t, r) {
e[f].destroy(null, function (e) {
e ? r(e) : t(p(void 0, !0));
});
});
}), n), g);
t.exports = function (e) {
var t,
n = Object.create(y, (i(t = {}, f, {
value: e,
writable: !0
}), i(t, s, {
value: null,
writable: !0
}), i(t, a, {
value: null,
writable: !0
}), i(t, l, {
value: null,
writable: !0
}), i(t, u, {
value: e._readableState.endEmitted,
writable: !0
}), i(t, h, {
value: function (e, t) {
var r = n[f].read();
r ? (n[c] = null, n[s] = null, n[a] = null, e(p(r, !1))) : (n[s] = e, n[a] = t);
},
writable: !0
}), t));
return n[c] = null, o(e, function (e) {
if (e && "ERR_STREAM_PREMATURE_CLOSE" !== e.code) {
var t = n[a];
return null !== t && (n[c] = null, n[s] = null, n[a] = null, t(e)), void (n[l] = e);
}
var r = n[s];
null !== r && (n[c] = null, n[s] = null, n[a] = null, r(p(void 0, !0))), n[u] = !0;
}), e.on("readable", function (e) {
r.nextTick(d, e);
}.bind(null, n)), n;
};
}).call(this);
}).call(this, e("_process"));
}, {
"./end-of-stream": 64,
_process: 50
}],
62: [function (e, t, r) {
function n(e, t) {
var r = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var n = Object.getOwnPropertySymbols(e);
t && (n = n.filter(function (t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), r.push.apply(r, n);
}
return r;
}
function i(e, t, r) {
return t in e ? Object.defineProperty(e, t, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = r, e;
}
function o(e, t) {
for (var r = 0; r < t.length; r++) {
var n = t[r];
n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, n.key, n);
}
}
var s = e("buffer").Buffer,
a = e("util").inspect,
l = a && a.custom || "inspect";
t.exports = function () {
function e() {
!function (e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, e), this.head = null, this.tail = null, this.length = 0;
}
var t, r;
return t = e, (r = [{
key: "push",
value: function (e) {
var t = {
data: e,
next: null
};
this.length > 0 ? this.tail.next = t : this.head = t, this.tail = t, ++this.length;
}
}, {
key: "unshift",
value: function (e) {
var t = {
data: e,
next: this.head
};
0 === this.length && (this.tail = t), this.head = t, ++this.length;
}
}, {
key: "shift",
value: function () {
if (0 !== this.length) {
var e = this.head.data;
return 1 === this.length ? this.head = this.tail = null : this.head = this.head.next, --this.length, e;
}
}
}, {
key: "clear",
value: function () {
this.head = this.tail = null, this.length = 0;
}
}, {
key: "join",
value: function (e) {
if (0 === this.length) return "";
for (var t = this.head, r = "" + t.data; t = t.next;) r += e + t.data;
return r;
}
}, {
key: "concat",
value: function (e) {
if (0 === this.length) return s.alloc(0);
for (var t, r, n, i = s.allocUnsafe(e >>> 0), o = this.head, a = 0; o;) t = o.data, r = i, n = a, s.prototype.copy.call(t, r, n), a += o.data.length, o = o.next;
return i;
}
}, {
key: "consume",
value: function (e, t) {
var r;
return e < this.head.data.length ? (r = this.head.data.slice(0, e), this.head.data = this.head.data.slice(e)) : r = e === this.head.data.length ? this.shift() : t ? this._getString(e) : this._getBuffer(e), r;
}
}, {
key: "first",
value: function () {
return this.head.data;
}
}, {
key: "_getString",
value: function (e) {
var t = this.head,
r = 1,
n = t.data;
for (e -= n.length; t = t.next;) {
var i = t.data,
o = e > i.length ? i.length : e;
if (o === i.length ? n += i : n += i.slice(0, e), 0 === (e -= o)) {
o === i.length ? (++r, t.next ? this.head = t.next : this.head = this.tail = null) : (this.head = t, t.data = i.slice(o));
break;
}
++r;
}
return this.length -= r, n;
}
}, {
key: "_getBuffer",
value: function (e) {
var t = s.allocUnsafe(e),
r = this.head,
n = 1;
for (r.data.copy(t), e -= r.data.length; r = r.next;) {
var i = r.data,
o = e > i.length ? i.length : e;
if (i.copy(t, t.length - e, 0, o), 0 === (e -= o)) {
o === i.length ? (++n, r.next ? this.head = r.next : this.head = this.tail = null) : (this.head = r, r.data = i.slice(o));
break;
}
++n;
}
return this.length -= n, t;
}
}, {
key: l,
value: function (e, t) {
return a(this, function (e) {
for (var t = 1; t < arguments.length; t++) {
var r = null != arguments[t] ? arguments[t] : {};
t % 2 ? n(Object(r), !0).forEach(function (t) {
i(e, t, r[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(r)) : n(Object(r)).forEach(function (t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(r, t));
});
}
return e;
}({}, t, {
depth: 0,
customInspect: !1
}));
}
}]) && o(t.prototype, r), e;
}();
}, {
buffer: 17,
util: 16
}],
63: [function (e, t, r) {
(function (e) {
(function () {
function r(e, t) {
i(e, t), n(e);
}
function n(e) {
e._writableState && !e._writableState.emitClose || e._readableState && !e._readableState.emitClose || e.emit("close");
}
function i(e, t) {
e.emit("error", t);
}
t.exports = {
destroy: function (t, o) {
var s = this,
a = this._readableState && this._readableState.destroyed,
l = this._writableState && this._writableState.destroyed;
return a || l ? (o ? o(t) : t && (this._writableState ? this._writableState.errorEmitted || (this._writableState.errorEmitted = !0, e.nextTick(i, this, t)) : e.nextTick(i, this, t)), this) : (this._readableState && (this._readableState.destroyed = !0), this._writableState && (this._writableState.destroyed = !0), this._destroy(t || null, function (t) {
!o && t ? s._writableState ? s._writableState.errorEmitted ? e.nextTick(n, s) : (s._writableState.errorEmitted = !0, e.nextTick(r, s, t)) : e.nextTick(r, s, t) : o ? (e.nextTick(n, s), o(t)) : e.nextTick(n, s);
}), this);
},
undestroy: function () {
this._readableState && (this._readableState.destroyed = !1, this._readableState.reading = !1, this._readableState.ended = !1, this._readableState.endEmitted = !1), this._writableState && (this._writableState.destroyed = !1, this._writableState.ended = !1, this._writableState.ending = !1, this._writableState.finalCalled = !1, this._writableState.prefinished = !1, this._writableState.finished = !1, this._writableState.errorEmitted = !1);
},
errorOrDestroy: function (e, t) {
var r = e._readableState,
n = e._writableState;
r && r.autoDestroy || n && n.autoDestroy ? e.destroy(t) : e.emit("error", t);
}
};
}).call(this);
}).call(this, e("_process"));
}, {
_process: 50
}],
64: [function (e, t, r) {
var n = e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;
function i() {}
t.exports = function e(t, r, o) {
if ("function" == typeof r) return e(t, null, r);
r || (r = {}), o = function (e) {
var t = !1;
return function () {
if (!t) {
t = !0;
for (var r = arguments.length, n = new Array(r), i = 0; i < r; i++) n[i] = arguments[i];
e.apply(this, n);
}
};
}(o || i);
var s = r.readable || !1 !== r.readable && t.readable,
a = r.writable || !1 !== r.writable && t.writable,
l = function () {
t.writable || c();
},
u = t._writableState && t._writableState.finished,
c = function () {
a = !1, u = !0, s || o.call(t);
},
h = t._readableState && t._readableState.endEmitted,
f = function () {
s = !1, h = !0, a || o.call(t);
},
p = function (e) {
o.call(t, e);
},
d = function () {
var e;
return s && !h ? (t._readableState && t._readableState.ended || (e = new n()), o.call(t, e)) : a && !u ? (t._writableState && t._writableState.ended || (e = new n()), o.call(t, e)) : void 0;
},
g = function () {
t.req.on("finish", c);
};
return function (e) {
return e.setHeader && "function" == typeof e.abort;
}(t) ? (t.on("complete", c), t.on("abort", d), t.req ? g() : t.on("request", g)) : a && !t._writableState && (t.on("end", l), t.on("close", l)), t.on("end", f), t.on("finish", c), !1 !== r.error && t.on("error", p), t.on("close", d), function () {
t.removeListener("complete", c), t.removeListener("abort", d), t.removeListener("request", g), t.req && t.req.removeListener("finish", c), t.removeListener("end", l), t.removeListener("close", l), t.removeListener("finish", c), t.removeListener("end", f), t.removeListener("error", p), t.removeListener("close", d);
};
};
}, {
"../../../errors": 55
}],
65: [function (e, t, r) {
t.exports = function () {
throw new Error("Readable.from is not available in the browser");
};
}, {}],
66: [function (e, t, r) {
var n;
var i = e("../../../errors").codes,
o = i.ERR_MISSING_ARGS,
s = i.ERR_STREAM_DESTROYED;
function a(e) {
if (e) throw e;
}
function l(e) {
e();
}
function u(e, t) {
return e.pipe(t);
}
t.exports = function () {
for (var t = arguments.length, r = new Array(t), i = 0; i < t; i++) r[i] = arguments[i];
var c,
h = function (e) {
return e.length ? "function" != typeof e[e.length - 1] ? a : e.pop() : a;
}(r);
if (Array.isArray(r[0]) && (r = r[0]), r.length < 2) throw new o("streams");
var f = r.map(function (t, i) {
var o = i < r.length - 1;
return function (t, r, i, o) {
o = function (e) {
var t = !1;
return function () {
t || (t = !0, e.apply(void 0, arguments));
};
}(o);
var a = !1;
t.on("close", function () {
a = !0;
}), void 0 === n && (n = e("./end-of-stream")), n(t, {
readable: r,
writable: i
}, function (e) {
if (e) return o(e);
a = !0, o();
});
var l = !1;
return function (e) {
if (!a && !l) return l = !0, function (e) {
return e.setHeader && "function" == typeof e.abort;
}(t) ? t.abort() : "function" == typeof t.destroy ? t.destroy() : void o(e || new s("pipe"));
};
}(t, o, i > 0, function (e) {
c || (c = e), e && f.forEach(l), o || (f.forEach(l), h(c));
});
});
return r.reduce(u);
};
}, {
"../../../errors": 55,
"./end-of-stream": 64
}],
67: [function (e, t, r) {
var n = e("../../../errors").codes.ERR_INVALID_OPT_VALUE;
t.exports = {
getHighWaterMark: function (e, t, r, i) {
var o = function (e, t, r) {
return null != e.highWaterMark ? e.highWaterMark : t ? e[r] : null;
}(t, i, r);
if (null != o) {
if (!isFinite(o) || Math.floor(o) !== o || o < 0) throw new n(i ? r : "highWaterMark", o);
return Math.floor(o);
}
return e.objectMode ? 16 : 16384;
}
};
}, {
"../../../errors": 55
}],
68: [function (e, t, r) {
t.exports = e("events").EventEmitter;
}, {
events: 22
}],
69: [function (e, t, r) {
(r = t.exports = e("./lib/_stream_readable.js")).Stream = r, r.Readable = r, r.Writable = e("./lib/_stream_writable.js"), r.Duplex = e("./lib/_stream_duplex.js"), r.Transform = e("./lib/_stream_transform.js"), r.PassThrough = e("./lib/_stream_passthrough.js"), r.finished = e("./lib/internal/streams/end-of-stream.js"), r.pipeline = e("./lib/internal/streams/pipeline.js");
}, {
"./lib/_stream_duplex.js": 56,
"./lib/_stream_passthrough.js": 57,
"./lib/_stream_readable.js": 58,
"./lib/_stream_transform.js": 59,
"./lib/_stream_writable.js": 60,
"./lib/internal/streams/end-of-stream.js": 64,
"./lib/internal/streams/pipeline.js": 66
}],
70: [function (e, t, r) {
t.exports = function () {
if ("function" != typeof arguments[0]) throw new Error("callback needed");
if ("number" != typeof arguments[1]) throw new Error("interval needed");
var e;
if (arguments.length > 0) {
e = new Array(arguments.length - 2);
for (var t = 0; t < e.length; t++) e[t] = arguments[t + 2];
}
return new function (e, t, r) {
var n = this;
this._callback = e, this._args = r, this._interval = setInterval(e, t, this._args), this.reschedule = function (e) {
e || (e = n._interval), n._interval && clearInterval(n._interval), n._interval = setInterval(n._callback, e, n._args);
}, this.clear = function () {
n._interval && (clearInterval(n._interval), n._interval = void 0);
}, this.destroy = function () {
n._interval && clearInterval(n._interval), n._callback = void 0, n._interval = void 0, n._args = void 0;
};
}(arguments[0], arguments[1], e);
};
}, {}],
71: [function (e, t, r) {
t.exports = e("./index.js")();
}, {
"./index.js": 72
}],
72: [function (e, t, r) {
(function (e) {
(function () {
function r(t) {
return t instanceof e ? e.from(t) : new t.constructor(t.buffer.slice(), t.byteOffset, t.length);
}
t.exports = function (e) {
return (e = e || {}).circles ? function (e) {
var t = [],
n = [];
return e.proto ? function e(o) {
if ("object" != typeof o || null === o) return o;
if (o instanceof Date) return new Date(o);
if (Array.isArray(o)) return i(o, e);
if (o instanceof Map) return new Map(i(Array.from(o), e));
if (o instanceof Set) return new Set(i(Array.from(o), e));
var s = {};
for (var a in t.push(o), n.push(s), o) {
var l = o[a];
if ("object" != typeof l || null === l) s[a] = l;else if (l instanceof Date) s[a] = new Date(l);else if (l instanceof Map) s[a] = new Map(i(Array.from(l), e));else if (l instanceof Set) s[a] = new Set(i(Array.from(l), e));else if (ArrayBuffer.isView(l)) s[a] = r(l);else {
var u = t.indexOf(l);
s[a] = -1 !== u ? n[u] : e(l);
}
}
return t.pop(), n.pop(), s;
} : function e(o) {
if ("object" != typeof o || null === o) return o;
if (o instanceof Date) return new Date(o);
if (Array.isArray(o)) return i(o, e);
if (o instanceof Map) return new Map(i(Array.from(o), e));
if (o instanceof Set) return new Set(i(Array.from(o), e));
var s = {};
for (var a in t.push(o), n.push(s), o) if (!1 !== Object.hasOwnProperty.call(o, a)) {
var l = o[a];
if ("object" != typeof l || null === l) s[a] = l;else if (l instanceof Date) s[a] = new Date(l);else if (l instanceof Map) s[a] = new Map(i(Array.from(l), e));else if (l instanceof Set) s[a] = new Set(i(Array.from(l), e));else if (ArrayBuffer.isView(l)) s[a] = r(l);else {
var u = t.indexOf(l);
s[a] = -1 !== u ? n[u] : e(l);
}
}
return t.pop(), n.pop(), s;
};
function i(e, i) {
for (var o = Object.keys(e), s = new Array(o.length), a = 0; a < o.length; a++) {
var l = o[a],
u = e[l];
if ("object" != typeof u || null === u) s[l] = u;else if (u instanceof Date) s[l] = new Date(u);else if (ArrayBuffer.isView(u)) s[l] = r(u);else {
var c = t.indexOf(u);
s[l] = -1 !== c ? n[c] : i(u);
}
}
return s;
}
}(e) : e.proto ? function e(n) {
if ("object" != typeof n || null === n) return n;
if (n instanceof Date) return new Date(n);
if (Array.isArray(n)) return t(n, e);
if (n instanceof Map) return new Map(t(Array.from(n), e));
if (n instanceof Set) return new Set(t(Array.from(n), e));
var i = {};
for (var o in n) {
var s = n[o];
"object" != typeof s || null === s ? i[o] = s : s instanceof Date ? i[o] = new Date(s) : s instanceof Map ? i[o] = new Map(t(Array.from(s), e)) : s instanceof Set ? i[o] = new Set(t(Array.from(s), e)) : ArrayBuffer.isView(s) ? i[o] = r(s) : i[o] = e(s);
}
return i;
} : function e(n) {
if ("object" != typeof n || null === n) return n;
if (n instanceof Date) return new Date(n);
if (Array.isArray(n)) return t(n, e);
if (n instanceof Map) return new Map(t(Array.from(n), e));
if (n instanceof Set) return new Set(t(Array.from(n), e));
var i = {};
for (var o in n) if (!1 !== Object.hasOwnProperty.call(n, o)) {
var s = n[o];
"object" != typeof s || null === s ? i[o] = s : s instanceof Date ? i[o] = new Date(s) : s instanceof Map ? i[o] = new Map(t(Array.from(s), e)) : s instanceof Set ? i[o] = new Set(t(Array.from(s), e)) : ArrayBuffer.isView(s) ? i[o] = r(s) : i[o] = e(s);
}
return i;
};
function t(e, t) {
for (var n = Object.keys(e), i = new Array(n.length), o = 0; o < n.length; o++) {
var s = n[o],
a = e[s];
"object" != typeof a || null === a ? i[s] = a : a instanceof Date ? i[s] = new Date(a) : ArrayBuffer.isView(a) ? i[s] = r(a) : i[s] = t(a);
}
return i;
}
};
}).call(this);
}).call(this, e("buffer").Buffer);
}, {
buffer: 17
}],
73: [function (e, t, r) {
var n = e("buffer"),
i = n.Buffer;
function o(e, t) {
for (var r in e) t[r] = e[r];
}
function s(e, t, r) {
return i(e, t, r);
}
i.from && i.alloc && i.allocUnsafe && i.allocUnsafeSlow ? t.exports = n : (o(n, r), r.Buffer = s), s.prototype = Object.create(i.prototype), o(i, s), s.from = function (e, t, r) {
if ("number" == typeof e) throw new TypeError("Argument must not be a number");
return i(e, t, r);
}, s.alloc = function (e, t, r) {
if ("number" != typeof e) throw new TypeError("Argument must be a number");
var n = i(e);
return void 0 !== t ? "string" == typeof r ? n.fill(t, r) : n.fill(t) : n.fill(0), n;
}, s.allocUnsafe = function (e) {
if ("number" != typeof e) throw new TypeError("Argument must be a number");
return i(e);
}, s.allocUnsafeSlow = function (e) {
if ("number" != typeof e) throw new TypeError("Argument must be a number");
return n.SlowBuffer(e);
};
}, {
buffer: 17
}],
74: [function (e, t, r) {
t.exports = function (e) {
var t = e._readableState;
return t ? t.objectMode || "number" == typeof e._duplexState ? e.read() : e.read((r = t, r.buffer.length ? r.buffer.head ? r.buffer.head.data.length : r.buffer[0].length : r.length)) : null;
var r;
};
}, {}],
75: [function (e, t, r) {
var n = e("safe-buffer").Buffer,
i = n.isEncoding || function (e) {
switch ((e = "" + e) && e.toLowerCase()) {
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
case "raw":
return !0;
default:
return !1;
}
};
function o(e) {
var t;
switch (this.encoding = function (e) {
var t = function (e) {
if (!e) return "utf8";
for (var t;;) switch (e) {
case "utf8":
case "utf-8":
return "utf8";
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return "utf16le";
case "latin1":
case "binary":
return "latin1";
case "base64":
case "ascii":
case "hex":
return e;
default:
if (t) return;
e = ("" + e).toLowerCase(), t = !0;
}
}(e);
if ("string" != typeof t && (n.isEncoding === i || !i(e))) throw new Error("Unknown encoding: " + e);
return t || e;
}(e), this.encoding) {
case "utf16le":
this.text = l, this.end = u, t = 4;
break;
case "utf8":
this.fillLast = a, t = 4;
break;
case "base64":
this.text = c, this.end = h, t = 3;
break;
default:
return this.write = f, void (this.end = p);
}
this.lastNeed = 0, this.lastTotal = 0, this.lastChar = n.allocUnsafe(t);
}
function s(e) {
return e <= 127 ? 0 : e >> 5 == 6 ? 2 : e >> 4 == 14 ? 3 : e >> 3 == 30 ? 4 : e >> 6 == 2 ? -1 : -2;
}
function a(e) {
var t = this.lastTotal - this.lastNeed,
r = function (e, t, r) {
if (128 != (192 & t[0])) return e.lastNeed = 0, "<22>";
if (e.lastNeed > 1 && t.length > 1) {
if (128 != (192 & t[1])) return e.lastNeed = 1, "<22>";
if (e.lastNeed > 2 && t.length > 2 && 128 != (192 & t[2])) return e.lastNeed = 2, "<22>";
}
}(this, e);
return void 0 !== r ? r : this.lastNeed <= e.length ? (e.copy(this.lastChar, t, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal)) : (e.copy(this.lastChar, t, 0, e.length), void (this.lastNeed -= e.length));
}
function l(e, t) {
if ((e.length - t) % 2 == 0) {
var r = e.toString("utf16le", t);
if (r) {
var n = r.charCodeAt(r.length - 1);
if (n >= 55296 && n <= 56319) return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1], r.slice(0, -1);
}
return r;
}
return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e[e.length - 1], e.toString("utf16le", t, e.length - 1);
}
function u(e) {
var t = e && e.length ? this.write(e) : "";
if (this.lastNeed) {
var r = this.lastTotal - this.lastNeed;
return t + this.lastChar.toString("utf16le", 0, r);
}
return t;
}
function c(e, t) {
var r = (e.length - t) % 3;
return 0 === r ? e.toString("base64", t) : (this.lastNeed = 3 - r, this.lastTotal = 3, 1 === r ? this.lastChar[0] = e[e.length - 1] : (this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1]), e.toString("base64", t, e.length - r));
}
function h(e) {
var t = e && e.length ? this.write(e) : "";
return this.lastNeed ? t + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t;
}
function f(e) {
return e.toString(this.encoding);
}
function p(e) {
return e && e.length ? this.write(e) : "";
}
r.StringDecoder = o, o.prototype.write = function (e) {
if (0 === e.length) return "";
var t, r;
if (this.lastNeed) {
if (void 0 === (t = this.fillLast(e))) return "";
r = this.lastNeed, this.lastNeed = 0;
} else r = 0;
return r < e.length ? t ? t + this.text(e, r) : this.text(e, r) : t || "";
}, o.prototype.end = function (e) {
var t = e && e.length ? this.write(e) : "";
return this.lastNeed ? t + "<22>" : t;
}, o.prototype.text = function (e, t) {
var r = function (e, t, r) {
var n = t.length - 1;
if (n < r) return 0;
var i = s(t[n]);
if (i >= 0) return i > 0 && (e.lastNeed = i - 1), i;
if (--n < r || -2 === i) return 0;
if ((i = s(t[n])) >= 0) return i > 0 && (e.lastNeed = i - 2), i;
if (--n < r || -2 === i) return 0;
if ((i = s(t[n])) >= 0) return i > 0 && (2 === i ? i = 0 : e.lastNeed = i - 3), i;
return 0;
}(this, e, t);
if (!this.lastNeed) return e.toString("utf8", t);
this.lastTotal = r;
var n = e.length - (r - this.lastNeed);
return e.copy(this.lastChar, 0, n), e.toString("utf8", t, n);
}, o.prototype.fillLast = function (e) {
if (this.lastNeed <= e.length) return e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal);
e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e.length), this.lastNeed -= e.length;
};
}, {
"safe-buffer": 73
}],
76: [function (e, t, r) {
var n = e("punycode"),
i = e("./util");
function o() {
this.protocol = null, this.slashes = null, this.auth = null, this.host = null, this.port = null, this.hostname = null, this.hash = null, this.search = null, this.query = null, this.pathname = null, this.path = null, this.href = null;
}
r.parse = v, r.resolve = function (e, t) {
return v(e, !1, !0).resolve(t);
}, r.resolveObject = function (e, t) {
return e ? v(e, !1, !0).resolveObject(t) : t;
}, r.format = function (e) {
i.isString(e) && (e = v(e));
return e instanceof o ? e.format() : o.prototype.format.call(e);
}, r.Url = o;
var s = /^([a-z0-9.+-]+:)/i,
a = /:[0-9]*$/,
l = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
u = ["{", "}", "|", "\\", "^", "`"].concat(["<", ">", '"', "`", " ", "\r", "\n", "\t"]),
c = ["'"].concat(u),
h = ["%", "/", "?", ";", "#"].concat(c),
f = ["/", "?", "#"],
p = /^[+a-z0-9A-Z_-]{0,63}$/,
d = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
g = {
javascript: !0,
"javascript:": !0
},
y = {
javascript: !0,
"javascript:": !0
},
b = {
http: !0,
https: !0,
ftp: !0,
gopher: !0,
file: !0,
"http:": !0,
"https:": !0,
"ftp:": !0,
"gopher:": !0,
"file:": !0
},
m = e("querystring");
function v(e, t, r) {
if (e && i.isObject(e) && e instanceof o) return e;
var n = new o();
return n.parse(e, t, r), n;
}
o.prototype.parse = function (e, t, r) {
if (!i.isString(e)) throw new TypeError("Parameter 'url' must be a string, not " + typeof e);
var o = e.indexOf("?"),
a = -1 !== o && o < e.indexOf("#") ? "?" : "#",
u = e.split(a);
u[0] = u[0].replace(/\\/g, "/");
var v = e = u.join(a);
if (v = v.trim(), !r && 1 === e.split("#").length) {
var w = l.exec(v);
if (w) return this.path = v, this.href = v, this.pathname = w[1], w[2] ? (this.search = w[2], this.query = t ? m.parse(this.search.substr(1)) : this.search.substr(1)) : t && (this.search = "", this.query = {}), this;
}
var _ = s.exec(v);
if (_) {
var k = (_ = _[0]).toLowerCase();
this.protocol = k, v = v.substr(_.length);
}
if (r || _ || v.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var S = "//" === v.substr(0, 2);
!S || _ && y[_] || (v = v.substr(2), this.slashes = !0);
}
if (!y[_] && (S || _ && !b[_])) {
for (var E, C, T = -1, x = 0; x < f.length; x++) {
-1 !== (A = v.indexOf(f[x])) && (-1 === T || A < T) && (T = A);
}
-1 !== (C = -1 === T ? v.lastIndexOf("@") : v.lastIndexOf("@", T)) && (E = v.slice(0, C), v = v.slice(C + 1), this.auth = decodeURIComponent(E)), T = -1;
for (x = 0; x < h.length; x++) {
var A;
-1 !== (A = v.indexOf(h[x])) && (-1 === T || A < T) && (T = A);
}
-1 === T && (T = v.length), this.host = v.slice(0, T), v = v.slice(T), this.parseHost(), this.hostname = this.hostname || "";
var I = "[" === this.hostname[0] && "]" === this.hostname[this.hostname.length - 1];
if (!I) for (var P = this.hostname.split(/\./), O = (x = 0, P.length); x < O; x++) {
var B = P[x];
if (B && !B.match(p)) {
for (var R = "", M = 0, N = B.length; M < N; M++) B.charCodeAt(M) > 127 ? R += "x" : R += B[M];
if (!R.match(p)) {
var L = P.slice(0, x),
j = P.slice(x + 1),
U = B.match(d);
U && (L.push(U[1]), j.unshift(U[2])), j.length && (v = "/" + j.join(".") + v), this.hostname = L.join(".");
break;
}
}
}
this.hostname.length > 255 ? this.hostname = "" : this.hostname = this.hostname.toLowerCase(), I || (this.hostname = n.toASCII(this.hostname));
var q = this.port ? ":" + this.port : "",
D = this.hostname || "";
this.host = D + q, this.href += this.host, I && (this.hostname = this.hostname.substr(1, this.hostname.length - 2), "/" !== v[0] && (v = "/" + v));
}
if (!g[k]) for (x = 0, O = c.length; x < O; x++) {
var z = c[x];
if (-1 !== v.indexOf(z)) {
var F = encodeURIComponent(z);
F === z && (F = escape(z)), v = v.split(z).join(F);
}
}
var V = v.indexOf("#");
-1 !== V && (this.hash = v.substr(V), v = v.slice(0, V));
var H = v.indexOf("?");
if (-1 !== H ? (this.search = v.substr(H), this.query = v.substr(H + 1), t && (this.query = m.parse(this.query)), v = v.slice(0, H)) : t && (this.search = "", this.query = {}), v && (this.pathname = v), b[k] && this.hostname && !this.pathname && (this.pathname = "/"), this.pathname || this.search) {
q = this.pathname || "";
var W = this.search || "";
this.path = q + W;
}
return this.href = this.format(), this;
}, o.prototype.format = function () {
var e = this.auth || "";
e && (e = (e = encodeURIComponent(e)).replace(/%3A/i, ":"), e += "@");
var t = this.protocol || "",
r = this.pathname || "",
n = this.hash || "",
o = !1,
s = "";
this.host ? o = e + this.host : this.hostname && (o = e + (-1 === this.hostname.indexOf(":") ? this.hostname : "[" + this.hostname + "]"), this.port && (o += ":" + this.port)), this.query && i.isObject(this.query) && Object.keys(this.query).length && (s = m.stringify(this.query));
var a = this.search || s && "?" + s || "";
return t && ":" !== t.substr(-1) && (t += ":"), this.slashes || (!t || b[t]) && !1 !== o ? (o = "//" + (o || ""), r && "/" !== r.charAt(0) && (r = "/" + r)) : o || (o = ""), n && "#" !== n.charAt(0) && (n = "#" + n), a && "?" !== a.charAt(0) && (a = "?" + a), t + o + (r = r.replace(/[?#]/g, function (e) {
return encodeURIComponent(e);
})) + (a = a.replace("#", "%23")) + n;
}, o.prototype.resolve = function (e) {
return this.resolveObject(v(e, !1, !0)).format();
}, o.prototype.resolveObject = function (e) {
if (i.isString(e)) {
var t = new o();
t.parse(e, !1, !0), e = t;
}
for (var r = new o(), n = Object.keys(this), s = 0; s < n.length; s++) {
var a = n[s];
r[a] = this[a];
}
if (r.hash = e.hash, "" === e.href) return r.href = r.format(), r;
if (e.slashes && !e.protocol) {
for (var l = Object.keys(e), u = 0; u < l.length; u++) {
var c = l[u];
"protocol" !== c && (r[c] = e[c]);
}
return b[r.protocol] && r.hostname && !r.pathname && (r.path = r.pathname = "/"), r.href = r.format(), r;
}
if (e.protocol && e.protocol !== r.protocol) {
if (!b[e.protocol]) {
for (var h = Object.keys(e), f = 0; f < h.length; f++) {
var p = h[f];
r[p] = e[p];
}
return r.href = r.format(), r;
}
if (r.protocol = e.protocol, e.host || y[e.protocol]) r.pathname = e.pathname;else {
for (var d = (e.pathname || "").split("/"); d.length && !(e.host = d.shift()););
e.host || (e.host = ""), e.hostname || (e.hostname = ""), "" !== d[0] && d.unshift(""), d.length < 2 && d.unshift(""), r.pathname = d.join("/");
}
if (r.search = e.search, r.query = e.query, r.host = e.host || "", r.auth = e.auth, r.hostname = e.hostname || e.host, r.port = e.port, r.pathname || r.search) {
var g = r.pathname || "",
m = r.search || "";
r.path = g + m;
}
return r.slashes = r.slashes || e.slashes, r.href = r.format(), r;
}
var v = r.pathname && "/" === r.pathname.charAt(0),
w = e.host || e.pathname && "/" === e.pathname.charAt(0),
_ = w || v || r.host && e.pathname,
k = _,
S = r.pathname && r.pathname.split("/") || [],
E = (d = e.pathname && e.pathname.split("/") || [], r.protocol && !b[r.protocol]);
if (E && (r.hostname = "", r.port = null, r.host && ("" === S[0] ? S[0] = r.host : S.unshift(r.host)), r.host = "", e.protocol && (e.hostname = null, e.port = null, e.host && ("" === d[0] ? d[0] = e.host : d.unshift(e.host)), e.host = null), _ = _ && ("" === d[0] || "" === S[0])), w) r.host = e.host || "" === e.host ? e.host : r.host, r.hostname = e.hostname || "" === e.hostname ? e.hostname : r.hostname, r.search = e.search, r.query = e.query, S = d;else if (d.length) S || (S = []), S.pop(), S = S.concat(d), r.search = e.search, r.query = e.query;else if (!i.isNullOrUndefined(e.search)) {
if (E) r.hostname = r.host = S.shift(), (I = !!(r.host && r.host.indexOf("@") > 0) && r.host.split("@")) && (r.auth = I.shift(), r.host = r.hostname = I.shift());
return r.search = e.search, r.query = e.query, i.isNull(r.pathname) && i.isNull(r.search) || (r.path = (r.pathname ? r.pathname : "") + (r.search ? r.search : "")), r.href = r.format(), r;
}
if (!S.length) return r.pathname = null, r.search ? r.path = "/" + r.search : r.path = null, r.href = r.format(), r;
for (var C = S.slice(-1)[0], T = (r.host || e.host || S.length > 1) && ("." === C || ".." === C) || "" === C, x = 0, A = S.length; A >= 0; A--) "." === (C = S[A]) ? S.splice(A, 1) : ".." === C ? (S.splice(A, 1), x++) : x && (S.splice(A, 1), x--);
if (!_ && !k) for (; x--; x) S.unshift("..");
!_ || "" === S[0] || S[0] && "/" === S[0].charAt(0) || S.unshift(""), T && "/" !== S.join("/").substr(-1) && S.push("");
var I,
P = "" === S[0] || S[0] && "/" === S[0].charAt(0);
E && (r.hostname = r.host = P ? "" : S.length ? S.shift() : "", (I = !!(r.host && r.host.indexOf("@") > 0) && r.host.split("@")) && (r.auth = I.shift(), r.host = r.hostname = I.shift()));
return (_ = _ || r.host && S.length) && !P && S.unshift(""), S.length ? r.pathname = S.join("/") : (r.pathname = null, r.path = null), i.isNull(r.pathname) && i.isNull(r.search) || (r.path = (r.pathname ? r.pathname : "") + (r.search ? r.search : "")), r.auth = e.auth || r.auth, r.slashes = r.slashes || e.slashes, r.href = r.format(), r;
}, o.prototype.parseHost = function () {
var e = this.host,
t = a.exec(e);
t && (":" !== (t = t[0]) && (this.port = t.substr(1)), e = e.substr(0, e.length - t.length)), e && (this.hostname = e);
};
}, {
"./util": 77,
punycode: 51,
querystring: 54
}],
77: [function (e, t, r) {
t.exports = {
isString: function (e) {
return "string" == typeof e;
},
isObject: function (e) {
return "object" == typeof e && null !== e;
},
isNull: function (e) {
return null === e;
},
isNullOrUndefined: function (e) {
return null == e;
}
};
}, {}],
78: [function (e, t, r) {
(function (e) {
(function () {
function r(t) {
try {
if (!e.localStorage) return !1;
} catch (e) {
return !1;
}
var r = e.localStorage[t];
return null != r && "true" === String(r).toLowerCase();
}
t.exports = function (e, t) {
if (r("noDeprecation")) return e;
var n = !1;
return function () {
if (!n) {
if (r("throwDeprecation")) throw new Error(t);
r("traceDeprecation") ? console.trace(t) : console.warn(t), n = !0;
}
return e.apply(this, arguments);
};
};
}).call(this);
}).call(this, "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}],
79: [function (e, t, r) {
t.exports = function e(t, r) {
if (t && r) return e(t)(r);
if ("function" != typeof t) throw new TypeError("need wrapper function");
Object.keys(t).forEach(function (e) {
n[e] = t[e];
});
return n;
function n() {
for (var e = new Array(arguments.length), r = 0; r < e.length; r++) e[r] = arguments[r];
var n = t.apply(this, e),
i = e[e.length - 1];
return "function" == typeof n && n !== i && Object.keys(i).forEach(function (e) {
n[e] = i[e];
}), n;
}
};
}, {}],
80: [function (e, t, r) {
t.exports = function () {
throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object");
};
}, {}],
81: [function (e, t, r) {
t.exports = function () {
for (var e = {}, t = 0; t < arguments.length; t++) {
var r = arguments[t];
for (var i in r) n.call(r, i) && (e[i] = r[i]);
}
return e;
};
var n = Object.prototype.hasOwnProperty;
}, {}],
82: [function (e, t, r) {
t.exports = function (e) {
e.prototype[Symbol.iterator] = function* () {
for (let e = this.head; e; e = e.next) yield e.value;
};
};
}, {}],
83: [function (e, t, r) {
function n(e) {
var t = this;
if (t instanceof n || (t = new n()), t.tail = null, t.head = null, t.length = 0, e && "function" == typeof e.forEach) e.forEach(function (e) {
t.push(e);
});else if (arguments.length > 0) for (var r = 0, i = arguments.length; r < i; r++) t.push(arguments[r]);
return t;
}
function i(e, t, r) {
var n = t === e.head ? new a(r, null, t, e) : new a(r, t, t.next, e);
return null === n.next && (e.tail = n), null === n.prev && (e.head = n), e.length++, n;
}
function o(e, t) {
e.tail = new a(t, e.tail, null, e), e.head || (e.head = e.tail), e.length++;
}
function s(e, t) {
e.head = new a(t, null, e.head, e), e.tail || (e.tail = e.head), e.length++;
}
function a(e, t, r, n) {
if (!(this instanceof a)) return new a(e, t, r, n);
this.list = n, this.value = e, t ? (t.next = this, this.prev = t) : this.prev = null, r ? (r.prev = this, this.next = r) : this.next = null;
}
t.exports = n, n.Node = a, n.create = n, n.prototype.removeNode = function (e) {
if (e.list !== this) throw new Error("removing node which does not belong to this list");
var t = e.next,
r = e.prev;
return t && (t.prev = r), r && (r.next = t), e === this.head && (this.head = t), e === this.tail && (this.tail = r), e.list.length--, e.next = null, e.prev = null, e.list = null, t;
}, n.prototype.unshiftNode = function (e) {
if (e !== this.head) {
e.list && e.list.removeNode(e);
var t = this.head;
e.list = this, e.next = t, t && (t.prev = e), this.head = e, this.tail || (this.tail = e), this.length++;
}
}, n.prototype.pushNode = function (e) {
if (e !== this.tail) {
e.list && e.list.removeNode(e);
var t = this.tail;
e.list = this, e.prev = t, t && (t.next = e), this.tail = e, this.head || (this.head = e), this.length++;
}
}, n.prototype.push = function () {
for (var e = 0, t = arguments.length; e < t; e++) o(this, arguments[e]);
return this.length;
}, n.prototype.unshift = function () {
for (var e = 0, t = arguments.length; e < t; e++) s(this, arguments[e]);
return this.length;
}, n.prototype.pop = function () {
if (this.tail) {
var e = this.tail.value;
return this.tail = this.tail.prev, this.tail ? this.tail.next = null : this.head = null, this.length--, e;
}
}, n.prototype.shift = function () {
if (this.head) {
var e = this.head.value;
return this.head = this.head.next, this.head ? this.head.prev = null : this.tail = null, this.length--, e;
}
}, n.prototype.forEach = function (e, t) {
t = t || this;
for (var r = this.head, n = 0; null !== r; n++) e.call(t, r.value, n, this), r = r.next;
}, n.prototype.forEachReverse = function (e, t) {
t = t || this;
for (var r = this.tail, n = this.length - 1; null !== r; n--) e.call(t, r.value, n, this), r = r.prev;
}, n.prototype.get = function (e) {
for (var t = 0, r = this.head; null !== r && t < e; t++) r = r.next;
if (t === e && null !== r) return r.value;
}, n.prototype.getReverse = function (e) {
for (var t = 0, r = this.tail; null !== r && t < e; t++) r = r.prev;
if (t === e && null !== r) return r.value;
}, n.prototype.map = function (e, t) {
t = t || this;
for (var r = new n(), i = this.head; null !== i;) r.push(e.call(t, i.value, this)), i = i.next;
return r;
}, n.prototype.mapReverse = function (e, t) {
t = t || this;
for (var r = new n(), i = this.tail; null !== i;) r.push(e.call(t, i.value, this)), i = i.prev;
return r;
}, n.prototype.reduce = function (e, t) {
var r,
n = this.head;
if (arguments.length > 1) r = t;else {
if (!this.head) throw new TypeError("Reduce of empty list with no initial value");
n = this.head.next, r = this.head.value;
}
for (var i = 0; null !== n; i++) r = e(r, n.value, i), n = n.next;
return r;
}, n.prototype.reduceReverse = function (e, t) {
var r,
n = this.tail;
if (arguments.length > 1) r = t;else {
if (!this.tail) throw new TypeError("Reduce of empty list with no initial value");
n = this.tail.prev, r = this.tail.value;
}
for (var i = this.length - 1; null !== n; i--) r = e(r, n.value, i), n = n.prev;
return r;
}, n.prototype.toArray = function () {
for (var e = new Array(this.length), t = 0, r = this.head; null !== r; t++) e[t] = r.value, r = r.next;
return e;
}, n.prototype.toArrayReverse = function () {
for (var e = new Array(this.length), t = 0, r = this.tail; null !== r; t++) e[t] = r.value, r = r.prev;
return e;
}, n.prototype.slice = function (e, t) {
(t = t || this.length) < 0 && (t += this.length), (e = e || 0) < 0 && (e += this.length);
var r = new n();
if (t < e || t < 0) return r;
e < 0 && (e = 0), t > this.length && (t = this.length);
for (var i = 0, o = this.head; null !== o && i < e; i++) o = o.next;
for (; null !== o && i < t; i++, o = o.next) r.push(o.value);
return r;
}, n.prototype.sliceReverse = function (e, t) {
(t = t || this.length) < 0 && (t += this.length), (e = e || 0) < 0 && (e += this.length);
var r = new n();
if (t < e || t < 0) return r;
e < 0 && (e = 0), t > this.length && (t = this.length);
for (var i = this.length, o = this.tail; null !== o && i > t; i--) o = o.prev;
for (; null !== o && i > e; i--, o = o.prev) r.push(o.value);
return r;
}, n.prototype.splice = function (e, t, ...r) {
e > this.length && (e = this.length - 1), e < 0 && (e = this.length + e);
for (var n = 0, o = this.head; null !== o && n < e; n++) o = o.next;
var s = [];
for (n = 0; o && n < t; n++) s.push(o.value), o = this.removeNode(o);
null === o && (o = this.tail), o !== this.head && o !== this.tail && (o = o.prev);
for (n = 0; n < r.length; n++) o = i(this, o, r[n]);
return s;
}, n.prototype.reverse = function () {
for (var e = this.head, t = this.tail, r = e; null !== r; r = r.prev) {
var n = r.prev;
r.prev = r.next, r.next = n;
}
return this.head = t, this.tail = e, this;
};
try {
e("./iterator.js")(n);
} catch (e) {}
}, {
"./iterator.js": 82
}]
}, {}, [12])(12);
});
})(mqtt_min);
var mqtt_minExports = mqtt_min.exports;
var logger$2 = new Logger('mqtt');
var DEBUG = '__duix-debug';
window.DUIXDEBUG = function (flag) {
if (flag === false) {
sessionStorage.removeItem(DEBUG);
} else {
sessionStorage.setItem(DEBUG, true);
}
};
var MqttClient = /*#__PURE__*/function (_Event) {
_inherits(MqttClient, _Event);
var _super = _createSuper(MqttClient);
function MqttClient() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, MqttClient);
_this = _super.call(this);
_this.connected = false;
_this.url = options.url;
_this.username = options.username;
_this.password = options.password;
_this.reconnectPeriod = 1000; // 1s自动重连
if (!_this.url || !_this.username || !_this.password) {
throw new Error('Signalling service initialization failed.');
}
_this.client = null;
// 未发送的消息
_this.unsent = [];
return _this;
}
_createClass(MqttClient, [{
key: "open",
value: function open() {
var _this2 = this;
this.unsent = [];
var url = this.url,
username = this.username,
password = this.password,
reconnectPeriod = this.reconnectPeriod;
var client = this.client = mqtt_minExports.connect(url, {
username: username,
password: password,
reconnectPeriod: reconnectPeriod,
clientId: 'duixmqttjs_' + Math.random().toString(16).slice(2, 8),
properties: {
sessionExpiryInterval: 10 * 1000
}
});
client.on('connect', function () {
logger$2.info('Mqtt client connect');
_this2.connected = true;
_this2.emit('connect');
if (_this2.unsent.length > 0) {
_this2.unsent.forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
topic = _ref2[0],
message = _ref2[1];
_this2.publish(topic, message);
});
_this2.unsent = [];
}
});
client.on('message', function (topic, message) {
if (sessionStorage.getItem(DEBUG)) {
logger$2.info('Receive message', topic, message.toString());
}
_this2.emit('message', topic, message.toString());
});
client.on('reconnect', function () {
logger$2.info('Client reconnect');
});
client.on('close', function () {
logger$2.info('Client close');
_this2.connected = false;
});
client.on('disconnect', function () {
logger$2.info('Client disconnect');
_this2.connected = false;
});
client.on('offline', function () {
logger$2.info('Client offline');
_this2.connected = false;
});
client.on('error', function () {
logger$2.info('Client error');
_this2.connected = false;
});
client.on('end', function () {
logger$2.info('Client end');
_this2.connected = false;
});
}
}, {
key: "close",
value: function close() {
var _this$client;
(_this$client = this.client) === null || _this$client === void 0 ? void 0 : _this$client.end();
this.unsent = [];
}
// 订阅topic
}, {
key: "subscribe",
value: function subscribe(topic) {
var _this3 = this;
return new Promise(function (resolve) {
if (!_this3.isConnected()) {
resolve(false);
}
_this3.client.subscribe(topic, {
qos: 2
}, function (error) {
if (error) {
logger$2.error("Subscribe ".concat(topic, " error"));
resolve(false);
return;
}
logger$2.info("Subscribe ".concat(topic, " success"));
resolve(true);
});
});
}
// 取消订阅
}, {
key: "unsubscribe",
value: function unsubscribe(topic) {
var _this4 = this;
return new Promise(function (resolve) {
var _this4$client;
(_this4$client = _this4.client) === null || _this4$client === void 0 ? void 0 : _this4$client.unsubscribe(topic, {
qos: 2
}, function (error) {
if (error) {
logger$2.warn("Unsubscribe ".concat(topic, " error"));
resolve(false);
return;
}
logger$2.info("Unsubscribe ".concat(topic, " success"));
resolve(true);
});
});
}
// 发布消息
}, {
key: "publish",
value: function publish(topic, message) {
if (this.isInit() && !this.isConnected()) {
this.unsent.push([topic, message]);
return;
}
if (sessionStorage.getItem(DEBUG)) {
logger$2.info('publish message', topic, message.toString());
}
this.client.publish(topic, message, {
qos: 2
});
}
}, {
key: "isInit",
value: function isInit() {
return !!this.client;
}
}, {
key: "isConnected",
value: function isConnected() {
return this.isInit() && this.connected;
}
}, {
key: "destroy",
value: function destroy() {
this.close();
this.connected = false;
this.url = '';
this.username = '';
this.password = '';
this.client = null;
this.unsent = [];
_get(_getPrototypeOf(MqttClient.prototype), "destroy", this).call(this);
}
}]);
return MqttClient;
}(Event$1);
var responseMap = {};
function response(id, complete) {
responseMap[id] = complete;
}
// 对服务端返回的消息进行处理,抛出业务层需要的数据,简化结构
function process$1(message) {
var messageObj = JSON.parse(message);
var id = messageObj.id,
method = messageObj.method,
params = messageObj.params;
var responseFn = responseMap[id];
if (responseFn) {
responseFn({
id: id,
result: messageObj.result,
error: messageObj.error
});
delete responseMap[id];
return null;
}
var state = params === null || params === void 0 ? void 0 : params.state;
if (state === 'asrData') {
return {
event: AgoraRtc.EventType.ASRDATA,
params: params
};
} else if (state === 'asrStop') {
return {
event: AgoraRtc.EventType.ASRSTOP,
params: params
};
} else if (state === 'asrStart') {
return {
event: AgoraRtc.EventType.ASRSTART,
params: params
};
} else if (state === 'speakStart') {
return {
event: AgoraRtc.EventType.SPEAKSTART,
params: params
};
} else if (state === 'speakStop') {
return {
event: AgoraRtc.EventType.SPEAKSTOP,
params: params
};
} else if (state === 'speakText') {
return {
event: AgoraRtc.EventType.SPEAKSECTION,
params: params
};
} else if (state === 'ttsSpeakStart') {
return {
event: AgoraRtc.EventType.TTSSPEAKSTART,
params: params
};
} else if (state === 'ttsSpeakStop') {
return {
event: AgoraRtc.EventType.TTSSPEAKSTOP,
params: params
};
} else if (state === 'ttsSpeakText') {
return {
event: AgoraRtc.EventType.TTSSPEAKSECTION,
params: params
};
}
if (method === 'HeartBeat') {
return {
event: method,
id: messageObj.id
};
}
if (method === 'SessionSdp') {
return {
event: method,
sdp: params.sdp
};
}
if (method === 'SessionCandidate') {
return {
event: method,
candidate: params.candidate
};
}
if (method === 'SessionState') {
var _state = params.state;
if (_state === 'Loading') {
var _params$detail;
return {
event: 'Loading',
progress: params === null || params === void 0 || (_params$detail = params.detail) === null || _params$detail === void 0 ? void 0 : _params$detail.progress
};
}
if (_state === 'Show') {
return {
event: 'Show'
};
}
if (_state === 'Destroy') {
return {
event: 'Destroy',
cause: params === null || params === void 0 ? void 0 : params.cause,
code: params.code
};
}
if (_state === 'AiFaceError') {
return {
event: 'AiFaceError',
code: params.code,
cause: params.cause
};
}
if (_state === 'playStart') {
if (params.type === 'dthuman') {
return {
event: 'SpeakStart',
audio: params === null || params === void 0 ? void 0 : params.wav,
content: params === null || params === void 0 ? void 0 : params.content
};
}
}
if (_state === 'playStop') {
if (params.type === 'dthuman') {
return {
event: 'SpeakStop',
audio: params === null || params === void 0 ? void 0 : params.wav,
content: params === null || params === void 0 ? void 0 : params.content
};
}
}
if (_state === 'playException') {
if (params.type === 'dthuman') {
return {
event: 'SpeakError',
cause: params === null || params === void 0 ? void 0 : params.cause,
audio: params === null || params === void 0 ? void 0 : params.wav,
content: params === null || params === void 0 ? void 0 : params.content
};
}
}
if (_state === 'AsrClose') {
return {
event: _state
};
}
if (_state === 'AsrOpen') {
return {
event: _state
};
}
if (_state === 'asrStart') {
return {
event: _state
};
}
if (_state === 'asrStop') {
return {
event: _state
};
}
if (_state === 'asrData') {
return {
event: _state,
text: params.text
};
}
if (_state === 'speakStart') {
return {
event: _state
};
}
if (_state === 'speakStop') {
return {
event: _state
};
}
if (_state === 'ttsSpeakStart') {
return {
event: _state
};
}
if (_state === 'ttsSpeakStop') {
return {
event: _state
};
}
}
if (method === 'SessionASR') {
if (params.asr) {
var _params$asr;
return {
event: 'AsrResult',
txt: (_params$asr = params.asr) === null || _params$asr === void 0 ? void 0 : _params$asr.txt
};
}
}
return null;
}
var MessageFactory = {
process: process$1,
response: response
};
var RESOURCE = {
rtmp: {
resOptions: {
name: 'rtmp',
type: 'rtmp'
},
type: 'center'
},
rtc: {
resOptions: {
enableTrickleIce: true,
timeToConnected: 10000,
timeToReconnected: 25000,
// rtc重连时间25秒未重连上触发destroy)
vpxMaxBitrate: 3000,
//最大码率
vpxMinBitrate: 500,
// 最小码率
dataChannelName: "webChannel",
type: 'rtc'
},
type: 'center'
},
agora: function agora(_ref) {
var remoteToken = _ref.remoteToken,
channelId = _ref.channelId,
remoteUid = _ref.remoteUid,
localUid = _ref.localUid;
return {
resOptions: {
type: "agora",
name: 'agora',
token: remoteToken,
channelId: channelId,
userId: remoteUid,
remoteId: localUid
},
type: "center"
};
},
background: function background(_background, video) {
// 背景资源
var url = _background === null || _background === void 0 ? void 0 : _background.url;
var isImage = /\.(jpeg|jpg|gif|png)$/i.test(url);
return {
resOptions: {
type: isImage ? 'image' : 'video',
url: url
},
drawOptions: {
// TODO 如果背景图片比例不一致,是否需要缩放
height: video.height,
width: video.width,
x: 0,
y: 0
},
type: 'back'
};
},
human: function human(data) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// 数字人资源
var width = data.width,
height = data.height,
x = data.x,
y = data.y,
sequence = data.sequence,
udCode = data.udCode,
matting = data.matting,
actionAreaList = data.actionAreaList,
silenceAreaList = data.silenceAreaList,
action_mode = data.action_mode,
actionJson = data.actionJson;
var param = {
resOptions: {
audioDriven: {
mode: 'livestream',
// 'interactstream',
quarter: 0,
templates: [{
matting: matting,
sequence: sequence,
udCode: udCode,
actionAreaList: action_mode ? [] : actionAreaList,
silenceAreaList: action_mode ? [] : silenceAreaList,
actionJson: action_mode && actionJson
}],
enableNotInferenceWhenSlienceAudio: options.enableNotInferenceWhenSlienceAudio
},
type: 'dthuman',
name: 'dthuman'
},
drawOptions: {
width: width,
height: height,
x: x,
y: y
},
type: 'center'
};
if (options.useActSection && actionAreaList.length > 0) {
param.resOptions.audioDriven.bodyPlayMode = 'smoothstandard';
}
return param;
},
localdigit: function localdigit(data) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// 本地数字人资源
var width = data.width,
height = data.height,
x = data.x,
y = data.y,
udCode = data.udCode,
matting = data.matting,
actionAreaList = data.actionAreaList,
silenceAreaList = data.silenceAreaList,
action_mode = data.action_mode,
actionJson = data.actionJson;
var param = {
resOptions: {
type: options.isTextModel ? 'localdigitex' : 'localdigit',
name: options.isTextModel ? 'localdigitex' : 'localdigit',
udCode: udCode,
matting: matting
},
drawOptions: {
width: width,
height: height,
x: x,
y: y
},
type: 'center'
};
if (options.useActSection && actionAreaList.length > 0) {
param.resOptions.bodyPlayMode = 'adaptive';
param.resOptions.actionAreaList = actionAreaList;
param.resOptions.silenceAreaList = silenceAreaList;
}
if (action_mode) {
param.resOptions.actionJson = actionJson;
}
return param;
}
};
function newSession(_ref2, info, agoraInfo) {
var transparent = _ref2.transparent,
enableRec = _ref2.enableRec,
human = _ref2.human,
background = _ref2.background,
video = _ref2.video,
useActSection = _ref2.useActSection,
useVideoAgent = _ref2.useVideoAgent,
useAudioAgent = _ref2.useAudioAgent,
useAgora = _ref2.useAgora;
var resList = [];
var rule = '';
if (useAgora && agoraInfo) {
resList.push(RESOURCE.agora(agoraInfo));
if (useAudioAgent) {
rule = 'LiveKitAgentWithAgoraAudio';
resList.push({
"resOptions": {
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
} else {
if (info.detailDto.imgSize == '168') {
// default 是文本模型
if (info.talktype === 'default') {
rule = useVideoAgent ? 'LocalDigitExWithVideoLiveKitAgentAgora' : 'LocalDigitExWithLiveKitAgentAgora';
} else {
rule = useVideoAgent ? 'LocalDigitWithVideoLiveKitAgentAgora' : 'LocalDigitWithLiveKitAgentAgora';
}
resList.push(RESOURCE.localdigit(human, {
useActSection: useActSection,
isTextModel: info.talktype === 'default'
}), {
"resOptions": {
"detectVoiceFeatures": info.talktype === 'default' ? true : false,
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
} else {
rule = useVideoAgent ? 'DTHumanLivestreamWithVideoLiveKitAgent' : 'DTHumanLivestreamWithLiveKitAgent';
resList.push(RESOURCE.human(human, {
useActSection: useActSection,
enableNotInferenceWhenSlienceAudio: true
}), {
"resOptions": {
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
}
}
} else {
resList.push(RESOURCE.rtc);
if (useAudioAgent) {
rule = 'LiveKitAgentWithRTCAudio';
resList.push({
"resOptions": {
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
} else {
if (info.detailDto.imgSize == '168') {
// LocalDigitExWithLiveKitAgent 168数字人(新模式) + livekitagent + webrtc (上行语音)
// LocalDigitExWithVideoLiveKitAgent 168数字人(新模式) + livekitagent + webrtc (上行语音+视频)
// LocalDigitExWithLiveKitAgentAgora 168数字人(新模式) + livekitagent + 声网rtc (上行语音)
// LocalDigitExWithVideoLiveKitAgentAgora 168数字人(新模式) + livekitagent + 声网rtc (上行语音+视频)
if (info.talktype === 'default') {
rule = useVideoAgent ? 'LocalDigitExWithVideoLiveKitAgent' : 'LocalDigitExWithLiveKitAgent';
} else {
rule = useVideoAgent ? 'LocalDigitWithVideoLiveKitAgent' : 'LocalDigitWithLiveKitAgent';
}
resList.push(RESOURCE.localdigit(human, {
useActSection: useActSection,
isTextModel: info.talktype === 'default'
}), {
"resOptions": {
"detectVoiceFeatures": info.talktype === 'default' ? true : false,
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
} else {
rule = useVideoAgent ? 'DTHumanLivestreamWithVideoLiveKitAgent' : 'DTHumanLivestreamWithLiveKitAgent';
resList.push(RESOURCE.human(human, {
useActSection: useActSection,
enableNotInferenceWhenSlienceAudio: true
}), {
"resOptions": {
"type": "livekitagent",
"name": "livekitagent",
"ext": info
},
"type": "center"
});
}
}
}
if (background !== null && background !== void 0 && background.url) {
resList.push(RESOURCE.background(background, video));
}
return {
rule: rule,
// 'DTHumanInteract',
mode: useAgora ? "checkheartbeat" : undefined,
// 混屏模式 greenmatting绿幕图 maskmatting掩码图 normal正常该值可选默认是normal
mixMode: transparent ? 'maskmatting' : 'normal',
videoSize: {
width: useAudioAgent ? 1 : video.width,
height: useAudioAgent ? 1 : video.height
},
// 是否开启录屏
enableRec: !!enableRec,
recMode: {
type: 'A1A2',
uplinkSize: {
width: video.width,
height: video.height
}
},
recRule: useAgora ? 'RecAgora' : 'RecAiFaceInteract',
// 'RecAiFaceInteract',
// 资源list
resList: resList
};
}
var ResourceFactory = {
newSession: newSession
};
var logger$1 = new Logger('openap');
function getSign(_x3, _x4) {
return _getSign.apply(this, arguments);
}
// export async function createSession(sig, domain) {
// const res = await Ajax.get(API.createSession.replace('{DOMAIN}', domain), { sig })
// if (res.success) {
// return res.data
// }
// return null
// }
// 查询会话详情
function _getSign() {
_getSign = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(parmas, domain) {
var res;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return http.post("".concat(API.getSign.replace('{DOMAIN}', domain)), parmas);
case 2:
res = _context2.sent;
if (!res.success) {
_context2.next = 5;
break;
}
return _context2.abrupt("return", res.data);
case 5:
return _context2.abrupt("return", null);
case 6:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return _getSign.apply(this, arguments);
}
function getByQuestion(_x9, _x10) {
return _getByQuestion.apply(this, arguments);
}
// 获取答案流式接口
function _getByQuestion() {
_getByQuestion = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(param, domain) {
var _res$data12, _res$data13, _res$data14, url, res;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
domain = domain || DefaultConfig.domain;
url = API.getByQuestion.replace('{DOMAIN}', domain);
_context5.next = 5;
return http.post(url, param);
case 5:
res = _context5.sent;
if (!(!res.success || !(res !== null && res !== void 0 && (_res$data12 = res.data) !== null && _res$data12 !== void 0 && _res$data12.answer))) {
_context5.next = 8;
break;
}
return _context5.abrupt("return", null);
case 8:
return _context5.abrupt("return", {
answer: res === null || res === void 0 || (_res$data13 = res.data) === null || _res$data13 === void 0 ? void 0 : _res$data13.answer,
audio: res === null || res === void 0 || (_res$data14 = res.data) === null || _res$data14 === void 0 ? void 0 : _res$data14.filePath
});
case 11:
_context5.prev = 11;
_context5.t0 = _context5["catch"](0);
return _context5.abrupt("return", null);
case 14:
case "end":
return _context5.stop();
}
}, _callee5, null, [[0, 11]]);
}));
return _getByQuestion.apply(this, arguments);
}
function saveEventTime(_x11, _x12) {
return _saveEventTime.apply(this, arguments);
}
function _saveEventTime() {
_saveEventTime = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(param, domain) {
var url, res;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
domain = domain || DefaultConfig.domain;
url = API.saveEventTime.replace('{DOMAIN}', domain);
_context7.next = 5;
return http.post(url, param);
case 5:
res = _context7.sent;
if (res.success) {
_context7.next = 8;
break;
}
return _context7.abrupt("return", null);
case 8:
return _context7.abrupt("return", true);
case 11:
_context7.prev = 11;
_context7.t0 = _context7["catch"](0);
return _context7.abrupt("return", null);
case 14:
case "end":
return _context7.stop();
}
}, _callee7, null, [[0, 11]]);
}));
return _saveEventTime.apply(this, arguments);
}
function createSession(_x13, _x14) {
return _createSession.apply(this, arguments);
}
function _createSession() {
_createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(param, domain) {
var url, res, _res$data15, _ttsConfig$customTTSR5, _ttsConfig$customTTSR6, _ttsConfig$customTTSR7, _ttsConfig$customTTSR8, conversationMaterial, humanConfig, actionAreaList, silenceAreaList, actionJson, action_mode, markContent, markObj, human, background, video, language, asr, asrService, ttsConfig, customTTSReq;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
url = API.createSession.replace('{DOMAIN}', domain);
_context8.next = 3;
return http.get(url, param);
case 3:
res = _context8.sent;
if (!res.success) {
_context8.next = 21;
break;
}
conversationMaterial = res === null || res === void 0 || (_res$data15 = res.data) === null || _res$data15 === void 0 ? void 0 : _res$data15.conversationMaterial;
humanConfig = conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.humanConfig; // 动作区间
actionAreaList = [], silenceAreaList = [], actionJson = [], action_mode = null;
try {
markContent = conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.markContent;
if (markContent) {
markObj = JSON.parse(markContent);
actionAreaList = ((markObj === null || markObj === void 0 ? void 0 : markObj.action_region) || []).map(function (arr) {
return {
start: arr[0],
end: arr[1]
};
});
silenceAreaList = ((markObj === null || markObj === void 0 ? void 0 : markObj.silence_region) || []).map(function (arr) {
return {
start: arr[0],
end: arr[1]
};
});
action_mode = markObj === null || markObj === void 0 ? void 0 : markObj.action_mode;
actionJson = markContent && JSON.parse(markContent);
}
} catch (e) {
logger$1.warn('Parse markcontent error', conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.markContent);
}
human = {
x: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.human_x,
y: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.human_y,
width: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.human_width,
height: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.human_height,
sequence: (conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.templateVideoList) || [],
udCode: conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.modelSceneId,
matting: conversationMaterial !== null && conversationMaterial !== void 0 && conversationMaterial.sceneType ? 0 : 1,
actionAreaList: actionAreaList,
silenceAreaList: silenceAreaList,
action_mode: action_mode,
actionJson: actionJson
};
background = {
url: conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.backgroundUrl
};
video = {
width: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.video_width,
height: humanConfig === null || humanConfig === void 0 ? void 0 : humanConfig.video_height
};
language = (conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.language) || 'zh';
asr = conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.asr;
asrService = conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.asrService;
ttsConfig = (conversationMaterial === null || conversationMaterial === void 0 ? void 0 : conversationMaterial.ttsConfig) || {};
customTTSReq = {
pitch: (ttsConfig === null || ttsConfig === void 0 || (_ttsConfig$customTTSR5 = ttsConfig.customTTSReq) === null || _ttsConfig$customTTSR5 === void 0 ? void 0 : _ttsConfig$customTTSR5.pitch) || 0,
speaker: ttsConfig === null || ttsConfig === void 0 || (_ttsConfig$customTTSR6 = ttsConfig.customTTSReq) === null || _ttsConfig$customTTSR6 === void 0 ? void 0 : _ttsConfig$customTTSR6.ttsSpeaker,
speechRate: (ttsConfig === null || ttsConfig === void 0 || (_ttsConfig$customTTSR7 = ttsConfig.customTTSReq) === null || _ttsConfig$customTTSR7 === void 0 ? void 0 : _ttsConfig$customTTSR7.speedRate) || 0,
ttsResource: ttsConfig === null || ttsConfig === void 0 ? void 0 : ttsConfig.engineTypeCode,
volume: (ttsConfig === null || ttsConfig === void 0 || (_ttsConfig$customTTSR8 = ttsConfig.customTTSReq) === null || _ttsConfig$customTTSR8 === void 0 ? void 0 : _ttsConfig$customTTSR8.volume) || 0
};
res.data.conversationMaterial = {
human: human,
background: background,
video: video,
language: language,
asr: asr,
asrService: asrService,
customTTSReq: customTTSReq
};
return _context8.abrupt("return", res.data);
case 21:
return _context8.abrupt("return", {
error: true,
code: res.code,
message: res.message || res.msg
});
case 22:
case "end":
return _context8.stop();
}
}, _callee8);
}));
return _createSession.apply(this, arguments);
}
var workletUrl = "data:application/javascript;base64,Y2xhc3MgUmVjb3JkZXJXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsNCiAgY29uc3RydWN0b3IoKSB7DQogICAgc3VwZXIoKQ0KICAgIHRoaXMuaXNSZWNvcmRpbmcgPSBmYWxzZQ0KICAgIHRoaXMuYnVmZmVyU2l6ZSA9IDEwMjQgLy8g57yT5Yay5Yy65aSn5bCPDQogICAgdGhpcy5idWZmZXIgPSBuZXcgRmxvYXQzMkFycmF5KHRoaXMuYnVmZmVyU2l6ZSkNCiAgICB0aGlzLmJ1ZmZlckluZGV4ID0gMA0KICAgIHRoaXMuc2FtcGxlUmF0ZSA9IDE2MDAwDQoNCiAgICAvLyDmt7vliqDmtojmga/lpITnkIYNCiAgICB0aGlzLnBvcnQub25tZXNzYWdlID0gKGV2ZW50KSA9PiB7DQogICAgICBpZiAoZXZlbnQuZGF0YS5jb21tYW5kID09PSAnc3RhcnQnKSB7DQogICAgICAgIHRoaXMuaXNSZWNvcmRpbmcgPSB0cnVlDQogICAgICAgIHRoaXMuYnVmZmVySW5kZXggPSAwDQogICAgICB9IGVsc2UgaWYgKGV2ZW50LmRhdGEuY29tbWFuZCA9PT0gJ3N0b3AnKSB7DQogICAgICAgIHRoaXMuaXNSZWNvcmRpbmcgPSBmYWxzZQ0KICAgICAgfQ0KICAgIH0NCiAgfQ0KDQogIHByb2Nlc3MoaW5wdXRzKSB7DQogICAgaWYgKCF0aGlzLmlzUmVjb3JkaW5nKSByZXR1cm4gdHJ1ZQ0KDQogICAgY29uc3QgaW5wdXQgPSBpbnB1dHNbMF0NCiAgICBpZiAoaW5wdXQgJiYgaW5wdXQubGVuZ3RoID4gMCkgew0KICAgICAgY29uc3QgaW5wdXREYXRhID0gaW5wdXRbMF0NCg0KICAgICAgLy8g56Gu5L+d6YeH5qC3546H5q2j56GuDQogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGlucHV0RGF0YS5sZW5ndGg7IGkrKykgew0KICAgICAgICAvLyDlr7novpPlhaXmlbDmja7ov5vooYzlop7nm4rmjqfliLYNCiAgICAgICAgY29uc3Qgc2FtcGxlID0gTWF0aC5tYXgoLTEsIE1hdGgubWluKDEsIGlucHV0RGF0YVtpXSAqIDEuNSkpIC8vIOmAguW9k+WinuWKoOWinuebig0KICAgICAgICB0aGlzLmJ1ZmZlclt0aGlzLmJ1ZmZlckluZGV4KytdID0gc2FtcGxlDQoNCiAgICAgICAgaWYgKHRoaXMuYnVmZmVySW5kZXggPj0gdGhpcy5idWZmZXJTaXplKSB7DQogICAgICAgICAgY29uc3QgcGNtRGF0YSA9IHRoaXMuZmxvYXRUbzE2Qml0UENNKHRoaXMuYnVmZmVyKQ0KICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShwY21EYXRhLCBbcGNtRGF0YS5idWZmZXJdKQ0KICAgICAgICAgIHRoaXMuYnVmZmVyID0gbmV3IEZsb2F0MzJBcnJheSh0aGlzLmJ1ZmZlclNpemUpDQogICAgICAgICAgdGhpcy5idWZmZXJJbmRleCA9IDANCiAgICAgICAgfQ0KICAgICAgfQ0KICAgIH0NCiAgICByZXR1cm4gdHJ1ZQ0KICB9DQoNCiAgZmxvYXRUbzE2Qml0UENNKGZsb2F0MzJBcnJheSkgew0KICAgIGNvbnN0IHBjbURhdGEgPSBuZXcgSW50MTZBcnJheShmbG9hdDMyQXJyYXkubGVuZ3RoKQ0KICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZmxvYXQzMkFycmF5Lmxlbmd0aDsgaSsrKSB7DQogICAgICAvLyDlop7liqDkuIDkupvlop7nm4rlubbnoa7kv53kuI3lpLHnnJ8NCiAgICAgIGNvbnN0IHMgPSBNYXRoLm1heCgtMSwgTWF0aC5taW4oMSwgZmxvYXQzMkFycmF5W2ldICogMS41KSkNCiAgICAgIC8vIOS9v+eUqOabtOeyvuehrueahOi9rOaNog0KICAgICAgcGNtRGF0YVtpXSA9IE1hdGgucm91bmQocyA8IDAgPyBzICogMHg4MDAwIDogcyAqIDB4N2ZmZikNCiAgICB9DQogICAgcmV0dXJuIHBjbURhdGENCiAgfQ0KfQ0KDQpyZWdpc3RlclByb2Nlc3NvcigncmVjb3JkZXItd29ya2xldCcsIFJlY29yZGVyV29ya2xldCkNCg==";
var _default = /*#__PURE__*/function () {
function _default() {
_classCallCheck(this, _default);
this.ws = null;
this.isConnected = false;
this.onResult = null;
this.id = 0;
this.startReqId = 0;
this.stopReqId = 0;
this.status = ''; // 1启动中 2已启动 3关闭中 4已关闭
}
_createClass(_default, [{
key: "connect",
value: function () {
var _connect = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, data) {
var _this = this;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (!(this.status == 3)) {
_context.next = 2;
break;
}
throw new Error('Asr is being shut down. Do not operate frequently');
case 2:
if (!(this.ws || this.status == 1 || this.status == 2)) {
_context.next = 4;
break;
}
throw new Error('ASR is being started or has been started');
case 4:
this.status = 1;
try {
this.ws = new WebSocket(url);
this.ws.onopen = function () {
_this.isConnected = true;
_this.ws.send(JSON.stringify(_objectSpread2({
check: true
}, data)));
};
this.ws.onmessage = function (event) {
_this.handleMessage(JSON.parse(event.data));
};
this.ws.onclose = function () {
_this.isConnected = false;
};
this.ws.onerror = function (error) {
console.error("WebSocket error:", error);
_this.isConnected = false;
};
} catch (error) {
console.error("Connection error:", error);
this.close();
}
case 6:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function connect(_x, _x2) {
return _connect.apply(this, arguments);
}
return connect;
}()
}, {
key: "start",
value: function start() {
if (!this.isConnected || !this.ws) {
return;
}
this.startReqId = ++this.id;
var startMessage = {
id: this.startReqId,
eventType: "start"
};
this.ws.send(JSON.stringify(startMessage));
}
}, {
key: "stop",
value: function stop() {
var _this2 = this;
if (!this.isConnected || !this.ws) {
this.status = 4;
return;
}
this.status = 3;
this.stopReqId = ++this.id;
var stopMessage = {
id: this.stopReqId,
eventType: "stop"
};
this.ws.send(JSON.stringify(stopMessage));
this.stopTimer = setTimeout(function () {
_this2.close();
_this2.onStop && _this2.onStop();
}, 1000);
}
}, {
key: "sendAudioData",
value: function sendAudioData(data) {
var _this$ws;
if (this.isConnected && ((_this$ws = this.ws) === null || _this$ws === void 0 ? void 0 : _this$ws.readyState) === WebSocket.OPEN && this.status == 2) {
try {
this.ws.send(data.buffer);
} catch (error) {
console.error("Error sending audio data:", error);
}
}
}
}, {
key: "handleMessage",
value: function handleMessage(message) {
var msgType = message.msgType,
eventType = message.eventType,
result = message.result;
// response
if (msgType == "resp") {
if (eventType == "conn" && result) {
this.start();
} else if (eventType == "start" && result) {
this.status = 2;
this.onStart && this.onStart();
} else if (eventType == 'stop' && result) {
clearTimeout(this.stopTimer);
this.close();
this.onStop && this.onStop();
}
return;
}
// 事件
switch (message.SentenceType) {
case "SentenceResultChange":
this.onSentenceResultChange && this.onSentenceResultChange(message.text);
break;
case "SentenceEnd":
this.onSentenceEnd && this.onSentenceEnd(message.text);
break;
}
}
}, {
key: "close",
value: function close() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
this.status = 4;
this.isConnected = false;
}
}]);
return _default;
}();
var audioContext,
mediaStream,
workletNode = null,
source = null;
var speechService = new _default();
var tmpText = [""];
function start(_x) {
return _start.apply(this, arguments);
}
function _start() {
_start = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
var headers;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
tmpText = [""];
if (audioContext) {
_context.next = 12;
break;
}
audioContext = new AudioContext({
sampleRate: 16000
});
_context.next = 5;
return audioContext.audioWorklet.addModule(workletUrl);
case 5:
_context.next = 7;
return navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 16000,
channelCount: 1,
echoCancellation: true,
autoGainControl: true,
noiseSuppression: true
}
});
case 7:
mediaStream = _context.sent;
source = audioContext.createMediaStreamSource(mediaStream);
workletNode = new AudioWorkletNode(audioContext, "recorder-worklet", {
numberOfInputs: 1,
numberOfOutputs: 1,
channelCount: 1,
processorOptions: {
sampleRate: 16000
}
});
source.connect(workletNode);
workletNode.connect(audioContext.destination);
case 12:
workletNode.port.onmessage = function (e) {
speechService.sendAudioData(e.data);
};
workletNode.port.postMessage({
command: "start"
});
headers = {
uuid: options.uuid,
auth: options.auth,
endpoint: options.endpoint
};
_context.next = 17;
return speechService.connect(options.url, headers);
case 17:
speechService.onStart = function () {
options.onStart && options.onStart();
};
speechService.onSentenceResultChange = function (result) {
tmpText[tmpText.length - 1] = result;
options.onSentenceResultChange && options.onSentenceResultChange({
content: result,
textList: tmpText.filter(function (item) {
return !!item;
})
});
};
speechService.onSentenceEnd = function (result) {
tmpText[tmpText.length - 1] = result;
options.onSentenceEnd && options.onSentenceEnd({
content: result,
textList: tmpText.filter(function (item) {
return !!item;
})
});
tmpText.push("");
};
speechService.onStop = function () {
options.onStop && options.onStop();
};
return _context.abrupt("return", {
stream: mediaStream
});
case 22:
case "end":
return _context.stop();
}
}, _callee);
}));
return _start.apply(this, arguments);
}
function stop() {
return _stop.apply(this, arguments);
}
function _stop() {
_stop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
if (workletNode) {
speechService.stop();
workletNode.port.postMessage({
command: "stop"
});
}
case 1:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return _stop.apply(this, arguments);
}
function destroy() {
return _destroy.apply(this, arguments);
}
function _destroy() {
_destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
// 清理资源
if (workletNode) {
workletNode.disconnect();
workletNode = null;
}
if (mediaStream) {
mediaStream.getTracks().forEach(function (track) {
return track.stop();
});
mediaStream = null;
source = null;
}
if (!audioContext) {
_context3.next = 6;
break;
}
_context3.next = 5;
return audioContext.close();
case 5:
audioContext = null;
case 6:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return _destroy.apply(this, arguments);
}
var Recorder = {
start: start,
stop: stop,
destroy: destroy
};
function per (event) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var param = _objectSpread2(_objectSpread2({
time: formatDate(new Date()),
event: event
}, data), {}, {
sessionId: data.sessionId || this.sessionId,
appId: data.appId || this.appId
});
this.emit('log', param);
}
var analysisData = [],
sendData = [];
function analysis(data) {
var t = new Date().getTime();
analysisData.push(_objectSpread2({
time: t
}, data));
}
function reportAnalysis(domain) {
setTimeout(function () {
if (!sendData.length) {
sendData = analysisData;
analysisData = [];
}
if (!sendData.length) {
reportAnalysis(domain);
return;
}
saveEventTime(sendData, domain).then(function (ret) {
if (ret != null) {
sendData = [];
}
})["finally"](function () {
reportAnalysis(domain);
});
}, 2 * 1000);
}
var logger = new Logger("index");
var _reconnectRTC = /*#__PURE__*/new WeakSet();
var DUIX = /*#__PURE__*/function (_Event) {
_inherits(DUIX, _Event);
var _super = _createSuper(DUIX);
function DUIX() {
var _this;
_classCallCheck(this, DUIX);
_this = _super.call(this);
_classPrivateMethodInitSpec(_assertThisInitialized(_this), _reconnectRTC);
_this.sign = "";
_this.domain = DefaultConfig.domain;
_this.containerLable = "";
_this.conversationId = "";
_this.sessionId = "";
_this.token = "";
_this.appId = "";
_this.rtcConfig = null;
_this.mqttConfig = null;
_this.mqttTopic = null;
//
_this.asrService = "";
_this.asr = {};
_this.language = "zh"; // 当前会话语言
_this.vpxMaxBitrate = 0; // 最大码率
_this.initOpenAsr = false; //
_this.useActSection = false;
_this.terminal = "app";
_this.mediaMode = "web_rtc";
_this.interactMode = "live";
_this.website = window.location.origin;
_this.timer = null;
_this.recorder = null;
_this.id = 1;
_this.username = "";
// 信令服务
_this.socket = null;
_this.recordState = RecordState.CLOSED;
_this.asrState = AsrState.CLOSED;
_this.sessionState = SessionState.CLOSED;
_this.speakState = SpeakState.SLIENT;
_this.stopTimeout = null;
_this.isInit = false;
// rtc重连
_this.isRestartICE = false;
_this.restartICETimer = null;
// 合并接口后数据
_this.conversationInfo = null;
_this.materialInfo = null;
_this.sessionInfo = null;
_this.configInfo = null;
_this.agoraInfo = null;
// 视频多模态
_this.videoAgentContainer = null; // 容器
_this.useVideoAgent = false; // 是否启用
_this.isSupportVideoAgent = null;
// 文本语音聊天
_this.useAudioAgent = false;
// 是否使用声网模式
_this.useAgora = false;
clientUuid();
logger.info("Version ".concat("0.1.0", ". ", navigator.userAgent));
return _this;
}
_createClass(DUIX, [{
key: "init",
value: function () {
var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _window,
_this2 = this,
_this$conversationInf;
var options,
sign,
containerLable,
domain,
conversationId,
appId,
appKey,
website,
privateSign,
data,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
options = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
per.call(this, "init");
if (isSupport()) {
_context.next = 4;
break;
}
throw new Error("Current browsers do not support WebRTC");
case 4:
if (isSupportProtocol()) {
_context.next = 6;
break;
}
throw new Error("It must be used in an HTTPS environment");
case 6:
sign = options.sign, containerLable = options.containerLable, domain = options.domain, conversationId = options.conversationId, appId = options.appId, appKey = options.appKey, website = options.website;
if (!(!sign && !appId && !appKey)) {
_context.next = 9;
break;
}
throw new Error("Missing required parameters 'sign'.");
case 9:
if (options.conversationId) {
_context.next = 11;
break;
}
throw new Error("Missing required parameters 'conversationId'.");
case 11:
if (containerLable) {
_context.next = 13;
break;
}
throw new Error("Missing required parameters 'containerLable'.");
case 13:
if (!this.isInit) {
_context.next = 15;
break;
}
return _context.abrupt("return", {
err: "Duix is already init"
});
case 15:
if (website) {
this.website = website;
}
this.domain = domain || DefaultConfig.domain;
this.containerLable = containerLable;
this.conversationId = conversationId;
if (!(appId && appKey && !sign)) {
_context.next = 23;
break;
}
_context.next = 22;
return getSign({
appId: appId,
appKey: appKey
}, this.domain);
case 22:
privateSign = _context.sent;
case 23:
this.sign = sign || privateSign;
_context.next = 26;
return createSession({
sig: this.sign,
conversationId: this.conversationId
}, this.domain);
case 26:
data = _context.sent;
if (!data.error) {
_context.next = 31;
break;
}
logger.error("Duix.init failed. createSession failed");
this.triggerError("4005", {
code: data.code,
message: data.message
});
return _context.abrupt("return", {
err: "Signature verification failed",
code: data.code,
message: data.message
});
case 31:
logger.info("Duix.init succeeded.", data.appId);
this.conversationInfo = data.conversationDto;
this.materialInfo = data.conversationMaterial;
this.sessionInfo = data.sessionRsp;
this.configInfo = data.tokenVO;
this.agoraInfo = data.agoraDto;
this.token = this.configInfo.sig;
this.appId = this.configInfo.appId;
this.sessionId = this.sessionInfo.sessionId;
sessionStorage.setItem("_duix_token", this.token);
sessionStorage.setItem("_duix_appid", this.appId);
sessionStorage.setItem("_duix_sign", this.sign);
this.asrService = this.configInfo.asrService;
this.asr = this.configInfo.asr;
this.rtcConfig = this.configInfo.rtcConfig;
this.mqttConfig = this.configInfo.mqttConfig;
this.useAgora = this.conversationInfo.agoraEnable === 1;
this.initSocket();
this.webRtcInit();
(_window = window) === null || _window === void 0 ? void 0 : _window.addEventListener("beforeunload", function () {
logger.info("window.beforeunload");
_this2.stop();
});
this.isSupportVideoAgent = !!((_this$conversationInf = this.conversationInfo) !== null && _this$conversationInf !== void 0 && (_this$conversationInf = _this$conversationInf.modelDtoList) !== null && _this$conversationInf !== void 0 && (_this$conversationInf = _this$conversationInf[0]) !== null && _this$conversationInf !== void 0 && _this$conversationInf.multimodal);
this.isInit = true;
reportAnalysis(this.domain);
Logger.start({
domain: this.domain,
interval: 15000
});
return _context.abrupt("return", {});
case 56:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function init() {
return _init.apply(this, arguments);
}
return init;
}()
}, {
key: "destroy",
value: function destroy() {
logger.info("Duix.destroy");
this.isInit = false;
this.stop();
if (this.socket) {
this.socket.destroy();
}
_get(_getPrototypeOf(DUIX.prototype), "destroy", this).call(this);
}
}, {
key: "getLocalStream",
value: function getLocalStream() {
logger.info("Duix.getLocalStream");
return this.webRtc.localMediaStream;
}
}, {
key: "getRemoteStream",
value: function getRemoteStream() {
logger.info("Duix.getRemoteStream");
return this.webRtc.remoteStream;
}
}, {
key: "initSocket",
value: function initSocket() {
var _this$mqttConfig,
_this$mqttConfig2,
_this$mqttConfig3,
_this3 = this;
this.socket = new MqttClient({
url: 'wss://14.103.170.130/mqtt',
username: (_this$mqttConfig2 = this.mqttConfig) === null || _this$mqttConfig2 === void 0 ? void 0 : _this$mqttConfig2.userName,
password: (_this$mqttConfig3 = this.mqttConfig) === null || _this$mqttConfig3 === void 0 ? void 0 : _this$mqttConfig3.password
});
console.log('4564567547567',this.socket.url);
this.socket.on("message", function (topic, message) {
var _this3$mqttTopic;
var data = MessageFactory.process(message);
if (!data) return;
if (_this3.sessionState === SessionState.CLOSED) {
logger.warn("Session is closed.");
return;
}
var info = data.params;
var eventType = _this3.useAgora ? AgoraRtc.EventType : WebRtc.EventType;
switch (data.event) {
case eventType.ASRSTART:
if (_this3.useAgora) {
_this3.emit("asrStart");
}
break;
case eventType.ASRSTOP:
if (_this3.useAgora) {
_this3.emit("asrStop", {
content: info.text
});
}
break;
case eventType.ASRDATA:
if (_this3.useAgora) {
_this3.emit("asrData", {
content: info.text
});
}
break;
case eventType.SPEAKSTART:
if (_this3.useAgora) {
per.call(_this3, "playStart");
analysis({
event: "CLIENT_RECEIVE_PLAY_START",
message: info.audio || info.content,
sessionId: _this3.sessionId
});
_this3.emit("speakStart", info);
_this3.speakState = SpeakState.SPEAKING;
logger.info("SpeakStart", info);
}
break;
case eventType.SPEAKSTOP:
if (_this3.useAgora) {
per.call(_this3, "speakEnd");
_this3.emit("speakEnd", info);
_this3.speakState = SpeakState.SLIENT;
logger.info("SpeakStop", info);
}
break;
case eventType.SPEAKSECTION:
if (_this3.useAgora) {
per.call(_this3, "speakSection");
_this3.emit("speakSection", info);
logger.info("speakSection", info);
}
break;
case eventType.TTSSPEAKSTART:
if (_this3.useAgora) {
_this3.emit("ttsSpeakStart", info);
logger.info("ttsSpeakStart", info);
}
break;
case eventType.TTSSPEAKSTOP:
if (_this3.useAgora) {
_this3.emit("ttsSpeakEnd", info);
logger.info("ttsSpeakEnd", info);
}
break;
case eventType.TTSSPEAKSECTION:
if (_this3.useAgora) {
_this3.emit("ttsSpeakSection", info);
logger.info("ttsSpeakSection", info);
}
break;
case "AiFaceError":
break;
case "Destroy":
clearTimeout(_this3.stopTimeout);
if (_this3.sessionState !== SessionState.CLOSING) {
_this3.triggerError("4007", {
code: data === null || data === void 0 ? void 0 : data.code,
cause: data === null || data === void 0 ? void 0 : data.cause
});
}
_this3.destroySession();
break;
case "SessionSdp":
_this3.webRtc.setRemoteDescription(data.sdp, _this3.isRestartICE);
break;
case "SessionCandidate":
_this3.webRtc.addIceCandidate(data.candidate);
break;
case "Loading":
logger.info("Trigger progress", data.progress);
_this3.emit("progress", data.progress);
break;
case "Show":
logger.info("Aiface show");
// this.webRtc?.playRemoteStream()
break;
case "HeartBeat":
var msg = {
sender: clientUuid(),
id: data.id,
sessionId: _this3.sessionId,
result: {
sessionId: _this3.sessionId,
message: "Heartbeat received."
}
};
console.info("replay Heartbeat", msg);
_this3.socket.publish((_this3$mqttTopic = _this3.mqttTopic) === null || _this3$mqttTopic === void 0 ? void 0 : _this3$mqttTopic.topicPub, JSON.stringify(msg));
break;
}
});
this.socket.once("connect", function () {
per.call(_this3, "initSuccess");
_this3.emit("intialSucccess");
});
this.socket.open();
}
}, {
key: "webRtcInit",
value: function webRtcInit() {
var _this4 = this;
this.webRtc = this.useAgora ? new AgoraRtc({
containerLable: this.containerLable
}) : new WebRtc({
containerLable: this.containerLable
});
var eventType = this.useAgora ? AgoraRtc.EventType : WebRtc.EventType;
// 以RTC的show事件为准作为数字人显示的时机
this.webRtc.on(eventType.SHOW, function () {
if (_this4.sessionState !== SessionState.CLOSED) {
per.call(_this4, "show");
logger.info("Trigger show");
_this4.sessionState = SessionState.CONNECTED;
_this4.emit("show");
}
});
// ASR
this.webRtc.on(eventType.ASRSTART, function () {
_this4.emit("asrStart");
});
this.webRtc.on(eventType.ASRSTOP, function (info) {
_this4.emit("asrStop", {
content: info.text
});
});
this.webRtc.on(eventType.ASRDATA, function (info) {
_this4.emit("asrData", {
content: info.text
});
});
// speak
this.webRtc.on(eventType.SPEAKSTART, function (info) {
per.call(_this4, "playStart");
analysis({
event: "CLIENT_RECEIVE_PLAY_START",
message: info.audio || info.content,
sessionId: _this4.sessionId
});
_this4.emit("speakStart", info);
_this4.speakState = SpeakState.SPEAKING;
logger.info("SpeakStart", info);
});
this.webRtc.on(eventType.SPEAKSTOP, function (info) {
per.call(_this4, "speakEnd");
_this4.emit("speakEnd", info);
_this4.speakState = SpeakState.SLIENT;
logger.info("SpeakStop", info);
});
this.webRtc.on(eventType.SPEAKSECTION, function (info) {
per.call(_this4, "speakSection");
_this4.emit("speakSection", info);
logger.info("speakSection", info);
});
// ttsspeak
this.webRtc.on(eventType.TTSSPEAKSTART, function (info) {
_this4.emit("ttsSpeakStart", info);
logger.info("ttsSpeakStart", info);
});
this.webRtc.on(eventType.TTSSPEAKSTOP, function (info) {
_this4.emit("ttsSpeakEnd", info);
logger.info("ttsSpeakEnd", info);
});
this.webRtc.on(eventType.TTSSPEAKSECTION, function (info) {
_this4.emit("ttsSpeakSection", info);
logger.info("ttsSpeakSection", info);
});
// 报告网络信息/画面质量等
this.webRtc.on(eventType.REPORT, function (info) {
_this4.emit("report", info);
});
//发送本地SDP
this.webRtc.on(eventType.SENDSDP, function (sdp) {
logger.info("Webrtc send sdp");
_this4.publishMessage("AnswerSession", {
sdp: sdp
});
});
//发送candidate
this.webRtc.on(eventType.SENDCANDIDATE, function (candidate) {
if (candidate.candidate) {
logger.info("Webrtc send candidate");
_this4.publishMessage("AddSessionCandidate", {
candidate: candidate
});
}
});
//webRtc连接状态
this.webRtc.on(eventType.STATUS, function (params) {
var step = params.step,
success = params.success,
connectionState = params.connectionState;
logger.info("Webrtc status", params);
if (step === "connectionstate") {
if (success === true) {
clearTimeout(_this4.restartICETimer);
_this4.restartICETimer = null;
} else if (connectionState === "failed") {
if (_this4.sessionState === SessionState.CONNECTED) {
_classPrivateMethodGet(_this4, _reconnectRTC, _reconnectRTC2).call(_this4);
} else {
_this4.stop();
}
}
} else if (step === "getUserMedia") {
if (success === false) {
_this4.triggerError("4008", params);
_this4.stop();
}
}
});
// webRtc错误
this.webRtc.on(eventType.NEEDUSERINTERACT, function (error) {
_this4.triggerError("4009", error);
});
this.webRtc.on(eventType.CAMERACHANGE, function (data) {
_this4.emit("cameraChange", data);
});
this.webRtc.on(eventType.RESTARTICE, function () {
_this4.isRestartICE = true;
_this4.publishMessage("RestartICE");
});
}
}, {
key: "start",
value: // 开启会话
function () {
var _start = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _this$agoraInfo,
_this$agoraInfo2,
_this$agoraInfo3,
_this$agoraInfo4,
_this$agoraInfo5,
_options$vpxMaxBitrat,
_this$materialInfo,
_this$mqttTopic,
_this5 = this,
_options$enhanceOpus;
var options,
data,
remoteUid,
channelId,
localUid,
localToken,
ret,
_this$mqttTopic2,
extra,
message,
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
options = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
if (this.isInit) {
_context2.next = 3;
break;
}
throw new Error("Duix not init");
case 3:
if (this.sessionId) {
_context2.next = 13;
break;
}
_context2.next = 6;
return createSession({
sig: this.sign,
conversationId: this.conversationId
}, this.domain);
case 6:
data = _context2.sent;
if (!data.error) {
_context2.next = 11;
break;
}
logger.error("Duix restart failed. createSession failed");
this.triggerError("4005", {
code: data.code,
message: data.message
});
return _context2.abrupt("return", {
err: "Signature verification failed",
code: data.code,
message: data.message
});
case 11:
this.sessionInfo = data.sessionRsp;
this.sessionId = this.sessionInfo.sessionId;
case 13:
per.call(this, "start", {
conversationId: this.conversationId
});
logger.info("Duix.start", options);
if (!(this.sessionState !== SessionState.CLOSED)) {
_context2.next = 18;
break;
}
logger.warn("Duix.start failed");
return _context2.abrupt("return", {
err: "Session state is not closed."
});
case 18:
// const res = await queryConversationMaterial({ conversionId: this.conversationId, uuid: this.sessionId }, this.domain)
remoteUid = (_this$agoraInfo = this.agoraInfo) === null || _this$agoraInfo === void 0 ? void 0 : _this$agoraInfo.remoteUid;
channelId = (_this$agoraInfo2 = this.agoraInfo) === null || _this$agoraInfo2 === void 0 ? void 0 : _this$agoraInfo2.channelId;
localUid = (_this$agoraInfo3 = this.agoraInfo) === null || _this$agoraInfo3 === void 0 ? void 0 : _this$agoraInfo3.localUid;
(_this$agoraInfo4 = this.agoraInfo) === null || _this$agoraInfo4 === void 0 ? void 0 : _this$agoraInfo4.remoteToken;
localToken = (_this$agoraInfo5 = this.agoraInfo) === null || _this$agoraInfo5 === void 0 ? void 0 : _this$agoraInfo5.localToken; // const resList = res?.newSession?.resList || []
// const agoraRes = resList.find(item => item.resOptions?.type == 'agora')
this.sessionState = SessionState.CONNECTING;
this.transparent = options.transparent = options.wipeGreen ? false : options.transparent; // 打开扣绿幕时,自动关闭掩码模式
this.wipeGreen = options.wipeGreen || false;
this.vpxMaxBitrate = (_options$vpxMaxBitrat = options.vpxMaxBitrate) !== null && _options$vpxMaxBitrat !== void 0 ? _options$vpxMaxBitrat : this.rtcConfig.vpxMaxBitrate;
this.initOpenAsr = options.openAsr;
if (options.openAsr) {
this.asrState = AsrState.OPENED;
}
this.useActSection = options.useActSection;
this.videoAgentContainer = options.videoAgentContainer;
this.useVideoAgent = options.useVideoAgent;
this.useAudioAgent = options.useAudioAgent;
if (this.materialInfo) {
_context2.next = 37;
break;
}
this.sessionState = SessionState.CLOSED;
logger.error("Duix.start failed. Query conversation error.");
return _context2.abrupt("return", {
err: "Query conversation info fail"
});
case 37:
if (!((_this$materialInfo = this.materialInfo) !== null && _this$materialInfo !== void 0 && _this$materialInfo.asr)) {
logger.warn("Duix.start. Asr in empty");
}
if (!this.asrService) {
logger.warn("Duix.start. asrService in empty");
}
if (this.sessionInfo) {
_context2.next = 41;
break;
}
return _context2.abrupt("return", {
err: "Create session fail"
});
case 41:
this.mqttTopic = this.sessionInfo.mqttTopic;
_context2.next = 44;
return this.socket.subscribe((_this$mqttTopic = this.mqttTopic) === null || _this$mqttTopic === void 0 ? void 0 : _this$mqttTopic.topicSub);
case 44:
ret = _context2.sent;
if (ret) {
_context2.next = 48;
break;
}
logger.error("Duix.start failed. Subsribe error.", (_this$mqttTopic2 = this.mqttTopic) === null || _this$mqttTopic2 === void 0 ? void 0 : _this$mqttTopic2.topicSub);
return _context2.abrupt("return", {
err: "Subsribe topic failed"
});
case 48:
sessionStorage.setItem("_duix_sessionId", this.sessionId);
logger.info("Duix.start with session uuid ".concat(this.sessionId));
if (options.userId && this.conversationInfo.memoryIsUsed == 1) {
this.conversationInfo.memId = "".concat(options.userId, "_").concat(this.conversationId);
}
extra = _objectSpread2(_objectSpread2({}, this.conversationInfo), {}, {
openAsr: !!options.openAsr,
sessionInfo: {
appName: options.appName || "h5",
sessionId: this.sessionId,
userId: options.userId || "h5-user",
extContext: {
fofaConversationConfigId: options.configId
},
promptVariables: options.promptVariables,
enableLLM: options.enableLLM,
vadSilenceTime: options.vadSilenceTime
},
uuid: this.sessionId
}); // 发送开始会话消息
message = ResourceFactory.newSession(_objectSpread2(_objectSpread2({}, this.materialInfo), {}, {
transparent: this.transparent,
enableRec: options.enableRec || false,
useActSection: this.useActSection,
useVideoAgent: this.isSupportVideoAgent,
useAudioAgent: this.useAudioAgent,
useAgora: this.useAgora
}), extra, this.agoraInfo);
per.call(this, "makeNewSession");
this.publishMessage("MakeNewSession", message, function (data) {
if (data.error) {
logger.error("Duix.start failed", data.error);
_this5.sessionState = SessionState.CLOSED;
_this5.triggerError("4001", data.error);
} else {
logger.info("Duix.start succeeded");
}
});
this.webRtc.open({
sessionType: this.rtcConfig.sessionType,
peeConfig: this.rtcConfig.peeConfig,
muted: options.muted,
transparent: options.transparent,
// 是否掩码模式扣背景
wipeGreen: options.wipeGreen,
// 是否抠绿幕
enhanceOpus: (_options$enhanceOpus = options.enhanceOpus) !== null && _options$enhanceOpus !== void 0 ? _options$enhanceOpus : false,
vpxMaxBitrate: this.vpxMaxBitrate,
openAsr: options.openAsr,
useVideoAgent: this.useVideoAgent,
useAudioAgent: this.useAudioAgent,
isSupportVideoAgent: this.isSupportVideoAgent,
videoAgentContainer: this.videoAgentContainer,
token: localToken,
channelId: channelId,
remoteUid: remoteUid,
localUid: localUid
});
return _context2.abrupt("return", {
data: this.sessionId
});
case 57:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function start() {
return _start.apply(this, arguments);
}
return start;
}()
/**
* 关闭会话
*/
}, {
key: "stop",
value: function stop() {
var _this6 = this,
_this$webRtc;
logger.info("Duix.stop");
if (this.sessionState <= 1) {
this.sessionState = SessionState.CLOSING;
this.publishMessage("DestroySession", {
cause: "client stop"
});
//延迟处理兼并stop消息丢失会话未能正常开启或服务端下发bye消息丢失等异常情况
this.stopTimeout = setTimeout(function () {
_this6.destroySession();
}, 1500);
} else {
this.sessionState = SessionState.CLOSED;
}
Recorder.destroy();
(_this$webRtc = this.webRtc) === null || _this$webRtc === void 0 ? void 0 : _this$webRtc.hideDHVideo();
}
/**
* 销毁会话,释放资源
*/
}, {
key: "destroySession",
value: function destroySession() {
var _this$socket, _this$mqttTopic3;
per.call(this, "destory");
this.stopRecord();
this.closeAsr();
this.webRtc.close();
this.sessionState = SessionState.CLOSED;
this.sessionId = "";
this.emit("bye");
clearTimeout(this.timer);
(_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.unsubscribe((_this$mqttTopic3 = this.mqttTopic) === null || _this$mqttTopic3 === void 0 ? void 0 : _this$mqttTopic3.topicSub);
Recorder.destroy();
}
/**
* 获取当前会话状态
*/
}, {
key: "getSessionState",
value: function getSessionState() {
return this.sessionState;
}
}, {
key: "playAudio",
value: function playAudio(_ref) {
var audio = _ref.audio,
content = _ref.content,
interrupt = _ref.interrupt,
id = _ref.id;
logger.info("playAudio", content, audio, interrupt);
per.call(this, "playSend");
if (audio) {
this.publishMessage("ExecSessionResList", {
executeList: [{
name: "livekitagent",
options: {
method: "speakAudio",
args: {
audioUrl: audio,
ext: id,
interrupt: !!interrupt // 当前是否可以被打断
}
}
}]
});
return;
}
if (content) {
this.publishMessage("ExecSessionResList", {
executeList: [{
name: "livekitagent",
options: {
method: "speakText",
args: {
text: content,
ext: id,
interrupt: !!interrupt // 当前是否可以被打断
}
}
}]
});
return;
}
}
}, {
key: "answerAudio",
value: function answerAudio(_ref2) {
var question = _ref2.question,
interrupt = _ref2.interrupt,
id = _ref2.id;
logger.info("answerAudio", question, interrupt);
per.call(this, "playSend");
this.publishMessage("ExecSessionResList", {
executeList: [{
name: "livekitagent",
options: {
method: "askText",
args: {
text: question,
ext: id,
interrupt: !!interrupt
}
}
}]
});
}
// 回答问题
}, {
key: "answer",
value: function () {
var _answer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var options,
question,
interrupt,
_options$id,
id,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
options = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {};
question = options.question, interrupt = options.interrupt, _options$id = options.id, id = _options$id === void 0 ? uuid() : _options$id;
if (question) {
_context3.next = 4;
break;
}
throw new Error("Parameters 'question' option cannot be empty.");
case 4:
logger.info("Duix.answer", JSON.stringify({
question: question,
interrupt: interrupt
}));
analysis({
event: "CLIENT_SEND_GET_ANSWER_REQUEST",
message: question,
sessionId: this.sessionId
});
this.answerAudio({
question: question,
interrupt: interrupt,
id: id
});
return _context3.abrupt("return", Promise.resolve({
id: id
}));
case 8:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function answer() {
return _answer.apply(this, arguments);
}
return answer;
}() // 获取问题答案
}, {
key: "getAnswer",
value: function () {
var _getAnswer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(options) {
var question, data;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
question = options.question;
if (question) {
_context4.next = 3;
break;
}
throw new Error("Parameters 'question' option cannot be empty.");
case 3:
logger.info("Duix.getAnswer");
if (!(this.sessionState !== SessionState.CONNECTED)) {
_context4.next = 7;
break;
}
logger.error("Duix.getAnswer failed. Session is not connected");
return _context4.abrupt("return", {
err: "Session is not connected"
});
case 7:
_context4.next = 9;
return getByQuestion({
extContext: options.extContext || "",
question: question,
conversationId: this.conversationId,
sessionId: this.sessionId,
userId: options.userId
}, this.domain);
case 9:
data = _context4.sent;
if (data) {
_context4.next = 13;
break;
}
logger.error("Duix.getAnswer failed. Get answer error");
return _context4.abrupt("return", {
err: "Get answer error"
});
case 13:
return _context4.abrupt("return", {
data: data
});
case 14:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function getAnswer(_x) {
return _getAnswer.apply(this, arguments);
}
return getAnswer;
}() // 驱动数字人说话
}, {
key: "speak",
value: function speak() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var content = options.content,
audio = options.audio,
interrupt = options.interrupt,
_options$id2 = options.id,
id = _options$id2 === void 0 ? uuid() : _options$id2;
logger.info("Duix.speak", JSON.stringify({
content: content,
audio: audio,
interrupt: interrupt
}));
if (this.sessionState !== SessionState.CONNECTED) {
logger.error("Duix.speak failed. Session is not connected");
return Promise.resolve({
err: "Session is not connected"
});
}
if (audio || content) {
this.playAudio({
audio: audio,
content: content,
interrupt: interrupt,
id: id
});
}
return Promise.resolve({
id: id
});
}
// 打断数字人说话
}, {
key: "break",
value: function _break() {
logger.info("Duix.break");
this.publishMessage("ExecSessionResList", {
executeList: [{
name: "livekitagent",
//'dthuman',
options: {
method: "breakCurVoice",
args: {}
}
}]
});
}
/**
* 开启ASR实时识别
*/
}, {
key: "openAsr",
value: function () {
var _openAsr = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var _this$webRtc2, _this$webRtc3;
var _this$webRtc4, _this$webRtc5;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
if (!(this.recordState <= 1)) {
_context5.next = 3;
break;
}
logger.debug("Please turn off the recording before turning on ASR.");
return _context5.abrupt("return", {
err: "ASR and recording cannot be turned on at the same time"
});
case 3:
if (!(this.asrState !== AsrState.CLOSED)) {
_context5.next = 6;
break;
}
logger.debug("ASR real-time identification in progress.");
return _context5.abrupt("return", {
err: "ASR is running"
});
case 6:
logger.info("Duix.openAsr");
this.asrState = AsrState.OPENED;
if ((_this$webRtc2 = this.webRtc) !== null && _this$webRtc2 !== void 0 && _this$webRtc2.localMediaStream && (_this$webRtc3 = this.webRtc) !== null && _this$webRtc3 !== void 0 && (_this$webRtc3 = _this$webRtc3.localMediaStream) !== null && _this$webRtc3 !== void 0 && _this$webRtc3.getAudioTracks()[0]) {
(_this$webRtc4 = this.webRtc) === null || _this$webRtc4 === void 0 ? void 0 : _this$webRtc4.enableAudioContext();
} else {
(_this$webRtc5 = this.webRtc) === null || _this$webRtc5 === void 0 ? void 0 : _this$webRtc5.reopenAsr();
this.publishMessage("RestartICE");
}
case 9:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function openAsr() {
return _openAsr.apply(this, arguments);
}
return openAsr;
}()
/**
* 关闭ASR实时识别
*/
}, {
key: "closeAsr",
value: function () {
var _closeAsr = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
var _this$webRtc6;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
if (!(this.asrState >= 2)) {
_context6.next = 3;
break;
}
logger.debug("ASR real-time recognition is not Unopened.");
return _context6.abrupt("return", {
err: "ASR is closed"
});
case 3:
logger.info("Duix.closeAsr");
this.asrState = AsrState.CLOSED;
(_this$webRtc6 = this.webRtc) === null || _this$webRtc6 === void 0 ? void 0 : _this$webRtc6.disableAudioContext();
return _context6.abrupt("return", {});
case 7:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function closeAsr() {
return _closeAsr.apply(this, arguments);
}
return closeAsr;
}()
/**
* 开启录音
*/
}, {
key: "startRecord",
value: function () {
var _startRecord = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
var _this7 = this,
_this$materialInfo2,
_this$conversationInf2;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
if (this.isInit) {
_context7.next = 2;
break;
}
throw new Error("Duix not init");
case 2:
if (!(this.asrState <= 1)) {
_context7.next = 4;
break;
}
throw new Error('Please turn off ASR before starting recording.');
case 4:
if (!(this.recordState !== RecordState.CLOSED)) {
_context7.next = 6;
break;
}
throw new Error('Recording is in progress or is already on.');
case 6:
logger.info("Duix.startRecord");
this.recordState = RecordState.OPENING;
return _context7.abrupt("return", Recorder.start({
onStart: function onStart() {
_this7.recordState = RecordState.OPENED;
_this7.emit("asrStart");
},
onSentenceEnd: function onSentenceEnd(data) {
_this7.emit("asrStop", data);
},
onSentenceResultChange: function onSentenceResultChange(data) {
_this7.emit("asrData", data);
},
onStop: function onStop() {
_this7.recordState = RecordState.CLOSED;
},
url: (_this$materialInfo2 = this.materialInfo) === null || _this$materialInfo2 === void 0 || (_this$materialInfo2 = _this$materialInfo2.asr) === null || _this$materialInfo2 === void 0 ? void 0 : _this$materialInfo2.urlV2,
uuid: this.sessionId,
auth: this.sign,
endpoint: (_this$conversationInf2 = this.conversationInfo) === null || _this$conversationInf2 === void 0 ? void 0 : _this$conversationInf2.asrEndPoint
}));
case 9:
case "end":
return _context7.stop();
}
}, _callee7, this);
}));
function startRecord() {
return _startRecord.apply(this, arguments);
}
return startRecord;
}()
/**
* 结束录音
*/
}, {
key: "stopRecord",
value: function () {
var _stopRecord = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
logger.info("Duix.stopRecord");
if (!(this.recordState >= 2)) {
_context8.next = 3;
break;
}
return _context8.abrupt("return");
case 3:
this.recordState = RecordState.CLOSING;
Recorder.stop();
case 5:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
function stopRecord() {
return _stopRecord.apply(this, arguments);
}
return stopRecord;
}()
}, {
key: "destoryRecord",
value: function () {
var _destoryRecord = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
this.recordState = RecordState.CLOSED;
Recorder.destroy();
case 2:
case "end":
return _context9.stop();
}
}, _callee9, this);
}));
function destoryRecord() {
return _destoryRecord.apply(this, arguments);
}
return destoryRecord;
}()
}, {
key: "triggerError",
value: function triggerError(code) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
logger.warn("Trigger error", code, data);
this.emit("error", {
code: code,
message: ErrorMessage[code],
data: data
});
}
/**
* 设置远端媒体流静音状态
* @param {Boolean} muted true: 静音, false: 取消静音
*/
}, {
key: "setVideoMuted",
value: function setVideoMuted(muted) {
var _this$webRtc7;
logger.info("Duix.setVideoMuted", muted);
(_this$webRtc7 = this.webRtc) === null || _this$webRtc7 === void 0 ? void 0 : _this$webRtc7.setVideoMuted(muted);
}
/**
* 移除视频标签
*/
}, {
key: "removeVideo",
value: function removeVideo() {
var _this$webRtc8;
logger.info("Duix.removeVideo");
(_this$webRtc8 = this.webRtc) === null || _this$webRtc8 === void 0 ? void 0 : _this$webRtc8.removeVideoLabel();
}
}, {
key: "publishMessage",
value: function publishMessage(method) {
var _this$mqttTopic4;
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var complete = arguments.length > 2 ? arguments[2] : undefined;
if (this.sessionState === SessionState.CLOSED) {
logger.warn("Publish ".concat(method, " failed. Session is closed."));
return;
}
logger.info("Publish method", method, params);
var message = {
id: this.id++,
method: method,
sender: clientUuid(),
token: this.sign,
appId: this.appId,
conversationId: this.conversationId,
website: this.website,
params: _objectSpread2({
sessionId: this.sessionId
}, params),
variable: {
client_version: "0.1.0",
client_type: 2 // 0 ios 1 安卓 2 web
}
};
this.socket.publish((_this$mqttTopic4 = this.mqttTopic) === null || _this$mqttTopic4 === void 0 ? void 0 : _this$mqttTopic4.topicPub, JSON.stringify(message));
if (complete) {
MessageFactory.response(message.id, complete);
}
}
}, {
key: "resume",
value: function resume() {
var _this$webRtc9;
(_this$webRtc9 = this.webRtc) === null || _this$webRtc9 === void 0 || (_this$webRtc9 = _this$webRtc9.dhVideo) === null || _this$webRtc9 === void 0 ? void 0 : _this$webRtc9.play();
}
}, {
key: "pause",
value: function pause() {
var _this$webRtc10;
(_this$webRtc10 = this.webRtc) === null || _this$webRtc10 === void 0 || (_this$webRtc10 = _this$webRtc10.dhVideo) === null || _this$webRtc10 === void 0 ? void 0 : _this$webRtc10.pause();
}
}, {
key: "createCamera",
value: function createCamera() {
var _this$webRtc11;
(_this$webRtc11 = this.webRtc) === null || _this$webRtc11 === void 0 ? void 0 : _this$webRtc11.createCamera();
}
}, {
key: "destroyCamera",
value: function destroyCamera() {
var _this$webRtc12;
(_this$webRtc12 = this.webRtc) === null || _this$webRtc12 === void 0 ? void 0 : _this$webRtc12.destroyCamera();
}
}, {
key: "switchCameraMode",
value: function switchCameraMode() {
var _this$webRtc13;
(_this$webRtc13 = this.webRtc) === null || _this$webRtc13 === void 0 ? void 0 : _this$webRtc13.switchCameraMode();
}
}, {
key: "showCamera",
value: function showCamera() {
var _this$webRtc14;
(_this$webRtc14 = this.webRtc) === null || _this$webRtc14 === void 0 ? void 0 : _this$webRtc14.createCamera();
}
}, {
key: "hideCamera",
value: function hideCamera() {
var _this$webRtc15;
(_this$webRtc15 = this.webRtc) === null || _this$webRtc15 === void 0 ? void 0 : _this$webRtc15.hideCamera();
}
}, {
key: "playCamera",
value: function playCamera() {
var _this$webRtc16;
(_this$webRtc16 = this.webRtc) === null || _this$webRtc16 === void 0 ? void 0 : _this$webRtc16.playCamera();
}
}, {
key: "switchstreamBetweenDigitalAndCamera",
value: function switchstreamBetweenDigitalAndCamera() {
var _this$webRtc17;
(_this$webRtc17 = this.webRtc) === null || _this$webRtc17 === void 0 ? void 0 : _this$webRtc17.switchstreamBetweenDigitalAndCamera();
}
}]);
return DUIX;
}(Event$1);
function _reconnectRTC2() {
var _this8 = this;
logger.warn("Webrtc RestartICE");
this.isRestartICE = true;
this.publishMessage("RestartICE");
// 20秒未连接上结束会话
this.restartICETimer = setTimeout(function () {
logger.error("RestartICE failed");
_this8.triggerError("3001", {
cause: "RTC failed."
});
_this8.stop();
}, 20 * 1000);
}
return DUIX;
}));