/**
 * TVox v1.5.0
 * Referenced: 26.0.0
 *
 * Dependencies:
 * tslib -- 2.4.1
 * rxjs -- 7.8.0
 * debug -- 4.3.4
 * ms -- 2.1.2
 * lodash-es -- 4.17.21
 * detect-browser -- 5.3.0
 * webrtc-adapter -- 8.2.3
 * sdp -- 3.2.0
 * sdp-transform -- 2.14.2
 * cookie -- 0.5.0
 * retry -- 0.13.1
 * eventemitter3 -- 5.0.0
 * jszip -- 3.10.1
 */

var TVox = (function (exports) {
    '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);
    }

    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m) return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
        }
        catch (error) { e = { error: error }; }
        finally {
            try {
                if (r && !r.done && (m = i["return"])) m.call(i);
            }
            finally { if (e) throw e.error; }
        }
        return ar;
    }
    function __spreadArray$1(to, from, pack) {
        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
            if (ar || !(i in from)) {
                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                ar[i] = from[i];
            }
        }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
    }

    function isFunction$1(value) {
        return typeof value === 'function';
    }

    function createErrorClass(createImpl) {
        var _super = function (instance) {
            Error.call(instance);
            instance.stack = new Error().stack;
        };
        var ctorFunc = createImpl(_super);
        ctorFunc.prototype = Object.create(Error.prototype);
        ctorFunc.prototype.constructor = ctorFunc;
        return ctorFunc;
    }

    var UnsubscriptionError = createErrorClass(function (_super) {
        return function UnsubscriptionErrorImpl(errors) {
            _super(this);
            this.message = errors
                ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ')
                : '';
            this.name = 'UnsubscriptionError';
            this.errors = errors;
        };
    });

    function arrRemove(arr, item) {
        if (arr) {
            var index = arr.indexOf(item);
            0 <= index && arr.splice(index, 1);
        }
    }

    var Subscription = (function () {
        function Subscription(initialTeardown) {
            this.initialTeardown = initialTeardown;
            this.closed = false;
            this._parentage = null;
            this._finalizers = null;
        }
        Subscription.prototype.unsubscribe = function () {
            var e_1, _a, e_2, _b;
            var errors;
            if (!this.closed) {
                this.closed = true;
                var _parentage = this._parentage;
                if (_parentage) {
                    this._parentage = null;
                    if (Array.isArray(_parentage)) {
                        try {
                            for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
                                var parent_1 = _parentage_1_1.value;
                                parent_1.remove(this);
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                    }
                    else {
                        _parentage.remove(this);
                    }
                }
                var initialFinalizer = this.initialTeardown;
                if (isFunction$1(initialFinalizer)) {
                    try {
                        initialFinalizer();
                    }
                    catch (e) {
                        errors = e instanceof UnsubscriptionError ? e.errors : [e];
                    }
                }
                var _finalizers = this._finalizers;
                if (_finalizers) {
                    this._finalizers = null;
                    try {
                        for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
                            var finalizer = _finalizers_1_1.value;
                            try {
                                execFinalizer(finalizer);
                            }
                            catch (err) {
                                errors = errors !== null && errors !== void 0 ? errors : [];
                                if (err instanceof UnsubscriptionError) {
                                    errors = __spreadArray$1(__spreadArray$1([], __read(errors)), __read(err.errors));
                                }
                                else {
                                    errors.push(err);
                                }
                            }
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
                if (errors) {
                    throw new UnsubscriptionError(errors);
                }
            }
        };
        Subscription.prototype.add = function (teardown) {
            var _a;
            if (teardown && teardown !== this) {
                if (this.closed) {
                    execFinalizer(teardown);
                }
                else {
                    if (teardown instanceof Subscription) {
                        if (teardown.closed || teardown._hasParent(this)) {
                            return;
                        }
                        teardown._addParent(this);
                    }
                    (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
                }
            }
        };
        Subscription.prototype._hasParent = function (parent) {
            var _parentage = this._parentage;
            return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
        };
        Subscription.prototype._addParent = function (parent) {
            var _parentage = this._parentage;
            this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
        };
        Subscription.prototype._removeParent = function (parent) {
            var _parentage = this._parentage;
            if (_parentage === parent) {
                this._parentage = null;
            }
            else if (Array.isArray(_parentage)) {
                arrRemove(_parentage, parent);
            }
        };
        Subscription.prototype.remove = function (teardown) {
            var _finalizers = this._finalizers;
            _finalizers && arrRemove(_finalizers, teardown);
            if (teardown instanceof Subscription) {
                teardown._removeParent(this);
            }
        };
        Subscription.EMPTY = (function () {
            var empty = new Subscription();
            empty.closed = true;
            return empty;
        })();
        return Subscription;
    }());
    var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
    function isSubscription(value) {
        return (value instanceof Subscription ||
            (value && 'closed' in value && isFunction$1(value.remove) && isFunction$1(value.add) && isFunction$1(value.unsubscribe)));
    }
    function execFinalizer(finalizer) {
        if (isFunction$1(finalizer)) {
            finalizer();
        }
        else {
            finalizer.unsubscribe();
        }
    }

    var config = {
        onUnhandledError: null,
        onStoppedNotification: null,
        Promise: undefined,
        useDeprecatedSynchronousErrorHandling: false,
        useDeprecatedNextContext: false,
    };

    var timeoutProvider = {
        setTimeout: function (handler, timeout) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            var delegate = timeoutProvider.delegate;
            if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
                return delegate.setTimeout.apply(delegate, __spreadArray$1([handler, timeout], __read(args)));
            }
            return setTimeout.apply(void 0, __spreadArray$1([handler, timeout], __read(args)));
        },
        clearTimeout: function (handle) {
            var delegate = timeoutProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
        },
        delegate: undefined,
    };

    function reportUnhandledError(err) {
        timeoutProvider.setTimeout(function () {
            {
                throw err;
            }
        });
    }

    function noop$1() { }

    function errorContext(cb) {
        {
            cb();
        }
    }

    var Subscriber = (function (_super) {
        __extends(Subscriber, _super);
        function Subscriber(destination) {
            var _this = _super.call(this) || this;
            _this.isStopped = false;
            if (destination) {
                _this.destination = destination;
                if (isSubscription(destination)) {
                    destination.add(_this);
                }
            }
            else {
                _this.destination = EMPTY_OBSERVER;
            }
            return _this;
        }
        Subscriber.create = function (next, error, complete) {
            return new SafeSubscriber(next, error, complete);
        };
        Subscriber.prototype.next = function (value) {
            if (this.isStopped) ;
            else {
                this._next(value);
            }
        };
        Subscriber.prototype.error = function (err) {
            if (this.isStopped) ;
            else {
                this.isStopped = true;
                this._error(err);
            }
        };
        Subscriber.prototype.complete = function () {
            if (this.isStopped) ;
            else {
                this.isStopped = true;
                this._complete();
            }
        };
        Subscriber.prototype.unsubscribe = function () {
            if (!this.closed) {
                this.isStopped = true;
                _super.prototype.unsubscribe.call(this);
                this.destination = null;
            }
        };
        Subscriber.prototype._next = function (value) {
            this.destination.next(value);
        };
        Subscriber.prototype._error = function (err) {
            try {
                this.destination.error(err);
            }
            finally {
                this.unsubscribe();
            }
        };
        Subscriber.prototype._complete = function () {
            try {
                this.destination.complete();
            }
            finally {
                this.unsubscribe();
            }
        };
        return Subscriber;
    }(Subscription));
    var _bind = Function.prototype.bind;
    function bind(fn, thisArg) {
        return _bind.call(fn, thisArg);
    }
    var ConsumerObserver = (function () {
        function ConsumerObserver(partialObserver) {
            this.partialObserver = partialObserver;
        }
        ConsumerObserver.prototype.next = function (value) {
            var partialObserver = this.partialObserver;
            if (partialObserver.next) {
                try {
                    partialObserver.next(value);
                }
                catch (error) {
                    handleUnhandledError(error);
                }
            }
        };
        ConsumerObserver.prototype.error = function (err) {
            var partialObserver = this.partialObserver;
            if (partialObserver.error) {
                try {
                    partialObserver.error(err);
                }
                catch (error) {
                    handleUnhandledError(error);
                }
            }
            else {
                handleUnhandledError(err);
            }
        };
        ConsumerObserver.prototype.complete = function () {
            var partialObserver = this.partialObserver;
            if (partialObserver.complete) {
                try {
                    partialObserver.complete();
                }
                catch (error) {
                    handleUnhandledError(error);
                }
            }
        };
        return ConsumerObserver;
    }());
    var SafeSubscriber = (function (_super) {
        __extends(SafeSubscriber, _super);
        function SafeSubscriber(observerOrNext, error, complete) {
            var _this = _super.call(this) || this;
            var partialObserver;
            if (isFunction$1(observerOrNext) || !observerOrNext) {
                partialObserver = {
                    next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
                    error: error !== null && error !== void 0 ? error : undefined,
                    complete: complete !== null && complete !== void 0 ? complete : undefined,
                };
            }
            else {
                var context_1;
                if (_this && config.useDeprecatedNextContext) {
                    context_1 = Object.create(observerOrNext);
                    context_1.unsubscribe = function () { return _this.unsubscribe(); };
                    partialObserver = {
                        next: observerOrNext.next && bind(observerOrNext.next, context_1),
                        error: observerOrNext.error && bind(observerOrNext.error, context_1),
                        complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
                    };
                }
                else {
                    partialObserver = observerOrNext;
                }
            }
            _this.destination = new ConsumerObserver(partialObserver);
            return _this;
        }
        return SafeSubscriber;
    }(Subscriber));
    function handleUnhandledError(error) {
        {
            reportUnhandledError(error);
        }
    }
    function defaultErrorHandler(err) {
        throw err;
    }
    var EMPTY_OBSERVER = {
        closed: true,
        next: noop$1,
        error: defaultErrorHandler,
        complete: noop$1,
    };

    var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();

    function identity$1(x) {
        return x;
    }

    function pipeFromArray(fns) {
        if (fns.length === 0) {
            return identity$1;
        }
        if (fns.length === 1) {
            return fns[0];
        }
        return function piped(input) {
            return fns.reduce(function (prev, fn) { return fn(prev); }, input);
        };
    }

    var Observable = (function () {
        function Observable(subscribe) {
            if (subscribe) {
                this._subscribe = subscribe;
            }
        }
        Observable.prototype.lift = function (operator) {
            var observable = new Observable();
            observable.source = this;
            observable.operator = operator;
            return observable;
        };
        Observable.prototype.subscribe = function (observerOrNext, error, complete) {
            var _this = this;
            var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
            errorContext(function () {
                var _a = _this, operator = _a.operator, source = _a.source;
                subscriber.add(operator
                    ?
                        operator.call(subscriber, source)
                    : source
                        ?
                            _this._subscribe(subscriber)
                        :
                            _this._trySubscribe(subscriber));
            });
            return subscriber;
        };
        Observable.prototype._trySubscribe = function (sink) {
            try {
                return this._subscribe(sink);
            }
            catch (err) {
                sink.error(err);
            }
        };
        Observable.prototype.forEach = function (next, promiseCtor) {
            var _this = this;
            promiseCtor = getPromiseCtor(promiseCtor);
            return new promiseCtor(function (resolve, reject) {
                var subscriber = new SafeSubscriber({
                    next: function (value) {
                        try {
                            next(value);
                        }
                        catch (err) {
                            reject(err);
                            subscriber.unsubscribe();
                        }
                    },
                    error: reject,
                    complete: resolve,
                });
                _this.subscribe(subscriber);
            });
        };
        Observable.prototype._subscribe = function (subscriber) {
            var _a;
            return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
        };
        Observable.prototype[observable] = function () {
            return this;
        };
        Observable.prototype.pipe = function () {
            var operations = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                operations[_i] = arguments[_i];
            }
            return pipeFromArray(operations)(this);
        };
        Observable.prototype.toPromise = function (promiseCtor) {
            var _this = this;
            promiseCtor = getPromiseCtor(promiseCtor);
            return new promiseCtor(function (resolve, reject) {
                var value;
                _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
            });
        };
        Observable.create = function (subscribe) {
            return new Observable(subscribe);
        };
        return Observable;
    }());
    function getPromiseCtor(promiseCtor) {
        var _a;
        return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
    }
    function isObserver(value) {
        return value && isFunction$1(value.next) && isFunction$1(value.error) && isFunction$1(value.complete);
    }
    function isSubscriber(value) {
        return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
    }

    function hasLift(source) {
        return isFunction$1(source === null || source === void 0 ? void 0 : source.lift);
    }
    function operate(init) {
        return function (source) {
            if (hasLift(source)) {
                return source.lift(function (liftedSource) {
                    try {
                        return init(liftedSource, this);
                    }
                    catch (err) {
                        this.error(err);
                    }
                });
            }
            throw new TypeError('Unable to lift unknown Observable type');
        };
    }

    function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
        return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
    }
    var OperatorSubscriber = (function (_super) {
        __extends(OperatorSubscriber, _super);
        function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
            var _this = _super.call(this, destination) || this;
            _this.onFinalize = onFinalize;
            _this.shouldUnsubscribe = shouldUnsubscribe;
            _this._next = onNext
                ? function (value) {
                    try {
                        onNext(value);
                    }
                    catch (err) {
                        destination.error(err);
                    }
                }
                : _super.prototype._next;
            _this._error = onError
                ? function (err) {
                    try {
                        onError(err);
                    }
                    catch (err) {
                        destination.error(err);
                    }
                    finally {
                        this.unsubscribe();
                    }
                }
                : _super.prototype._error;
            _this._complete = onComplete
                ? function () {
                    try {
                        onComplete();
                    }
                    catch (err) {
                        destination.error(err);
                    }
                    finally {
                        this.unsubscribe();
                    }
                }
                : _super.prototype._complete;
            return _this;
        }
        OperatorSubscriber.prototype.unsubscribe = function () {
            var _a;
            if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
                var closed_1 = this.closed;
                _super.prototype.unsubscribe.call(this);
                !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
            }
        };
        return OperatorSubscriber;
    }(Subscriber));

    var ObjectUnsubscribedError = createErrorClass(function (_super) {
        return function ObjectUnsubscribedErrorImpl() {
            _super(this);
            this.name = 'ObjectUnsubscribedError';
            this.message = 'object unsubscribed';
        };
    });

    var Subject = (function (_super) {
        __extends(Subject, _super);
        function Subject() {
            var _this = _super.call(this) || this;
            _this.closed = false;
            _this.currentObservers = null;
            _this.observers = [];
            _this.isStopped = false;
            _this.hasError = false;
            _this.thrownError = null;
            return _this;
        }
        Subject.prototype.lift = function (operator) {
            var subject = new AnonymousSubject(this, this);
            subject.operator = operator;
            return subject;
        };
        Subject.prototype._throwIfClosed = function () {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
        };
        Subject.prototype.next = function (value) {
            var _this = this;
            errorContext(function () {
                var e_1, _a;
                _this._throwIfClosed();
                if (!_this.isStopped) {
                    if (!_this.currentObservers) {
                        _this.currentObservers = Array.from(_this.observers);
                    }
                    try {
                        for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
                            var observer = _c.value;
                            observer.next(value);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                }
            });
        };
        Subject.prototype.error = function (err) {
            var _this = this;
            errorContext(function () {
                _this._throwIfClosed();
                if (!_this.isStopped) {
                    _this.hasError = _this.isStopped = true;
                    _this.thrownError = err;
                    var observers = _this.observers;
                    while (observers.length) {
                        observers.shift().error(err);
                    }
                }
            });
        };
        Subject.prototype.complete = function () {
            var _this = this;
            errorContext(function () {
                _this._throwIfClosed();
                if (!_this.isStopped) {
                    _this.isStopped = true;
                    var observers = _this.observers;
                    while (observers.length) {
                        observers.shift().complete();
                    }
                }
            });
        };
        Subject.prototype.unsubscribe = function () {
            this.isStopped = this.closed = true;
            this.observers = this.currentObservers = null;
        };
        Object.defineProperty(Subject.prototype, "observed", {
            get: function () {
                var _a;
                return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
            },
            enumerable: false,
            configurable: true
        });
        Subject.prototype._trySubscribe = function (subscriber) {
            this._throwIfClosed();
            return _super.prototype._trySubscribe.call(this, subscriber);
        };
        Subject.prototype._subscribe = function (subscriber) {
            this._throwIfClosed();
            this._checkFinalizedStatuses(subscriber);
            return this._innerSubscribe(subscriber);
        };
        Subject.prototype._innerSubscribe = function (subscriber) {
            var _this = this;
            var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
            if (hasError || isStopped) {
                return EMPTY_SUBSCRIPTION;
            }
            this.currentObservers = null;
            observers.push(subscriber);
            return new Subscription(function () {
                _this.currentObservers = null;
                arrRemove(observers, subscriber);
            });
        };
        Subject.prototype._checkFinalizedStatuses = function (subscriber) {
            var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
            if (hasError) {
                subscriber.error(thrownError);
            }
            else if (isStopped) {
                subscriber.complete();
            }
        };
        Subject.prototype.asObservable = function () {
            var observable = new Observable();
            observable.source = this;
            return observable;
        };
        Subject.create = function (destination, source) {
            return new AnonymousSubject(destination, source);
        };
        return Subject;
    }(Observable));
    var AnonymousSubject = (function (_super) {
        __extends(AnonymousSubject, _super);
        function AnonymousSubject(destination, source) {
            var _this = _super.call(this) || this;
            _this.destination = destination;
            _this.source = source;
            return _this;
        }
        AnonymousSubject.prototype.next = function (value) {
            var _a, _b;
            (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
        };
        AnonymousSubject.prototype.error = function (err) {
            var _a, _b;
            (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
        };
        AnonymousSubject.prototype.complete = function () {
            var _a, _b;
            (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
        };
        AnonymousSubject.prototype._subscribe = function (subscriber) {
            var _a, _b;
            return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
        };
        return AnonymousSubject;
    }(Subject));

    var BehaviorSubject = (function (_super) {
        __extends(BehaviorSubject, _super);
        function BehaviorSubject(_value) {
            var _this = _super.call(this) || this;
            _this._value = _value;
            return _this;
        }
        Object.defineProperty(BehaviorSubject.prototype, "value", {
            get: function () {
                return this.getValue();
            },
            enumerable: false,
            configurable: true
        });
        BehaviorSubject.prototype._subscribe = function (subscriber) {
            var subscription = _super.prototype._subscribe.call(this, subscriber);
            !subscription.closed && subscriber.next(this._value);
            return subscription;
        };
        BehaviorSubject.prototype.getValue = function () {
            var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
            if (hasError) {
                throw thrownError;
            }
            this._throwIfClosed();
            return _value;
        };
        BehaviorSubject.prototype.next = function (value) {
            _super.prototype.next.call(this, (this._value = value));
        };
        return BehaviorSubject;
    }(Subject));

    var dateTimestampProvider = {
        now: function () {
            return (dateTimestampProvider.delegate || Date).now();
        },
        delegate: undefined,
    };

    var ReplaySubject = (function (_super) {
        __extends(ReplaySubject, _super);
        function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
            if (_bufferSize === void 0) { _bufferSize = Infinity; }
            if (_windowTime === void 0) { _windowTime = Infinity; }
            if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider; }
            var _this = _super.call(this) || this;
            _this._bufferSize = _bufferSize;
            _this._windowTime = _windowTime;
            _this._timestampProvider = _timestampProvider;
            _this._buffer = [];
            _this._infiniteTimeWindow = true;
            _this._infiniteTimeWindow = _windowTime === Infinity;
            _this._bufferSize = Math.max(1, _bufferSize);
            _this._windowTime = Math.max(1, _windowTime);
            return _this;
        }
        ReplaySubject.prototype.next = function (value) {
            var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
            if (!isStopped) {
                _buffer.push(value);
                !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
            }
            this._trimBuffer();
            _super.prototype.next.call(this, value);
        };
        ReplaySubject.prototype._subscribe = function (subscriber) {
            this._throwIfClosed();
            this._trimBuffer();
            var subscription = this._innerSubscribe(subscriber);
            var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
            var copy = _buffer.slice();
            for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
                subscriber.next(copy[i]);
            }
            this._checkFinalizedStatuses(subscriber);
            return subscription;
        };
        ReplaySubject.prototype._trimBuffer = function () {
            var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
            var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
            _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
            if (!_infiniteTimeWindow) {
                var now = _timestampProvider.now();
                var last = 0;
                for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
                    last = i;
                }
                last && _buffer.splice(0, last + 1);
            }
        };
        return ReplaySubject;
    }(Subject));

    var Action$1 = (function (_super) {
        __extends(Action, _super);
        function Action(scheduler, work) {
            return _super.call(this) || this;
        }
        Action.prototype.schedule = function (state, delay) {
            return this;
        };
        return Action;
    }(Subscription));

    var intervalProvider = {
        setInterval: function (handler, timeout) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            var delegate = intervalProvider.delegate;
            if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
                return delegate.setInterval.apply(delegate, __spreadArray$1([handler, timeout], __read(args)));
            }
            return setInterval.apply(void 0, __spreadArray$1([handler, timeout], __read(args)));
        },
        clearInterval: function (handle) {
            var delegate = intervalProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
        },
        delegate: undefined,
    };

    var AsyncAction = (function (_super) {
        __extends(AsyncAction, _super);
        function AsyncAction(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            _this.pending = false;
            return _this;
        }
        AsyncAction.prototype.schedule = function (state, delay) {
            var _a;
            if (delay === void 0) { delay = 0; }
            if (this.closed) {
                return this;
            }
            this.state = state;
            var id = this.id;
            var scheduler = this.scheduler;
            if (id != null) {
                this.id = this.recycleAsyncId(scheduler, id, delay);
            }
            this.pending = true;
            this.delay = delay;
            this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay);
            return this;
        };
        AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
            if (delay === void 0) { delay = 0; }
            return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
        };
        AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
            if (delay === void 0) { delay = 0; }
            if (delay != null && this.delay === delay && this.pending === false) {
                return id;
            }
            if (id != null) {
                intervalProvider.clearInterval(id);
            }
            return undefined;
        };
        AsyncAction.prototype.execute = function (state, delay) {
            if (this.closed) {
                return new Error('executing a cancelled action');
            }
            this.pending = false;
            var error = this._execute(state, delay);
            if (error) {
                return error;
            }
            else if (this.pending === false && this.id != null) {
                this.id = this.recycleAsyncId(this.scheduler, this.id, null);
            }
        };
        AsyncAction.prototype._execute = function (state, _delay) {
            var errored = false;
            var errorValue;
            try {
                this.work(state);
            }
            catch (e) {
                errored = true;
                errorValue = e ? e : new Error('Scheduled action threw falsy error');
            }
            if (errored) {
                this.unsubscribe();
                return errorValue;
            }
        };
        AsyncAction.prototype.unsubscribe = function () {
            if (!this.closed) {
                var _a = this, id = _a.id, scheduler = _a.scheduler;
                var actions = scheduler.actions;
                this.work = this.state = this.scheduler = null;
                this.pending = false;
                arrRemove(actions, this);
                if (id != null) {
                    this.id = this.recycleAsyncId(scheduler, id, null);
                }
                this.delay = null;
                _super.prototype.unsubscribe.call(this);
            }
        };
        return AsyncAction;
    }(Action$1));

    var Scheduler = (function () {
        function Scheduler(schedulerActionCtor, now) {
            if (now === void 0) { now = Scheduler.now; }
            this.schedulerActionCtor = schedulerActionCtor;
            this.now = now;
        }
        Scheduler.prototype.schedule = function (work, delay, state) {
            if (delay === void 0) { delay = 0; }
            return new this.schedulerActionCtor(this, work).schedule(state, delay);
        };
        Scheduler.now = dateTimestampProvider.now;
        return Scheduler;
    }());

    var AsyncScheduler = (function (_super) {
        __extends(AsyncScheduler, _super);
        function AsyncScheduler(SchedulerAction, now) {
            if (now === void 0) { now = Scheduler.now; }
            var _this = _super.call(this, SchedulerAction, now) || this;
            _this.actions = [];
            _this._active = false;
            return _this;
        }
        AsyncScheduler.prototype.flush = function (action) {
            var actions = this.actions;
            if (this._active) {
                actions.push(action);
                return;
            }
            var error;
            this._active = true;
            do {
                if ((error = action.execute(action.state, action.delay))) {
                    break;
                }
            } while ((action = actions.shift()));
            this._active = false;
            if (error) {
                while ((action = actions.shift())) {
                    action.unsubscribe();
                }
                throw error;
            }
        };
        return AsyncScheduler;
    }(Scheduler));

    var asyncScheduler = new AsyncScheduler(AsyncAction);
    var async = asyncScheduler;

    var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); });

    function isScheduler(value) {
        return value && isFunction$1(value.schedule);
    }

    function last$1(arr) {
        return arr[arr.length - 1];
    }
    function popResultSelector(args) {
        return isFunction$1(last$1(args)) ? args.pop() : undefined;
    }
    function popScheduler(args) {
        return isScheduler(last$1(args)) ? args.pop() : undefined;
    }
    function popNumber(args, defaultValue) {
        return typeof last$1(args) === 'number' ? args.pop() : defaultValue;
    }

    var isArrayLike$1 = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });

    function isPromise(value) {
        return isFunction$1(value === null || value === void 0 ? void 0 : value.then);
    }

    function isInteropObservable(input) {
        return isFunction$1(input[observable]);
    }

    function isAsyncIterable(obj) {
        return Symbol.asyncIterator && isFunction$1(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
    }

    function createInvalidObservableTypeError(input) {
        return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
    }

    function getSymbolIterator() {
        if (typeof Symbol !== 'function' || !Symbol.iterator) {
            return '@@iterator';
        }
        return Symbol.iterator;
    }
    var iterator = getSymbolIterator();

    function isIterable(input) {
        return isFunction$1(input === null || input === void 0 ? void 0 : input[iterator]);
    }

    function readableStreamLikeToAsyncGenerator(readableStream) {
        return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
            var reader, _a, value, done;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        reader = readableStream.getReader();
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, , 9, 10]);
                        _b.label = 2;
                    case 2:
                        return [4, __await(reader.read())];
                    case 3:
                        _a = _b.sent(), value = _a.value, done = _a.done;
                        if (!done) return [3, 5];
                        return [4, __await(void 0)];
                    case 4: return [2, _b.sent()];
                    case 5: return [4, __await(value)];
                    case 6: return [4, _b.sent()];
                    case 7:
                        _b.sent();
                        return [3, 2];
                    case 8: return [3, 10];
                    case 9:
                        reader.releaseLock();
                        return [7];
                    case 10: return [2];
                }
            });
        });
    }
    function isReadableStreamLike(obj) {
        return isFunction$1(obj === null || obj === void 0 ? void 0 : obj.getReader);
    }

    function innerFrom(input) {
        if (input instanceof Observable) {
            return input;
        }
        if (input != null) {
            if (isInteropObservable(input)) {
                return fromInteropObservable(input);
            }
            if (isArrayLike$1(input)) {
                return fromArrayLike(input);
            }
            if (isPromise(input)) {
                return fromPromise(input);
            }
            if (isAsyncIterable(input)) {
                return fromAsyncIterable(input);
            }
            if (isIterable(input)) {
                return fromIterable(input);
            }
            if (isReadableStreamLike(input)) {
                return fromReadableStreamLike(input);
            }
        }
        throw createInvalidObservableTypeError(input);
    }
    function fromInteropObservable(obj) {
        return new Observable(function (subscriber) {
            var obs = obj[observable]();
            if (isFunction$1(obs.subscribe)) {
                return obs.subscribe(subscriber);
            }
            throw new TypeError('Provided object does not correctly implement Symbol.observable');
        });
    }
    function fromArrayLike(array) {
        return new Observable(function (subscriber) {
            for (var i = 0; i < array.length && !subscriber.closed; i++) {
                subscriber.next(array[i]);
            }
            subscriber.complete();
        });
    }
    function fromPromise(promise) {
        return new Observable(function (subscriber) {
            promise
                .then(function (value) {
                if (!subscriber.closed) {
                    subscriber.next(value);
                    subscriber.complete();
                }
            }, function (err) { return subscriber.error(err); })
                .then(null, reportUnhandledError);
        });
    }
    function fromIterable(iterable) {
        return new Observable(function (subscriber) {
            var e_1, _a;
            try {
                for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
                    var value = iterable_1_1.value;
                    subscriber.next(value);
                    if (subscriber.closed) {
                        return;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            subscriber.complete();
        });
    }
    function fromAsyncIterable(asyncIterable) {
        return new Observable(function (subscriber) {
            process$1(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
        });
    }
    function fromReadableStreamLike(readableStream) {
        return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
    }
    function process$1(asyncIterable, subscriber) {
        var asyncIterable_1, asyncIterable_1_1;
        var e_2, _a;
        return __awaiter(this, void 0, void 0, function () {
            var value, e_2_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 5, 6, 11]);
                        asyncIterable_1 = __asyncValues(asyncIterable);
                        _b.label = 1;
                    case 1: return [4, asyncIterable_1.next()];
                    case 2:
                        if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
                        value = asyncIterable_1_1.value;
                        subscriber.next(value);
                        if (subscriber.closed) {
                            return [2];
                        }
                        _b.label = 3;
                    case 3: return [3, 1];
                    case 4: return [3, 11];
                    case 5:
                        e_2_1 = _b.sent();
                        e_2 = { error: e_2_1 };
                        return [3, 11];
                    case 6:
                        _b.trys.push([6, , 9, 10]);
                        if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
                        return [4, _a.call(asyncIterable_1)];
                    case 7:
                        _b.sent();
                        _b.label = 8;
                    case 8: return [3, 10];
                    case 9:
                        if (e_2) throw e_2.error;
                        return [7];
                    case 10: return [7];
                    case 11:
                        subscriber.complete();
                        return [2];
                }
            });
        });
    }

    function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
        if (delay === void 0) { delay = 0; }
        if (repeat === void 0) { repeat = false; }
        var scheduleSubscription = scheduler.schedule(function () {
            work();
            if (repeat) {
                parentSubscription.add(this.schedule(null, delay));
            }
            else {
                this.unsubscribe();
            }
        }, delay);
        parentSubscription.add(scheduleSubscription);
        if (!repeat) {
            return scheduleSubscription;
        }
    }

    function observeOn(scheduler, delay) {
        if (delay === void 0) { delay = 0; }
        return operate(function (source, subscriber) {
            source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
        });
    }

    function subscribeOn(scheduler, delay) {
        if (delay === void 0) { delay = 0; }
        return operate(function (source, subscriber) {
            subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
        });
    }

    function scheduleObservable(input, scheduler) {
        return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
    }

    function schedulePromise(input, scheduler) {
        return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
    }

    function scheduleArray(input, scheduler) {
        return new Observable(function (subscriber) {
            var i = 0;
            return scheduler.schedule(function () {
                if (i === input.length) {
                    subscriber.complete();
                }
                else {
                    subscriber.next(input[i++]);
                    if (!subscriber.closed) {
                        this.schedule();
                    }
                }
            });
        });
    }

    function scheduleIterable(input, scheduler) {
        return new Observable(function (subscriber) {
            var iterator$1;
            executeSchedule(subscriber, scheduler, function () {
                iterator$1 = input[iterator]();
                executeSchedule(subscriber, scheduler, function () {
                    var _a;
                    var value;
                    var done;
                    try {
                        (_a = iterator$1.next(), value = _a.value, done = _a.done);
                    }
                    catch (err) {
                        subscriber.error(err);
                        return;
                    }
                    if (done) {
                        subscriber.complete();
                    }
                    else {
                        subscriber.next(value);
                    }
                }, 0, true);
            });
            return function () { return isFunction$1(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
        });
    }

    function scheduleAsyncIterable(input, scheduler) {
        if (!input) {
            throw new Error('Iterable cannot be null');
        }
        return new Observable(function (subscriber) {
            executeSchedule(subscriber, scheduler, function () {
                var iterator = input[Symbol.asyncIterator]();
                executeSchedule(subscriber, scheduler, function () {
                    iterator.next().then(function (result) {
                        if (result.done) {
                            subscriber.complete();
                        }
                        else {
                            subscriber.next(result.value);
                        }
                    });
                }, 0, true);
            });
        });
    }

    function scheduleReadableStreamLike(input, scheduler) {
        return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
    }

    function scheduled(input, scheduler) {
        if (input != null) {
            if (isInteropObservable(input)) {
                return scheduleObservable(input, scheduler);
            }
            if (isArrayLike$1(input)) {
                return scheduleArray(input, scheduler);
            }
            if (isPromise(input)) {
                return schedulePromise(input, scheduler);
            }
            if (isAsyncIterable(input)) {
                return scheduleAsyncIterable(input, scheduler);
            }
            if (isIterable(input)) {
                return scheduleIterable(input, scheduler);
            }
            if (isReadableStreamLike(input)) {
                return scheduleReadableStreamLike(input, scheduler);
            }
        }
        throw createInvalidObservableTypeError(input);
    }

    function from(input, scheduler) {
        return scheduler ? scheduled(input, scheduler) : innerFrom(input);
    }

    function of() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var scheduler = popScheduler(args);
        return from(args, scheduler);
    }

    function throwError(errorOrErrorFactory, scheduler) {
        var errorFactory = isFunction$1(errorOrErrorFactory) ? errorOrErrorFactory : function () { return errorOrErrorFactory; };
        var init = function (subscriber) { return subscriber.error(errorFactory()); };
        return new Observable(scheduler ? function (subscriber) { return scheduler.schedule(init, 0, subscriber); } : init);
    }

    var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
        _super(this);
        this.name = 'EmptyError';
        this.message = 'no elements in sequence';
    }; });

    function lastValueFrom(source, config) {
        var hasConfig = typeof config === 'object';
        return new Promise(function (resolve, reject) {
            var _hasValue = false;
            var _value;
            source.subscribe({
                next: function (value) {
                    _value = value;
                    _hasValue = true;
                },
                error: reject,
                complete: function () {
                    if (_hasValue) {
                        resolve(_value);
                    }
                    else if (hasConfig) {
                        resolve(config.defaultValue);
                    }
                    else {
                        reject(new EmptyError());
                    }
                },
            });
        });
    }

    function isValidDate(value) {
        return value instanceof Date && !isNaN(value);
    }

    var TimeoutError = createErrorClass(function (_super) {
        return function TimeoutErrorImpl(info) {
            if (info === void 0) { info = null; }
            _super(this);
            this.message = 'Timeout has occurred';
            this.name = 'TimeoutError';
            this.info = info;
        };
    });
    function timeout(config, schedulerArg) {
        var _a = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config), first = _a.first, each = _a.each, _b = _a.with, _with = _b === void 0 ? timeoutErrorFactory : _b, _c = _a.scheduler, scheduler = _c === void 0 ? schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : asyncScheduler : _c, _d = _a.meta, meta = _d === void 0 ? null : _d;
        if (first == null && each == null) {
            throw new TypeError('No timeout provided.');
        }
        return operate(function (source, subscriber) {
            var originalSourceSubscription;
            var timerSubscription;
            var lastValue = null;
            var seen = 0;
            var startTimer = function (delay) {
                timerSubscription = executeSchedule(subscriber, scheduler, function () {
                    try {
                        originalSourceSubscription.unsubscribe();
                        innerFrom(_with({
                            meta: meta,
                            lastValue: lastValue,
                            seen: seen,
                        })).subscribe(subscriber);
                    }
                    catch (err) {
                        subscriber.error(err);
                    }
                }, delay);
            };
            originalSourceSubscription = source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
                seen++;
                subscriber.next((lastValue = value));
                each > 0 && startTimer(each);
            }, undefined, undefined, function () {
                if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
                    timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
                }
                lastValue = null;
            }));
            !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);
        });
    }
    function timeoutErrorFactory(info) {
        throw new TimeoutError(info);
    }

    function map(project, thisArg) {
        return operate(function (source, subscriber) {
            var index = 0;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                subscriber.next(project.call(thisArg, value, index++));
            }));
        });
    }

    var isArray$3 = Array.isArray;
    function callOrApply(fn, args) {
        return isArray$3(args) ? fn.apply(void 0, __spreadArray$1([], __read(args))) : fn(args);
    }
    function mapOneOrManyArgs(fn) {
        return map(function (args) { return callOrApply(fn, args); });
    }

    var isArray$2 = Array.isArray;
    var getPrototypeOf = Object.getPrototypeOf, objectProto$6 = Object.prototype, getKeys = Object.keys;
    function argsArgArrayOrObject(args) {
        if (args.length === 1) {
            var first_1 = args[0];
            if (isArray$2(first_1)) {
                return { args: first_1, keys: null };
            }
            if (isPOJO(first_1)) {
                var keys = getKeys(first_1);
                return {
                    args: keys.map(function (key) { return first_1[key]; }),
                    keys: keys,
                };
            }
        }
        return { args: args, keys: null };
    }
    function isPOJO(obj) {
        return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto$6;
    }

    function createObject(keys, values) {
        return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});
    }

    function combineLatest() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var scheduler = popScheduler(args);
        var resultSelector = popResultSelector(args);
        var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
        if (observables.length === 0) {
            return from([], scheduler);
        }
        var result = new Observable(combineLatestInit(observables, scheduler, keys
            ?
                function (values) { return createObject(keys, values); }
            :
                identity$1));
        return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
    }
    function combineLatestInit(observables, scheduler, valueTransform) {
        if (valueTransform === void 0) { valueTransform = identity$1; }
        return function (subscriber) {
            maybeSchedule(scheduler, function () {
                var length = observables.length;
                var values = new Array(length);
                var active = length;
                var remainingFirstValues = length;
                var _loop_1 = function (i) {
                    maybeSchedule(scheduler, function () {
                        var source = from(observables[i], scheduler);
                        var hasFirstValue = false;
                        source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                            values[i] = value;
                            if (!hasFirstValue) {
                                hasFirstValue = true;
                                remainingFirstValues--;
                            }
                            if (!remainingFirstValues) {
                                subscriber.next(valueTransform(values.slice()));
                            }
                        }, function () {
                            if (!--active) {
                                subscriber.complete();
                            }
                        }));
                    }, subscriber);
                };
                for (var i = 0; i < length; i++) {
                    _loop_1(i);
                }
            }, subscriber);
        };
    }
    function maybeSchedule(scheduler, execute, subscription) {
        if (scheduler) {
            executeSchedule(subscription, scheduler, execute);
        }
        else {
            execute();
        }
    }

    function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
        var buffer = [];
        var active = 0;
        var index = 0;
        var isComplete = false;
        var checkComplete = function () {
            if (isComplete && !buffer.length && !active) {
                subscriber.complete();
            }
        };
        var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
        var doInnerSub = function (value) {
            expand && subscriber.next(value);
            active++;
            var innerComplete = false;
            innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
                onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
                if (expand) {
                    outerNext(innerValue);
                }
                else {
                    subscriber.next(innerValue);
                }
            }, function () {
                innerComplete = true;
            }, undefined, function () {
                if (innerComplete) {
                    try {
                        active--;
                        var _loop_1 = function () {
                            var bufferedValue = buffer.shift();
                            if (innerSubScheduler) {
                                executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
                            }
                            else {
                                doInnerSub(bufferedValue);
                            }
                        };
                        while (buffer.length && active < concurrent) {
                            _loop_1();
                        }
                        checkComplete();
                    }
                    catch (err) {
                        subscriber.error(err);
                    }
                }
            }));
        };
        source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
            isComplete = true;
            checkComplete();
        }));
        return function () {
            additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
        };
    }

    function mergeMap(project, resultSelector, concurrent) {
        if (concurrent === void 0) { concurrent = Infinity; }
        if (isFunction$1(resultSelector)) {
            return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
        }
        else if (typeof resultSelector === 'number') {
            concurrent = resultSelector;
        }
        return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
    }

    function mergeAll(concurrent) {
        if (concurrent === void 0) { concurrent = Infinity; }
        return mergeMap(identity$1, concurrent);
    }

    function concatAll() {
        return mergeAll(1);
    }

    function concat() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return concatAll()(from(args, popScheduler(args)));
    }

    function defer(observableFactory) {
        return new Observable(function (subscriber) {
            innerFrom(observableFactory()).subscribe(subscriber);
        });
    }

    var nodeEventEmitterMethods = ['addListener', 'removeListener'];
    var eventTargetMethods = ['addEventListener', 'removeEventListener'];
    var jqueryMethods = ['on', 'off'];
    function fromEvent(target, eventName, options, resultSelector) {
        if (isFunction$1(options)) {
            resultSelector = options;
            options = undefined;
        }
        if (resultSelector) {
            return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs(resultSelector));
        }
        var _a = __read(isEventTarget(target)
            ? eventTargetMethods.map(function (methodName) { return function (handler) { return target[methodName](eventName, handler, options); }; })
            :
                isNodeStyleEventEmitter(target)
                    ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
                    : isJQueryStyleEventEmitter(target)
                        ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
                        : [], 2), add = _a[0], remove = _a[1];
        if (!add) {
            if (isArrayLike$1(target)) {
                return mergeMap(function (subTarget) { return fromEvent(subTarget, eventName, options); })(innerFrom(target));
            }
        }
        if (!add) {
            throw new TypeError('Invalid event target');
        }
        return new Observable(function (subscriber) {
            var handler = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return subscriber.next(1 < args.length ? args : args[0]);
            };
            add(handler);
            return function () { return remove(handler); };
        });
    }
    function toCommonHandlerRegistry(target, eventName) {
        return function (methodName) { return function (handler) { return target[methodName](eventName, handler); }; };
    }
    function isNodeStyleEventEmitter(target) {
        return isFunction$1(target.addListener) && isFunction$1(target.removeListener);
    }
    function isJQueryStyleEventEmitter(target) {
        return isFunction$1(target.on) && isFunction$1(target.off);
    }
    function isEventTarget(target) {
        return isFunction$1(target.addEventListener) && isFunction$1(target.removeEventListener);
    }

    function timer(dueTime, intervalOrScheduler, scheduler) {
        if (dueTime === void 0) { dueTime = 0; }
        if (scheduler === void 0) { scheduler = async; }
        var intervalDuration = -1;
        if (intervalOrScheduler != null) {
            if (isScheduler(intervalOrScheduler)) {
                scheduler = intervalOrScheduler;
            }
            else {
                intervalDuration = intervalOrScheduler;
            }
        }
        return new Observable(function (subscriber) {
            var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
            if (due < 0) {
                due = 0;
            }
            var n = 0;
            return scheduler.schedule(function () {
                if (!subscriber.closed) {
                    subscriber.next(n++);
                    if (0 <= intervalDuration) {
                        this.schedule(undefined, intervalDuration);
                    }
                    else {
                        subscriber.complete();
                    }
                }
            }, due);
        });
    }

    function interval(period, scheduler) {
        if (period === void 0) { period = 0; }
        if (scheduler === void 0) { scheduler = asyncScheduler; }
        if (period < 0) {
            period = 0;
        }
        return timer(period, period, scheduler);
    }

    function merge() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var scheduler = popScheduler(args);
        var concurrent = popNumber(args, Infinity);
        var sources = args;
        return !sources.length
            ?
                EMPTY
            : sources.length === 1
                ?
                    innerFrom(sources[0])
                :
                    mergeAll(concurrent)(from(sources, scheduler));
    }

    function not(pred, thisArg) {
        return function (value, index) { return !pred.call(thisArg, value, index); };
    }

    function filter(predicate, thisArg) {
        return operate(function (source, subscriber) {
            var index = 0;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
        });
    }

    function partition(source, predicate, thisArg) {
        return [filter(predicate, thisArg)(innerFrom(source)), filter(not(predicate, thisArg))(innerFrom(source))];
    }

    function bufferCount(bufferSize, startBufferEvery) {
        if (startBufferEvery === void 0) { startBufferEvery = null; }
        startBufferEvery = startBufferEvery !== null && startBufferEvery !== void 0 ? startBufferEvery : bufferSize;
        return operate(function (source, subscriber) {
            var buffers = [];
            var count = 0;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                var e_1, _a, e_2, _b;
                var toEmit = null;
                if (count++ % startBufferEvery === 0) {
                    buffers.push([]);
                }
                try {
                    for (var buffers_1 = __values(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
                        var buffer = buffers_1_1.value;
                        buffer.push(value);
                        if (bufferSize <= buffer.length) {
                            toEmit = toEmit !== null && toEmit !== void 0 ? toEmit : [];
                            toEmit.push(buffer);
                        }
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                if (toEmit) {
                    try {
                        for (var toEmit_1 = __values(toEmit), toEmit_1_1 = toEmit_1.next(); !toEmit_1_1.done; toEmit_1_1 = toEmit_1.next()) {
                            var buffer = toEmit_1_1.value;
                            arrRemove(buffers, buffer);
                            subscriber.next(buffer);
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (toEmit_1_1 && !toEmit_1_1.done && (_b = toEmit_1.return)) _b.call(toEmit_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
            }, function () {
                var e_3, _a;
                try {
                    for (var buffers_2 = __values(buffers), buffers_2_1 = buffers_2.next(); !buffers_2_1.done; buffers_2_1 = buffers_2.next()) {
                        var buffer = buffers_2_1.value;
                        subscriber.next(buffer);
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (buffers_2_1 && !buffers_2_1.done && (_a = buffers_2.return)) _a.call(buffers_2);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
                subscriber.complete();
            }, undefined, function () {
                buffers = null;
            }));
        });
    }

    function catchError(selector) {
        return operate(function (source, subscriber) {
            var innerSub = null;
            var syncUnsub = false;
            var handledResult;
            innerSub = source.subscribe(createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
                handledResult = innerFrom(selector(err, catchError(selector)(source)));
                if (innerSub) {
                    innerSub.unsubscribe();
                    innerSub = null;
                    handledResult.subscribe(subscriber);
                }
                else {
                    syncUnsub = true;
                }
            }));
            if (syncUnsub) {
                innerSub.unsubscribe();
                innerSub = null;
                handledResult.subscribe(subscriber);
            }
        });
    }

    function concatMap(project, resultSelector) {
        return isFunction$1(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);
    }

    function debounceTime(dueTime, scheduler) {
        if (scheduler === void 0) { scheduler = asyncScheduler; }
        return operate(function (source, subscriber) {
            var activeTask = null;
            var lastValue = null;
            var lastTime = null;
            var emit = function () {
                if (activeTask) {
                    activeTask.unsubscribe();
                    activeTask = null;
                    var value = lastValue;
                    lastValue = null;
                    subscriber.next(value);
                }
            };
            function emitWhenIdle() {
                var targetTime = lastTime + dueTime;
                var now = scheduler.now();
                if (now < targetTime) {
                    activeTask = this.schedule(undefined, targetTime - now);
                    subscriber.add(activeTask);
                    return;
                }
                emit();
            }
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                lastValue = value;
                lastTime = scheduler.now();
                if (!activeTask) {
                    activeTask = scheduler.schedule(emitWhenIdle, dueTime);
                    subscriber.add(activeTask);
                }
            }, function () {
                emit();
                subscriber.complete();
            }, undefined, function () {
                lastValue = activeTask = null;
            }));
        });
    }

    function defaultIfEmpty(defaultValue) {
        return operate(function (source, subscriber) {
            var hasValue = false;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                hasValue = true;
                subscriber.next(value);
            }, function () {
                if (!hasValue) {
                    subscriber.next(defaultValue);
                }
                subscriber.complete();
            }));
        });
    }

    function take(count) {
        return count <= 0
            ?
                function () { return EMPTY; }
            : operate(function (source, subscriber) {
                var seen = 0;
                source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                    if (++seen <= count) {
                        subscriber.next(value);
                        if (count <= seen) {
                            subscriber.complete();
                        }
                    }
                }));
            });
    }

    function ignoreElements() {
        return operate(function (source, subscriber) {
            source.subscribe(createOperatorSubscriber(subscriber, noop$1));
        });
    }

    function mapTo(value) {
        return map(function () { return value; });
    }

    function delayWhen(delayDurationSelector, subscriptionDelay) {
        if (subscriptionDelay) {
            return function (source) {
                return concat(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));
            };
        }
        return mergeMap(function (value, index) { return innerFrom(delayDurationSelector(value, index)).pipe(take(1), mapTo(value)); });
    }

    function delay(due, scheduler) {
        if (scheduler === void 0) { scheduler = asyncScheduler; }
        var duration = timer(due, scheduler);
        return delayWhen(function () { return duration; });
    }

    function distinctUntilChanged(comparator, keySelector) {
        if (keySelector === void 0) { keySelector = identity$1; }
        comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
        return operate(function (source, subscriber) {
            var previousKey;
            var first = true;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                var currentKey = keySelector(value);
                if (first || !comparator(previousKey, currentKey)) {
                    first = false;
                    previousKey = currentKey;
                    subscriber.next(value);
                }
            }));
        });
    }
    function defaultCompare(a, b) {
        return a === b;
    }

    function throwIfEmpty(errorFactory) {
        if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
        return operate(function (source, subscriber) {
            var hasValue = false;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                hasValue = true;
                subscriber.next(value);
            }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
        });
    }
    function defaultErrorFactory() {
        return new EmptyError();
    }

    function finalize(callback) {
        return operate(function (source, subscriber) {
            try {
                source.subscribe(subscriber);
            }
            finally {
                subscriber.add(callback);
            }
        });
    }

    function first(predicate, defaultValue) {
        var hasDefaultValue = arguments.length >= 2;
        return function (source) {
            return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
        };
    }

    function takeLast(count) {
        return count <= 0
            ? function () { return EMPTY; }
            : operate(function (source, subscriber) {
                var buffer = [];
                source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                    buffer.push(value);
                    count < buffer.length && buffer.shift();
                }, function () {
                    var e_1, _a;
                    try {
                        for (var buffer_1 = __values(buffer), buffer_1_1 = buffer_1.next(); !buffer_1_1.done; buffer_1_1 = buffer_1.next()) {
                            var value = buffer_1_1.value;
                            subscriber.next(value);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (buffer_1_1 && !buffer_1_1.done && (_a = buffer_1.return)) _a.call(buffer_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    subscriber.complete();
                }, undefined, function () {
                    buffer = null;
                }));
            });
    }

    function last(predicate, defaultValue) {
        var hasDefaultValue = arguments.length >= 2;
        return function (source) {
            return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
        };
    }

    function pairwise() {
        return operate(function (source, subscriber) {
            var prev;
            var hasPrev = false;
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                var p = prev;
                prev = value;
                hasPrev && subscriber.next([p, value]);
                hasPrev = true;
            }));
        });
    }

    function share(options) {
        if (options === void 0) { options = {}; }
        var _a = options.connector, connector = _a === void 0 ? function () { return new Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d;
        return function (wrapperSource) {
            var connection;
            var resetConnection;
            var subject;
            var refCount = 0;
            var hasCompleted = false;
            var hasErrored = false;
            var cancelReset = function () {
                resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();
                resetConnection = undefined;
            };
            var reset = function () {
                cancelReset();
                connection = subject = undefined;
                hasCompleted = hasErrored = false;
            };
            var resetAndUnsubscribe = function () {
                var conn = connection;
                reset();
                conn === null || conn === void 0 ? void 0 : conn.unsubscribe();
            };
            return operate(function (source, subscriber) {
                refCount++;
                if (!hasErrored && !hasCompleted) {
                    cancelReset();
                }
                var dest = (subject = subject !== null && subject !== void 0 ? subject : connector());
                subscriber.add(function () {
                    refCount--;
                    if (refCount === 0 && !hasErrored && !hasCompleted) {
                        resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
                    }
                });
                dest.subscribe(subscriber);
                if (!connection &&
                    refCount > 0) {
                    connection = new SafeSubscriber({
                        next: function (value) { return dest.next(value); },
                        error: function (err) {
                            hasErrored = true;
                            cancelReset();
                            resetConnection = handleReset(reset, resetOnError, err);
                            dest.error(err);
                        },
                        complete: function () {
                            hasCompleted = true;
                            cancelReset();
                            resetConnection = handleReset(reset, resetOnComplete);
                            dest.complete();
                        },
                    });
                    innerFrom(source).subscribe(connection);
                }
            })(wrapperSource);
        };
    }
    function handleReset(reset, on) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        if (on === true) {
            reset();
            return;
        }
        if (on === false) {
            return;
        }
        var onSubscriber = new SafeSubscriber({
            next: function () {
                onSubscriber.unsubscribe();
                reset();
            },
        });
        return innerFrom(on.apply(void 0, __spreadArray$1([], __read(args)))).subscribe(onSubscriber);
    }

    function shareReplay(configOrBufferSize, windowTime, scheduler) {
        var _a, _b, _c;
        var bufferSize;
        var refCount = false;
        if (configOrBufferSize && typeof configOrBufferSize === 'object') {
            (_a = configOrBufferSize.bufferSize, bufferSize = _a === void 0 ? Infinity : _a, _b = configOrBufferSize.windowTime, windowTime = _b === void 0 ? Infinity : _b, _c = configOrBufferSize.refCount, refCount = _c === void 0 ? false : _c, scheduler = configOrBufferSize.scheduler);
        }
        else {
            bufferSize = (configOrBufferSize !== null && configOrBufferSize !== void 0 ? configOrBufferSize : Infinity);
        }
        return share({
            connector: function () { return new ReplaySubject(bufferSize, windowTime, scheduler); },
            resetOnError: true,
            resetOnComplete: false,
            resetOnRefCountZero: refCount,
        });
    }

    function skip(count) {
        return filter(function (_, index) { return count <= index; });
    }

    function switchMap(project, resultSelector) {
        return operate(function (source, subscriber) {
            var innerSubscriber = null;
            var index = 0;
            var isComplete = false;
            var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
                var innerIndex = 0;
                var outerIndex = index++;
                innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
                    innerSubscriber = null;
                    checkComplete();
                })));
            }, function () {
                isComplete = true;
                checkComplete();
            }));
        });
    }

    function tap(observerOrNext, error, complete) {
        var tapObserver = isFunction$1(observerOrNext) || error || complete
            ?
                { next: observerOrNext, error: error, complete: complete }
            : observerOrNext;
        return tapObserver
            ? operate(function (source, subscriber) {
                var _a;
                (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
                var isUnsub = true;
                source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                    var _a;
                    (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
                    subscriber.next(value);
                }, function () {
                    var _a;
                    isUnsub = false;
                    (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
                    subscriber.complete();
                }, function (err) {
                    var _a;
                    isUnsub = false;
                    (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
                    subscriber.error(err);
                }, function () {
                    var _a, _b;
                    if (isUnsub) {
                        (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
                    }
                    (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
                }));
            })
            :
                identity$1;
    }

    var defaultThrottleConfig = {
        leading: true,
        trailing: false,
    };
    function throttle(durationSelector, config) {
        if (config === void 0) { config = defaultThrottleConfig; }
        return operate(function (source, subscriber) {
            var leading = config.leading, trailing = config.trailing;
            var hasValue = false;
            var sendValue = null;
            var throttled = null;
            var isComplete = false;
            var endThrottling = function () {
                throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
                throttled = null;
                if (trailing) {
                    send();
                    isComplete && subscriber.complete();
                }
            };
            var cleanupThrottling = function () {
                throttled = null;
                isComplete && subscriber.complete();
            };
            var startThrottle = function (value) {
                return (throttled = innerFrom(durationSelector(value)).subscribe(createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));
            };
            var send = function () {
                if (hasValue) {
                    hasValue = false;
                    var value = sendValue;
                    sendValue = null;
                    subscriber.next(value);
                    !isComplete && startThrottle(value);
                }
            };
            source.subscribe(createOperatorSubscriber(subscriber, function (value) {
                hasValue = true;
                sendValue = value;
                !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
            }, function () {
                isComplete = true;
                !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
            }));
        });
    }

    function throttleTime(duration, scheduler, config) {
        if (scheduler === void 0) { scheduler = asyncScheduler; }
        if (config === void 0) { config = defaultThrottleConfig; }
        var duration$ = timer(duration, scheduler);
        return throttle(function () { return duration$; }, config);
    }

    var ChannelType;
    (function (ChannelType) {
        ChannelType["PhoneCall"] = "PHONE_CALL";
        ChannelType["MC1"] = "CHANNEL_1";
        ChannelType["MC2"] = "CHANNEL_2";
        ChannelType["MC3"] = "CHANNEL_3";
        ChannelType["Video"] = "VIDEO";
        ChannelType["Mail"] = "MAIL";
        ChannelType["LiveHelp"] = "LIVEHELP";
        ChannelType["Chat"] = "CHAT";
        ChannelType["CallBack"] = "CALLBACK";
        ChannelType["Omnidesk"] = "OMNIDESK";
    })(ChannelType || (ChannelType = {}));
    const multiChannelMapper = new Map([
        [ChannelType.PhoneCall, "0"],
        [ChannelType.MC1, "1"],
        [ChannelType.MC2, "2"],
        [ChannelType.MC3, "3"],
        [ChannelType.CallBack, "1000"],
        [ChannelType.Video, "1001"],
        [ChannelType.Mail, "1002"],
        [ChannelType.LiveHelp, "1003"],
        [ChannelType.Chat, "1004"],
        [ChannelType.Omnidesk, "1006"],
    ]);
    const multiChannelIdMapper = (function initMultiChannelIdMapper() {
        const map = new Map();
        multiChannelMapper.forEach((channelId, channelType) => {
            map.set(channelId, channelType);
        });
        return map;
    })();
    function channelTypeToId(channelType) {
        var _a;
        return channelType ? (_a = multiChannelMapper.get(channelType)) !== null && _a !== void 0 ? _a : null : null;
    }
    function channelIdToChannelType(channelId) {
        var _a;
        return (_a = multiChannelIdMapper.get((channelId !== null && channelId !== void 0 ? channelId : "").trim())) !== null && _a !== void 0 ? _a : null;
    }
    const asyncTimeout = (timeout) => __awaiter(void 0, void 0, void 0, function* () { return new Promise((resolve) => setTimeout(resolve, timeout)); });
    function MapOrSet_toJSON(key, value) {
        if (value && typeof value === "object") {
            if (value instanceof Set) {
                const result = [];
                value.forEach((m) => result.push(m));
                return result;
            }
            else if (value instanceof Map) {
                const result = {};
                value.forEach((value, key) => {
                    result[key] = value;
                });
                return result;
            }
        }
        return value;
    }
    const returnFalse = () => __awaiter(void 0, void 0, void 0, function* () { return false; });

    var ConnectionKey;
    (function (ConnectionKey) {
        ConnectionKey["pingToMaster"] = "pingToMaster";
        ConnectionKey["pingToSlave"] = "pingToSlave";
        ConnectionKey["pongToSlave"] = "pongToSlave";
        ConnectionKey["pongToMaster"] = "pongToMaster";
        ConnectionKey["hierarchy"] = "hierarchy";
        ConnectionKey["toWsRequest"] = "toWsRequest";
        ConnectionKey["toWsRequestComplete"] = "toWsRequestComplete";
        ConnectionKey["fromWsRequestId"] = "fromWsRequestId";
        ConnectionKey["fromWsRequestIdUpdate"] = "fromWsRequestIdUpdate";
        ConnectionKey["fromWsResponse"] = "fromWsResponse";
        ConnectionKey["videoChannelConfig"] = "videochannelConfig";
        ConnectionKey["chatChannelConfig"] = "chatChannelConfig";
        ConnectionKey["commonMethodsMessage"] = "commonMethodsMessage";
        ConnectionKey["closeChatSession"] = "closeChatSession";
        ConnectionKey["closeVideoSession"] = "closeVideoSession";
        ConnectionKey["closeCallSession"] = "closeCallSession";
        ConnectionKey["chatChannelSession"] = "chatChannelSession";
        ConnectionKey["jsessionId"] = "jsessionId";
        ConnectionKey["deviceId"] = "deviceId";
    })(ConnectionKey || (ConnectionKey = {}));
    var Storagelevel;
    (function (Storagelevel) {
        Storagelevel[Storagelevel["master"] = 0] = "master";
        Storagelevel[Storagelevel["slave"] = 1] = "slave";
        Storagelevel[Storagelevel["futureMaster"] = 2] = "futureMaster";
    })(Storagelevel || (Storagelevel = {}));
    class HierarchyMessage {
        constructor(master, slave) {
            this.connectionFutureMaster = null;
            this.connectionMaster = master;
            this.connectionSlave = slave;
        }
    }
    class RegisterRequestObj {
        constructor(idSlaves, request, requestIdentifierNotification) {
            this.id_slaves = idSlaves;
            this.request = request;
            this.requestIdentifierNotification = requestIdentifierNotification;
            this.lastResponse = new Array();
        }
    }
    class ToWsMessage {
        constructor(from_id, data) {
            this.from_id = from_id;
            this.data = data;
        }
        static fromStringMessage(data) {
            let msg = JSON.parse(data);
            return new ToWsMessage(msg.from_id, new StorageMessage(msg.data.connection_id, msg.data.message));
        }
    }
    class FromWsMessage {
        constructor(to_id, data) {
            this.to_ids = to_id;
            this.data = data;
        }
        static fromStringMessage(data) {
            let msg = JSON.parse(data);
            return new FromWsMessage(msg.to_ids, new StorageMessage(msg.data.connection_id, msg.data.message));
        }
    }
    class StorageMessage {
        constructor(connection_id, message) {
            this.connection_id = connection_id;
            this.message = message;
        }
        static fromStringMessage(data) {
            const msg = JSON.parse(data);
            return new StorageMessage(msg.connection_id, msg.message);
        }
    }

    var AbandonedCallInfoClosedResult;
    (function (AbandonedCallInfoClosedResult) {
        AbandonedCallInfoClosedResult["SUCCESS"] = "SUCCESS";
        AbandonedCallInfoClosedResult["DELETED_BY_AGENT"] = "DELETED_BY_AGENT";
        AbandonedCallInfoClosedResult["EXPIRED"] = "EXPIRED";
        AbandonedCallInfoClosedResult["RETRY_EXCEEDED"] = "RETRY_EXCEEDED";
        AbandonedCallInfoClosedResult["CONTACT_RECALL"] = "CONTACT_RECALL";
        AbandonedCallInfoClosedResult["SUCCESS_FROM_CALLBACK"] = "SUCCESS_FROM_CALLBACK";
        AbandonedCallInfoClosedResult["DELETED_BY_AGENT_FROM_CALLBACK"] = "DELETED_BY_AGENT_FROM_CALLBACK";
    })(AbandonedCallInfoClosedResult || (AbandonedCallInfoClosedResult = {}));
    var AbandonedCallInfoStatus;
    (function (AbandonedCallInfoStatus) {
        AbandonedCallInfoStatus["NEW"] = "NEW";
        AbandonedCallInfoStatus["UNLOCKED"] = "UNLOCKED";
        AbandonedCallInfoStatus["LOCKED"] = "LOCKED";
        AbandonedCallInfoStatus["CLOSED"] = "CLOSED";
    })(AbandonedCallInfoStatus || (AbandonedCallInfoStatus = {}));
    var AccessPattern;
    (function (AccessPattern) {
        AccessPattern["ALWAYS_NULL"] = "ALWAYS_NULL";
        AccessPattern["CONSTANT"] = "CONSTANT";
        AccessPattern["DYNAMIC"] = "DYNAMIC";
    })(AccessPattern || (AccessPattern = {}));
    var AccessTokenState;
    (function (AccessTokenState) {
        AccessTokenState["ACTIVE"] = "ACTIVE";
        AccessTokenState["EXPIRED"] = "EXPIRED";
        AccessTokenState["ERROR"] = "ERROR";
    })(AccessTokenState || (AccessTokenState = {}));
    var ActionToDoType;
    (function (ActionToDoType) {
        ActionToDoType["DIAL"] = "DIAL";
        ActionToDoType["BACK_PO"] = "BACK_PO";
        ActionToDoType["VOICEMAIL"] = "VOICEMAIL";
        ActionToDoType["HANGUP"] = "HANGUP";
        ActionToDoType["PLAY"] = "PLAY";
    })(ActionToDoType || (ActionToDoType = {}));
    var AddressBookContactAddressType;
    (function (AddressBookContactAddressType) {
        AddressBookContactAddressType["MAIN"] = "MAIN";
        AddressBookContactAddressType["OTHER"] = "OTHER";
    })(AddressBookContactAddressType || (AddressBookContactAddressType = {}));
    var AddressBookContactForgottenStatus;
    (function (AddressBookContactForgottenStatus) {
        AddressBookContactForgottenStatus["NONE"] = "NONE";
        AddressBookContactForgottenStatus["WAIT"] = "WAIT";
        AddressBookContactForgottenStatus["RUN"] = "RUN";
        AddressBookContactForgottenStatus["ERR"] = "ERR";
        AddressBookContactForgottenStatus["END"] = "END";
    })(AddressBookContactForgottenStatus || (AddressBookContactForgottenStatus = {}));
    var AddressBookContactMailType;
    (function (AddressBookContactMailType) {
        AddressBookContactMailType["INTERNET_WORK"] = "INTERNET_WORK";
        AddressBookContactMailType["INTERNET_HOME"] = "INTERNET_HOME";
    })(AddressBookContactMailType || (AddressBookContactMailType = {}));
    var AddressBookContactNumberType;
    (function (AddressBookContactNumberType) {
        AddressBookContactNumberType["FAX"] = "FAX";
        AddressBookContactNumberType["HOME"] = "HOME";
        AddressBookContactNumberType["CELL"] = "CELL";
        AddressBookContactNumberType["WORK"] = "WORK";
        AddressBookContactNumberType["CELL_WORK"] = "CELL_WORK";
        AddressBookContactNumberType["FAX_WORK"] = "FAX_WORK";
        AddressBookContactNumberType["FAX_HOME"] = "FAX_HOME";
        AddressBookContactNumberType["CELL_HOME"] = "CELL_HOME";
        AddressBookContactNumberType["MAIN"] = "MAIN";
        AddressBookContactNumberType["OTHER"] = "OTHER";
    })(AddressBookContactNumberType || (AddressBookContactNumberType = {}));
    var AddressBookContactType;
    (function (AddressBookContactType) {
        AddressBookContactType["USER"] = "USER";
        AddressBookContactType["REMOTE_USER"] = "REMOTE_USER";
        AddressBookContactType["SERVICE"] = "SERVICE";
        AddressBookContactType["SERVICE_CODE"] = "SERVICE_CODE";
        AddressBookContactType["SHORT_NUMBER"] = "SHORT_NUMBER";
        AddressBookContactType["EXTERNAL_ITEM"] = "EXTERNAL_ITEM";
        AddressBookContactType["EXTERNAL_ORGANIZATION"] = "EXTERNAL_ORGANIZATION";
        AddressBookContactType["PERSONAL_ITEM"] = "PERSONAL_ITEM";
        AddressBookContactType["UNKNOWN"] = "UNKNOWN";
        AddressBookContactType["MULTIPLE"] = "MULTIPLE";
        AddressBookContactType["MEETING"] = "MEETING";
        AddressBookContactType["ERROR"] = "ERROR";
        AddressBookContactType["DELAYED"] = "DELAYED";
        AddressBookContactType["ANONYMOUS"] = "ANONYMOUS";
    })(AddressBookContactType || (AddressBookContactType = {}));
    var AddressBookContactWebType;
    (function (AddressBookContactWebType) {
        AddressBookContactWebType["WORK"] = "WORK";
        AddressBookContactWebType["HOME"] = "HOME";
    })(AddressBookContactWebType || (AddressBookContactWebType = {}));
    var AddressBookField;
    (function (AddressBookField) {
        AddressBookField["img"] = "img";
        AddressBookField["number"] = "number";
        AddressBookField["email"] = "email";
        AddressBookField["webLink"] = "webLink";
        AddressBookField["note"] = "note";
        AddressBookField["department"] = "department";
        AddressBookField["street"] = "street";
        AddressBookField["city"] = "city";
        AddressBookField["district"] = "district";
        AddressBookField["cap"] = "cap";
        AddressBookField["country"] = "country";
        AddressBookField["site"] = "site";
        AddressBookField["category"] = "category";
        AddressBookField["company"] = "company";
        AddressBookField["vip"] = "vip";
        AddressBookField["name"] = "name";
        AddressBookField["surname"] = "surname";
        AddressBookField["otherName"] = "otherName";
        AddressBookField["role"] = "role";
        AddressBookField["customField"] = "customField";
        AddressBookField["priority"] = "priority";
    })(AddressBookField || (AddressBookField = {}));
    var AddressBookFieldKey;
    (function (AddressBookFieldKey) {
        AddressBookFieldKey["UID"] = "UID";
        AddressBookFieldKey["N"] = "N";
        AddressBookFieldKey["ORG"] = "ORG";
        AddressBookFieldKey["RELATED"] = "RELATED";
        AddressBookFieldKey["ADR"] = "ADR";
        AddressBookFieldKey["CATEGORIES"] = "CATEGORIES";
        AddressBookFieldKey["NOTE"] = "NOTE";
        AddressBookFieldKey["X_TELENIA_VIP"] = "X-TELENIA-VIP";
        AddressBookFieldKey["X_TELENIA_SITE"] = "X-TELENIA-SITE";
        AddressBookFieldKey["X_TELENIA_ROLE"] = "X-TELENIA-ROLE";
        AddressBookFieldKey["X_TELENIA_CUSTOM_A"] = "X-TELENIA-CUSTOM-A";
        AddressBookFieldKey["X_TELENIA_CUSTOM_B"] = "X-TELENIA-CUSTOM-B";
        AddressBookFieldKey["X_TELENIA_CUSTOM_C"] = "X-TELENIA-CUSTOM-C";
        AddressBookFieldKey["X_TELENIA_CUSTOM_D"] = "X-TELENIA-CUSTOM-D";
        AddressBookFieldKey["X_TELENIA_CUSTOM_E"] = "X-TELENIA-CUSTOM-E";
        AddressBookFieldKey["X_TELENIA_CUSTOM_F"] = "X-TELENIA-CUSTOM-F";
        AddressBookFieldKey["X_TELENIA_CUSTOM_G"] = "X-TELENIA-CUSTOM-G";
        AddressBookFieldKey["X_TELENIA_CUSTOM_H"] = "X-TELENIA-CUSTOM-H";
        AddressBookFieldKey["X_TELENIA_CUSTOM_I"] = "X-TELENIA-CUSTOM-I";
        AddressBookFieldKey["X_TELENIA_CUSTOM_J"] = "X-TELENIA-CUSTOM-J";
        AddressBookFieldKey["X_TELENIA_BACKEND_CONFIG_NAME"] = "X-TELENIA-BACKEND-CONFIG-NAME";
        AddressBookFieldKey["TEL"] = "TEL";
        AddressBookFieldKey["EMAIL"] = "EMAIL";
        AddressBookFieldKey["KIND"] = "KIND";
        AddressBookFieldKey["URL"] = "URL";
        AddressBookFieldKey["X_TELENIA_NOTE_AGENT"] = "X-TELENIA-NOTE-AGENT";
        AddressBookFieldKey["X_TELENIA_ACCEPT_CENSUS"] = "X-TELENIA-ACCEPT-CENSUS";
        AddressBookFieldKey["X_TELENIA_PRIORITY"] = "X-TELENIA-PRIORITY";
        AddressBookFieldKey["X_TELENIA_CUSTOMER_CODE"] = "X-TELENIA-CUSTOMER-CODE";
        AddressBookFieldKey["X_TELENIA_FORGOTTEN_CONTACT"] = "X-TELENIA-FORGOTTEN-CONTACT";
        AddressBookFieldKey["X_TELENIA_IS_IMPERSONAL"] = "X-TELENIA-IS-IMPERSONAL";
    })(AddressBookFieldKey || (AddressBookFieldKey = {}));
    var AddressBookFieldType;
    (function (AddressBookFieldType) {
        AddressBookFieldType["MAIN"] = "MAIN";
        AddressBookFieldType["WORK"] = "WORK";
        AddressBookFieldType["CELL"] = "CELL";
        AddressBookFieldType["HOME"] = "HOME";
        AddressBookFieldType["NONE"] = "NONE";
        AddressBookFieldType["FAX"] = "FAX";
    })(AddressBookFieldType || (AddressBookFieldType = {}));
    var AddressBookSearchMode;
    (function (AddressBookSearchMode) {
        AddressBookSearchMode["EQUAL"] = "EQUAL";
        AddressBookSearchMode["LIKE"] = "LIKE";
        AddressBookSearchMode["START_WITH"] = "START_WITH";
        AddressBookSearchMode["END_WITH"] = "END_WITH";
    })(AddressBookSearchMode || (AddressBookSearchMode = {}));
    var AddressBookSourceOriginType;
    (function (AddressBookSourceOriginType) {
        AddressBookSourceOriginType["SOURCE_SYNC"] = "SOURCE_SYNC";
        AddressBookSourceOriginType["DIRECT_SYNC"] = "DIRECT_SYNC";
        AddressBookSourceOriginType["T4YOU_USER_AGENT"] = "T4YOU_USER_AGENT";
        AddressBookSourceOriginType["MC0"] = "MC0";
        AddressBookSourceOriginType["MC1"] = "MC1";
        AddressBookSourceOriginType["MC2"] = "MC2";
        AddressBookSourceOriginType["MC3"] = "MC3";
        AddressBookSourceOriginType["MC1000"] = "MC1000";
        AddressBookSourceOriginType["MC1001"] = "MC1001";
        AddressBookSourceOriginType["MC1002"] = "MC1002";
        AddressBookSourceOriginType["MC1003"] = "MC1003";
        AddressBookSourceOriginType["MC1004"] = "MC1004";
        AddressBookSourceOriginType["MC1005"] = "MC1005";
    })(AddressBookSourceOriginType || (AddressBookSourceOriginType = {}));
    var AddressBookType;
    (function (AddressBookType) {
        AddressBookType["PERSONAL"] = "PERSONAL";
        AddressBookType["EXTERNAL"] = "EXTERNAL";
        AddressBookType["INTERNAL"] = "INTERNAL";
    })(AddressBookType || (AddressBookType = {}));
    var AddressBookWritePermission;
    (function (AddressBookWritePermission) {
        AddressBookWritePermission["ENABLED"] = "ENABLED";
        AddressBookWritePermission["DISABLED"] = "DISABLED";
        AddressBookWritePermission["ENABLED_ON_NOSYNC"] = "ENABLED_ON_NOSYNC";
    })(AddressBookWritePermission || (AddressBookWritePermission = {}));
    var AddressbookField;
    (function (AddressbookField) {
        AddressbookField["N"] = "N";
        AddressbookField["FN"] = "FN";
        AddressbookField["ORG"] = "ORG";
        AddressbookField["ADR"] = "ADR";
        AddressbookField["CATEGORIES"] = "CATEGORIES";
        AddressbookField["NOTE"] = "NOTE";
        AddressbookField["TEL"] = "TEL";
        AddressbookField["EMAIL"] = "EMAIL";
        AddressbookField["URL"] = "URL";
        AddressbookField["RELATED"] = "RELATED";
        AddressbookField["KIND"] = "KIND";
        AddressbookField["TELENIA_NOTE_AGENT"] = "TELENIA_NOTE_AGENT";
        AddressbookField["TELENIA_NOTE_AGENT_LAST_UPDATE"] = "TELENIA_NOTE_AGENT_LAST_UPDATE";
        AddressbookField["TELENIA_NOTE_AGENT_USER_UPDATE"] = "TELENIA_NOTE_AGENT_USER_UPDATE";
        AddressbookField["TELENIA_NOTE_AGENT_MODIFIED"] = "TELENIA_NOTE_AGENT_MODIFIED";
        AddressbookField["TELENIA_VCARD_ORIGIN"] = "TELENIA_VCARD_ORIGIN";
        AddressbookField["TELENIA_VIP"] = "TELENIA_VIP";
        AddressbookField["TELENIA_SITE"] = "TELENIA_SITE";
        AddressbookField["TELENIA_ROLE"] = "TELENIA_ROLE";
        AddressbookField["TELENIA_CUSTOM_01"] = "TELENIA_CUSTOM_01";
        AddressbookField["TELENIA_CUSTOM_02"] = "TELENIA_CUSTOM_02";
        AddressbookField["TELENIA_CUSTOM_03"] = "TELENIA_CUSTOM_03";
        AddressbookField["TELENIA_CUSTOM_04"] = "TELENIA_CUSTOM_04";
        AddressbookField["TELENIA_CUSTOM_05"] = "TELENIA_CUSTOM_05";
        AddressbookField["TELENIA_CUSTOM_06"] = "TELENIA_CUSTOM_06";
        AddressbookField["TELENIA_CUSTOM_07"] = "TELENIA_CUSTOM_07";
        AddressbookField["TELENIA_CUSTOM_08"] = "TELENIA_CUSTOM_08";
        AddressbookField["TELENIA_CUSTOM_09"] = "TELENIA_CUSTOM_09";
        AddressbookField["TELENIA_CUSTOM_10"] = "TELENIA_CUSTOM_10";
        AddressbookField["TELENIA_CHANNEL_PHONE"] = "TELENIA_CHANNEL_PHONE";
        AddressbookField["TELENIA_CHANNEL_CALLBACK"] = "TELENIA_CHANNEL_CALLBACK";
        AddressbookField["TELENIA_CHANNEL_VIDEO"] = "TELENIA_CHANNEL_VIDEO";
        AddressbookField["TELENIA_CHANNEL_MAIL"] = "TELENIA_CHANNEL_MAIL";
        AddressbookField["TELENIA_CHANNEL_MAIL_ORG"] = "TELENIA_CHANNEL_MAIL_ORG";
        AddressbookField["TELENIA_CHANNEL_LIVEHELP"] = "TELENIA_CHANNEL_LIVEHELP";
        AddressbookField["TELENIA_CHANNEL_WHATSAPP_TWILIO"] = "TELENIA_CHANNEL_WHATSAPP_TWILIO";
        AddressbookField["TELENIA_CHANNEL_CHAT"] = "TELENIA_CHANNEL_CHAT";
        AddressbookField["TELENIA_CHANNEL_1"] = "TELENIA_CHANNEL_1";
        AddressbookField["TELENIA_CHANNEL_2"] = "TELENIA_CHANNEL_2";
        AddressbookField["TELENIA_CHANNEL_3"] = "TELENIA_CHANNEL_3";
        AddressbookField["TELENIA_BACKEND_CONFIG_NAME"] = "TELENIA_BACKEND_CONFIG_NAME";
        AddressbookField["TELENIA_PERSISTENT_INTERACTIONS"] = "TELENIA_PERSISTENT_INTERACTIONS";
        AddressbookField["TELENIA_ACCEPT_CENSUS"] = "TELENIA_ACCEPT_CENSUS";
        AddressbookField["TELENIA_CUSTOMER_CODE"] = "TELENIA_CUSTOMER_CODE";
        AddressbookField["TELENIA_LAST_A_TYPE"] = "TELENIA_LAST_A_TYPE";
        AddressbookField["TELENIA_NPS"] = "TELENIA_NPS";
        AddressbookField["TELENIA_SOURCE_ORIGIN_TYPE"] = "TELENIA_SOURCE_ORIGIN_TYPE";
        AddressbookField["TELENIA_PRIORITY"] = "TELENIA_PRIORITY";
        AddressbookField["TELENIA_IMPERSONAL"] = "TELENIA_IMPERSONAL";
        AddressbookField["TELENIA_FORGOTTEN_CONTACT"] = "TELENIA_FORGOTTEN_CONTACT";
    })(AddressbookField || (AddressbookField = {}));
    var AddressbookFieldType;
    (function (AddressbookFieldType) {
        AddressbookFieldType["FAX"] = "FAX";
        AddressbookFieldType["HOME"] = "HOME";
        AddressbookFieldType["CELL"] = "CELL";
        AddressbookFieldType["WORK"] = "WORK";
        AddressbookFieldType["CELL_WORK"] = "CELL_WORK";
        AddressbookFieldType["FAX_WORK"] = "FAX_WORK";
        AddressbookFieldType["FAX_HOME"] = "FAX_HOME";
        AddressbookFieldType["CELL_HOME"] = "CELL_HOME";
        AddressbookFieldType["MAIN"] = "MAIN";
        AddressbookFieldType["NONE"] = "NONE";
        AddressbookFieldType["OTHER"] = "OTHER";
        AddressbookFieldType["INTERNET_WORK"] = "INTERNET_WORK";
        AddressbookFieldType["INTERNET_HOME"] = "INTERNET_HOME";
    })(AddressbookFieldType || (AddressbookFieldType = {}));
    var AlarmIssuedDetailStatus;
    (function (AlarmIssuedDetailStatus) {
        AlarmIssuedDetailStatus["IDLE"] = "IDLE";
        AlarmIssuedDetailStatus["TO_RUN"] = "TO_RUN";
        AlarmIssuedDetailStatus["RUNNING"] = "RUNNING";
        AlarmIssuedDetailStatus["WAITING_FEEDBACK"] = "WAITING_FEEDBACK";
        AlarmIssuedDetailStatus["BUSY"] = "BUSY";
        AlarmIssuedDetailStatus["NOANSWER"] = "NOANSWER";
        AlarmIssuedDetailStatus["ANSWERED"] = "ANSWERED";
        AlarmIssuedDetailStatus["ERROR"] = "ERROR";
        AlarmIssuedDetailStatus["ERROR_CALLING"] = "ERROR_CALLING";
        AlarmIssuedDetailStatus["ERROR_CONGESTION"] = "ERROR_CONGESTION";
        AlarmIssuedDetailStatus["ERROR_CHANUNAVAIL"] = "ERROR_CHANUNAVAIL";
        AlarmIssuedDetailStatus["ERROR_NOFEEDBACK"] = "ERROR_NOFEEDBACK";
        AlarmIssuedDetailStatus["DELETED"] = "DELETED";
        AlarmIssuedDetailStatus["SKIPPED"] = "SKIPPED";
        AlarmIssuedDetailStatus["UNPROCESSED"] = "UNPROCESSED";
    })(AlarmIssuedDetailStatus || (AlarmIssuedDetailStatus = {}));
    var AlarmIssuedDetailType;
    (function (AlarmIssuedDetailType) {
        AlarmIssuedDetailType["MAIL"] = "MAIL";
        AlarmIssuedDetailType["SMS"] = "SMS";
        AlarmIssuedDetailType["CALL"] = "CALL";
        AlarmIssuedDetailType["CHAT"] = "CHAT";
        AlarmIssuedDetailType["SNMP"] = "SNMP";
        AlarmIssuedDetailType["WEBPORTAL"] = "WEBPORTAL";
        AlarmIssuedDetailType["ALL"] = "ALL";
    })(AlarmIssuedDetailType || (AlarmIssuedDetailType = {}));
    var AllowedAction;
    (function (AllowedAction) {
        AllowedAction["ADD"] = "ADD";
        AllowedAction["ENABLE"] = "ENABLE";
        AllowedAction["DISABLE"] = "DISABLE";
        AllowedAction["COPY"] = "COPY";
        AllowedAction["UPDATE"] = "UPDATE";
        AllowedAction["DELETE"] = "DELETE";
    })(AllowedAction || (AllowedAction = {}));
    var ApiVersionEnum;
    (function (ApiVersionEnum) {
        ApiVersionEnum["SUPPORT"] = "SUPPORT";
        ApiVersionEnum["SUPPORT_WEBAPI"] = "SUPPORT_WEBAPI";
        ApiVersionEnum["ZAMMAD_WEBAPI"] = "ZAMMAD_WEBAPI";
    })(ApiVersionEnum || (ApiVersionEnum = {}));
    var AppFeature;
    (function (AppFeature) {
        AppFeature["ACK"] = "ACK";
        AppFeature["DEVICE_EMBEDDED"] = "DEVICE_EMBEDDED";
        AppFeature["FAVS"] = "FAVS";
    })(AppFeature || (AppFeature = {}));
    var AppStatusOnConnect;
    (function (AppStatusOnConnect) {
        AppStatusOnConnect["terminate"] = "terminate";
        AppStatusOnConnect["login"] = "login";
        AppStatusOnConnect["background"] = "background";
    })(AppStatusOnConnect || (AppStatusOnConnect = {}));
    var ArticleSender;
    (function (ArticleSender) {
        ArticleSender["Agent"] = "Agent";
        ArticleSender["Customer"] = "Customer";
        ArticleSender["System"] = "System";
    })(ArticleSender || (ArticleSender = {}));
    var ArticleType;
    (function (ArticleType) {
        ArticleType["email"] = "email";
        ArticleType["sms"] = "sms";
        ArticleType["chat"] = "chat";
        ArticleType["fax"] = "fax";
        ArticleType["phone"] = "phone";
        ArticleType["TWITTER_STATUS"] = "twitter status";
        ArticleType["TWITTER_DIRECT_MESSAGE"] = "twitter direct-message";
        ArticleType["FACEBOOK_FEED_POST"] = "facebook feed post";
        ArticleType["FACEBOOK_FEED_COMMENT"] = "facebook feed comment";
        ArticleType["note"] = "note";
        ArticleType["web"] = "web";
        ArticleType["TELEGRAM_PERSONAL_MESSAGE"] = "telegram personal-message";
    })(ArticleType || (ArticleType = {}));
    var As;
    (function (As) {
        As["PROPERTY"] = "PROPERTY";
        As["WRAPPER_OBJECT"] = "WRAPPER_OBJECT";
        As["WRAPPER_ARRAY"] = "WRAPPER_ARRAY";
        As["EXTERNAL_PROPERTY"] = "EXTERNAL_PROPERTY";
        As["EXISTING_PROPERTY"] = "EXISTING_PROPERTY";
    })(As || (As = {}));
    var AuthServerType;
    (function (AuthServerType) {
        AuthServerType["GOOGLE"] = "GOOGLE";
        AuthServerType["MICROSOFT365"] = "MICROSOFT365";
        AuthServerType["META_FACEBOOK"] = "META_FACEBOOK";
        AuthServerType["GENERIC"] = "GENERIC";
    })(AuthServerType || (AuthServerType = {}));
    var AutoAnswerMode;
    (function (AutoAnswerMode) {
        AutoAnswerMode["DISABLED"] = "DISABLED";
        AutoAnswerMode["BEFORE_POPUP"] = "BEFORE_POPUP";
        AutoAnswerMode["AFTER_POPUP"] = "AFTER_POPUP";
    })(AutoAnswerMode || (AutoAnswerMode = {}));
    var BridgeDeviceType;
    (function (BridgeDeviceType) {
        BridgeDeviceType["WEBCLIENT"] = "WEBCLIENT";
        BridgeDeviceType["APP"] = "APP";
        BridgeDeviceType["PHONE"] = "PHONE";
    })(BridgeDeviceType || (BridgeDeviceType = {}));
    var CCBSResult;
    (function (CCBSResult) {
        CCBSResult["DEFAULT"] = "DEFAULT";
        CCBSResult["CHANUNAVAIL"] = "CHANUNAVAIL";
        CCBSResult["CONGESTION"] = "CONGESTION";
        CCBSResult["NOANSWER"] = "NOANSWER";
        CCBSResult["BUSY"] = "BUSY";
        CCBSResult["ANSWER"] = "ANSWER";
        CCBSResult["CANCEL"] = "CANCEL";
        CCBSResult["DONTCALL"] = "DONTCALL";
        CCBSResult["TORTURE"] = "TORTURE";
        CCBSResult["INVALIDARGS"] = "INVALIDARGS";
        CCBSResult["ERROR"] = "ERROR";
    })(CCBSResult || (CCBSResult = {}));
    var CalendarFrequency;
    (function (CalendarFrequency) {
        CalendarFrequency["SECONDLY"] = "SECONDLY";
        CalendarFrequency["MINUTELY"] = "MINUTELY";
        CalendarFrequency["HOURLY"] = "HOURLY";
        CalendarFrequency["DAILY"] = "DAILY";
        CalendarFrequency["WEEKLY"] = "WEEKLY";
        CalendarFrequency["MONTHLY"] = "MONTHLY";
        CalendarFrequency["YEARLY"] = "YEARLY";
    })(CalendarFrequency || (CalendarFrequency = {}));
    var CalendarWeekDay;
    (function (CalendarWeekDay) {
        CalendarWeekDay["UNKNOWN"] = "UNKNOWN";
        CalendarWeekDay["SUNDAY"] = "SUNDAY";
        CalendarWeekDay["MONDAY"] = "MONDAY";
        CalendarWeekDay["TUESDAY"] = "TUESDAY";
        CalendarWeekDay["WEDNESDAY"] = "WEDNESDAY";
        CalendarWeekDay["THURSDAY"] = "THURSDAY";
        CalendarWeekDay["FRIDAY"] = "FRIDAY";
        CalendarWeekDay["SATURDAY"] = "SATURDAY";
    })(CalendarWeekDay || (CalendarWeekDay = {}));
    var CallDeviceState;
    (function (CallDeviceState) {
        CallDeviceState["INITIALING"] = "INITIALING";
        CallDeviceState["CONNECTED"] = "CONNECTED";
        CallDeviceState["DIALING"] = "DIALING";
        CallDeviceState["RINGING"] = "RINGING";
        CallDeviceState["CALL_CONNECTED"] = "CALL_CONNECTED";
    })(CallDeviceState || (CallDeviceState = {}));
    var CallDirection;
    (function (CallDirection) {
        CallDirection["inbound"] = "inbound";
        CallDirection["outbound"] = "outbound";
    })(CallDirection || (CallDirection = {}));
    var CallFeature;
    (function (CallFeature) {
        CallFeature["ANSWER"] = "ANSWER";
        CallFeature["CANCEL"] = "CANCEL";
        CallFeature["CONFERENCE"] = "CONFERENCE";
        CallFeature["DIAL"] = "DIAL";
        CallFeature["HOLD"] = "HOLD";
        CallFeature["GENERATE_DTMF"] = "GENERATE_DTMF";
        CallFeature["MONITOR_START"] = "MONITOR_START";
        CallFeature["SETCALLDATA"] = "SETCALLDATA";
        CallFeature["TRANSFER_BLIND"] = "TRANSFER_BLIND";
        CallFeature["TRANSFER_ATTENDED"] = "TRANSFER_ATTENDED";
        CallFeature["UNHOLD"] = "UNHOLD";
        CallFeature["MONITOR_STOP"] = "MONITOR_STOP";
        CallFeature["MUTE"] = "MUTE";
        CallFeature["REJECT"] = "REJECT";
        CallFeature["ACCEPT"] = "ACCEPT";
        CallFeature["UNMUTE"] = "UNMUTE";
        CallFeature["UPDATE"] = "UPDATE";
        CallFeature["VIDEO_START"] = "VIDEO_START";
        CallFeature["VIDEO_STOP"] = "VIDEO_STOP";
        CallFeature["SWITCH_TO_GSM"] = "SWITCH_TO_GSM";
        CallFeature["DIAL_ATXFER"] = "DIAL_ATXFER";
        CallFeature["ATXFER_CANCEL"] = "ATXFER_CANCEL";
    })(CallFeature || (CallFeature = {}));
    var CallFowardMode;
    (function (CallFowardMode) {
        CallFowardMode["EMAIL"] = "EMAIL";
        CallFowardMode["SMS"] = "SMS";
        CallFowardMode["ALL"] = "ALL";
    })(CallFowardMode || (CallFowardMode = {}));
    var CallFowardStatus;
    (function (CallFowardStatus) {
        CallFowardStatus["ENABLE_ALL"] = "ENABLE_ALL";
        CallFowardStatus["ENABLE_INTERNAL"] = "ENABLE_INTERNAL";
        CallFowardStatus["ENABLE_EXTERNAL"] = "ENABLE_EXTERNAL";
        CallFowardStatus["DISABLE"] = "DISABLE";
    })(CallFowardStatus || (CallFowardStatus = {}));
    var CallHistoryType;
    (function (CallHistoryType) {
        CallHistoryType["INBOUND"] = "INBOUND";
        CallHistoryType["OUTBOUND"] = "OUTBOUND";
    })(CallHistoryType || (CallHistoryType = {}));
    var CallHistoryWebRTCResult;
    (function (CallHistoryWebRTCResult) {
        CallHistoryWebRTCResult["OK"] = "OK";
        CallHistoryWebRTCResult["ERROR_ICE"] = "ERROR_ICE";
        CallHistoryWebRTCResult["ERROR_DTLS"] = "ERROR_DTLS";
        CallHistoryWebRTCResult["ERROR_MEDIA"] = "ERROR_MEDIA";
        CallHistoryWebRTCResult["ERROR_CONNECTIVITY"] = "ERROR_CONNECTIVITY";
        CallHistoryWebRTCResult["ERROR_BAD_MEDIA"] = "ERROR_BAD_MEDIA";
        CallHistoryWebRTCResult["NO_SMARTWORKING"] = "NO_SMARTWORKING";
    })(CallHistoryWebRTCResult || (CallHistoryWebRTCResult = {}));
    var CallMedia;
    (function (CallMedia) {
        CallMedia["audio"] = "audio";
        CallMedia["video"] = "video";
        CallMedia["desktop"] = "desktop";
        CallMedia["data"] = "data";
    })(CallMedia || (CallMedia = {}));
    var CallMediaFeature;
    (function (CallMediaFeature) {
        CallMediaFeature["MUTE"] = "MUTE";
        CallMediaFeature["UNMUTE"] = "UNMUTE";
        CallMediaFeature["START"] = "START";
        CallMediaFeature["STOP"] = "STOP";
    })(CallMediaFeature || (CallMediaFeature = {}));
    var CallMediaLinkStatus;
    (function (CallMediaLinkStatus) {
        CallMediaLinkStatus["MUTE"] = "MUTE";
        CallMediaLinkStatus["UNMUTE"] = "UNMUTE";
    })(CallMediaLinkStatus || (CallMediaLinkStatus = {}));
    var CallMediaStatus;
    (function (CallMediaStatus) {
        CallMediaStatus["OK"] = "OK";
        CallMediaStatus["ERROR_BAD_MEDIA"] = "ERROR_BAD_MEDIA";
        CallMediaStatus["ERROR_ICE"] = "ERROR_ICE";
        CallMediaStatus["ERROR_DTLS"] = "ERROR_DTLS";
        CallMediaStatus["ERROR_MEDIA"] = "ERROR_MEDIA";
        CallMediaStatus["ERROR_CONNECTIVITY"] = "ERROR_CONNECTIVITY";
    })(CallMediaStatus || (CallMediaStatus = {}));
    var CallPopupMode;
    (function (CallPopupMode) {
        CallPopupMode["DISABLED"] = "DISABLED";
        CallPopupMode["IFRAME"] = "IFRAME";
        CallPopupMode["NEW_TAB"] = "NEW_TAB";
        CallPopupMode["ACTIVEX"] = "ACTIVEX";
    })(CallPopupMode || (CallPopupMode = {}));
    var CallPopupType;
    (function (CallPopupType) {
        CallPopupType["onRing"] = "onRing";
        CallPopupType["onAnswer"] = "onAnswer";
        CallPopupType["onHangup"] = "onHangup";
        CallPopupType["onDemand"] = "onDemand";
        CallPopupType["webClientOpenNewTab"] = "webClientOpenNewTab";
        CallPopupType["webClientTabLabel"] = "webClientTabLabel";
        CallPopupType["custom"] = "custom";
    })(CallPopupType || (CallPopupType = {}));
    var CallRecordingFileType;
    (function (CallRecordingFileType) {
        CallRecordingFileType["WAV"] = "wav";
        CallRecordingFileType["MP3"] = "mp3";
        CallRecordingFileType["WAVE"] = "wave";
        CallRecordingFileType["ZIP"] = "zip";
    })(CallRecordingFileType || (CallRecordingFileType = {}));
    var CallResultCodeCallbackState;
    (function (CallResultCodeCallbackState) {
        CallResultCodeCallbackState["DONE"] = "DONE";
        CallResultCodeCallbackState["RETRY"] = "RETRY";
    })(CallResultCodeCallbackState || (CallResultCodeCallbackState = {}));
    var CallResultStatusType;
    (function (CallResultStatusType) {
        CallResultStatusType["inbound"] = "inbound";
        CallResultStatusType["outbound"] = "outbound";
        CallResultStatusType["abandoned_call"] = "abandoned_call";
        CallResultStatusType["callback_call"] = "callback_call";
    })(CallResultStatusType || (CallResultStatusType = {}));
    var CallState;
    (function (CallState) {
        CallState["NEW_INBOUND"] = "NEW_INBOUND";
        CallState["NEW_OUTBOUND"] = "NEW_OUTBOUND";
        CallState["CONNECTED"] = "CONNECTED";
        CallState["CONFERENCED"] = "CONFERENCED";
        CallState["HOLD"] = "HOLD";
        CallState["IDLE"] = "IDLE";
        CallState["HOLD_PENDING_TRANSFER"] = "HOLD_PENDING_TRANSFER";
        CallState["HOLD_PENDING_SIP"] = "HOLD_PENDING_SIP";
    })(CallState || (CallState = {}));
    var CallStatus;
    (function (CallStatus) {
        CallStatus["ACTIVE"] = "ACTIVE";
        CallStatus["ON_QUEUE"] = "ON_QUEUE";
        CallStatus["AGENT"] = "AGENT";
        CallStatus["OUT_OF_QUEUE"] = "OUT_OF_QUEUE";
        CallStatus["ABANDONED"] = "ABANDONED";
    })(CallStatus || (CallStatus = {}));
    var CallbackRequestCloseResult;
    (function (CallbackRequestCloseResult) {
        CallbackRequestCloseResult["SUCCESS"] = "SUCCESS";
        CallbackRequestCloseResult["DELETED_BY_AGENT"] = "DELETED_BY_AGENT";
        CallbackRequestCloseResult["EXPIRED"] = "EXPIRED";
        CallbackRequestCloseResult["RETRY_EXCEEDED"] = "RETRY_EXCEEDED";
        CallbackRequestCloseResult["CONTACT_RECALL"] = "CONTACT_RECALL";
        CallbackRequestCloseResult["SUCCESS_FROM_ABANDONED"] = "SUCCESS_FROM_ABANDONED";
        CallbackRequestCloseResult["DELETED_BY_AGENT_FROM_ABANDONED"] = "DELETED_BY_AGENT_FROM_ABANDONED";
    })(CallbackRequestCloseResult || (CallbackRequestCloseResult = {}));
    var CallbackRequestStatus;
    (function (CallbackRequestStatus) {
        CallbackRequestStatus["NEW"] = "NEW";
        CallbackRequestStatus["UNLOCKED"] = "UNLOCKED";
        CallbackRequestStatus["LOCKED"] = "LOCKED";
        CallbackRequestStatus["CLOSED"] = "CLOSED";
    })(CallbackRequestStatus || (CallbackRequestStatus = {}));
    var CallbackRequestType;
    (function (CallbackRequestType) {
        CallbackRequestType["IVR"] = "IVR";
        CallbackRequestType["WEB"] = "WEB";
    })(CallbackRequestType || (CallbackRequestType = {}));
    var CallbackTypeResultCodeList;
    (function (CallbackTypeResultCodeList) {
        CallbackTypeResultCodeList["MANUAL"] = "MANUAL";
        CallbackTypeResultCodeList["COURTESY"] = "COURTESY";
    })(CallbackTypeResultCodeList || (CallbackTypeResultCodeList = {}));
    var CampaignPhoneChannelType;
    (function (CampaignPhoneChannelType) {
        CampaignPhoneChannelType["AVAILABLE"] = "AVAILABLE";
        CampaignPhoneChannelType["PRESENT"] = "PRESENT";
    })(CampaignPhoneChannelType || (CampaignPhoneChannelType = {}));
    var CampaignStatusValue;
    (function (CampaignStatusValue) {
        CampaignStatusValue["DISABLE"] = "DISABLE";
        CampaignStatusValue["ACTIVE"] = "ACTIVE";
        CampaignStatusValue["ACTIVE_QUEUED"] = "ACTIVE_QUEUED";
        CampaignStatusValue["EVALUATING_RESULT"] = "EVALUATING_RESULT";
        CampaignStatusValue["PENDING"] = "PENDING";
        CampaignStatusValue["STOP"] = "STOP";
        CampaignStatusValue["END"] = "END";
        CampaignStatusValue["ERROR"] = "ERROR";
        CampaignStatusValue["STOPPING"] = "STOPPING";
        CampaignStatusValue["LOADING_DATA"] = "LOADING_DATA";
        CampaignStatusValue["SCHEDULED"] = "SCHEDULED";
    })(CampaignStatusValue || (CampaignStatusValue = {}));
    var CampaignType;
    (function (CampaignType) {
        CampaignType["CALL"] = "CALL";
        CampaignType["MASSIVE_SMS"] = "MASSIVE_SMS";
        CampaignType["SMS"] = "SMS";
        CampaignType["MASSIVE_MAIL"] = "MASSIVE_MAIL";
        CampaignType["MAIL"] = "MAIL";
        CampaignType["APP"] = "APP";
    })(CampaignType || (CampaignType = {}));
    var CancelReason;
    (function (CancelReason) {
        CancelReason["BUSY"] = "BUSY";
        CancelReason["REJECTED"] = "REJECTED";
        CancelReason["NORMAL_CLEARING"] = "NORMAL_CLEARING";
    })(CancelReason || (CancelReason = {}));
    var ChannelInfoImprovementDataType;
    (function (ChannelInfoImprovementDataType) {
        ChannelInfoImprovementDataType["STRING"] = "STRING";
        ChannelInfoImprovementDataType["DATE"] = "DATE";
        ChannelInfoImprovementDataType["CHECKBOX"] = "CHECKBOX";
    })(ChannelInfoImprovementDataType || (ChannelInfoImprovementDataType = {}));
    var ChatChannelEventMessageStatus;
    (function (ChatChannelEventMessageStatus) {
        ChatChannelEventMessageStatus["WROTE"] = "WROTE";
        ChatChannelEventMessageStatus["COMPOSING"] = "COMPOSING";
        ChatChannelEventMessageStatus["IDLE"] = "IDLE";
    })(ChatChannelEventMessageStatus || (ChatChannelEventMessageStatus = {}));
    var ChatHistoryType;
    (function (ChatHistoryType) {
        ChatHistoryType["INBOUND"] = "INBOUND";
        ChatHistoryType["OUTBOUND"] = "OUTBOUND";
    })(ChatHistoryType || (ChatHistoryType = {}));
    var ChatStatus;
    (function (ChatStatus) {
        ChatStatus["ACTIVE"] = "ACTIVE";
        ChatStatus["ON_DISTRIBUTION"] = "ON_DISTRIBUTION";
        ChatStatus["ON_AGENT"] = "ON_AGENT";
        ChatStatus["ON_QUEUE"] = "ON_QUEUE";
        ChatStatus["AGENT"] = "AGENT";
        ChatStatus["OUT_OF_QUEUE"] = "OUT_OF_QUEUE";
        ChatStatus["ABANDONED"] = "ABANDONED";
        ChatStatus["ERROR"] = "ERROR";
        ChatStatus["TRANSFER"] = "TRANSFER";
        ChatStatus["TERMINATED"] = "TERMINATED";
        ChatStatus["ANSWERED"] = "ANSWERED";
        ChatStatus["ANSWERED_TRANSFER"] = "ANSWERED_TRANSFER";
    })(ChatStatus || (ChatStatus = {}));
    var ClientCommandRequest;
    (function (ClientCommandRequest) {
        ClientCommandRequest["DIAL"] = "DIAL";
        ClientCommandRequest["SEND_FEEDBACK"] = "SEND_FEEDBACK";
        ClientCommandRequest["ANSWER"] = "ANSWER";
        ClientCommandRequest["HOLD"] = "HOLD";
        ClientCommandRequest["UNHOLD"] = "UNHOLD";
        ClientCommandRequest["CANCEL"] = "CANCEL";
        ClientCommandRequest["ATTENDED_TRANSFER"] = "ATTENDED_TRANSFER";
        ClientCommandRequest["BLIND_TRANSFER"] = "BLIND_TRANSFER";
        ClientCommandRequest["SEND_DTMF"] = "SEND_DTMF";
        ClientCommandRequest["ATXFER_GENERIC_DEVICE"] = "ATXFER_GENERIC_DEVICE";
        ClientCommandRequest["CANCEL_ON_TRANSFER_GENERIC_DEVICE"] = "CANCEL_ON_TRANSFER_GENERIC_DEVICE";
        ClientCommandRequest["SUPPORT_VERSION"] = "SUPPORT_VERSION";
    })(ClientCommandRequest || (ClientCommandRequest = {}));
    var ClientCommandResult;
    (function (ClientCommandResult) {
        ClientCommandResult["OK"] = "OK";
        ClientCommandResult["RECEIVED"] = "RECEIVED";
        ClientCommandResult["FAILED"] = "FAILED";
        ClientCommandResult["TIMEOUT_EXPIRED"] = "TIMEOUT_EXPIRED";
        ClientCommandResult["FEATURE_UNSUPPORTED"] = "FEATURE_UNSUPPORTED";
        ClientCommandResult["NO_CLIENT"] = "NO_CLIENT";
    })(ClientCommandResult || (ClientCommandResult = {}));
    var ClientParamType;
    (function (ClientParamType) {
        ClientParamType["NUMBER"] = "NUMBER";
        ClientParamType["STRING"] = "STRING";
        ClientParamType["BOOLEAN"] = "BOOLEAN";
    })(ClientParamType || (ClientParamType = {}));
    var ClientStatus;
    (function (ClientStatus) {
        ClientStatus["ACTIVE"] = "ACTIVE";
        ClientStatus["ACTIVATING"] = "ACTIVATING";
        ClientStatus["INACTIVE"] = "INACTIVE";
        ClientStatus["DISCONNETING"] = "DISCONNETING";
    })(ClientStatus || (ClientStatus = {}));
    var Condition;
    (function (Condition) {
        Condition["ticketAction"] = "ticket.action";
        Condition["ticketStateId"] = "ticket.state_id";
        Condition["ticketOwnerId"] = "ticket.owner_id";
        Condition["ticketCustomerId"] = "ticket.customer_id";
        Condition["ticketGroupId"] = "ticket.group_id";
        Condition["articleTypeId"] = "article.type_id";
        Condition["articleSenderId"] = "article.sender_id";
    })(Condition || (Condition = {}));
    var ConfigurationPermission;
    (function (ConfigurationPermission) {
        ConfigurationPermission["DEFAULT"] = "DEFAULT";
        ConfigurationPermission["NONE"] = "NONE";
        ConfigurationPermission["READ"] = "READ";
        ConfigurationPermission["READ_WRITE"] = "READ_WRITE";
        ConfigurationPermission["READ_ADD"] = "READ_ADD";
        ConfigurationPermission["READ_WRITE_ADD"] = "READ_WRITE_ADD";
    })(ConfigurationPermission || (ConfigurationPermission = {}));
    var ConnectionType;
    (function (ConnectionType) {
        ConnectionType["APP_IOS_2"] = "APP_IOS_2";
        ConnectionType["APP_ANDROID_2"] = "APP_ANDROID_2";
        ConnectionType["APP_IOS"] = "APP_IOS";
        ConnectionType["APP_ANDROID"] = "APP_ANDROID";
        ConnectionType["EXE_CLIENT"] = "EXE_CLIENT";
        ConnectionType["WEB"] = "WEB";
        ConnectionType["WEB_FOR_APP"] = "WEB_FOR_APP";
    })(ConnectionType || (ConnectionType = {}));
    var Context;
    (function (Context) {
        Context["ENABLE_FROM_PHONE"] = "ENABLE_FROM_PHONE";
        Context["ALWAYS"] = "ALWAYS";
        Context["CHANUNAVAIL"] = "CHANUNAVAIL";
        Context["BUSY"] = "BUSY";
        Context["NOANSWER"] = "NOANSWER";
        Context["NOT_PRESENT"] = "NOT_PRESENT";
    })(Context || (Context = {}));
    var CustomCliType;
    (function (CustomCliType) {
        CustomCliType["CUST"] = "CUST";
        CustomCliType["SERV"] = "SERV";
    })(CustomCliType || (CustomCliType = {}));
    var CustomFieldConfigType;
    (function (CustomFieldConfigType) {
        CustomFieldConfigType["TEXT"] = "TEXT";
        CustomFieldConfigType["LIST"] = "LIST";
    })(CustomFieldConfigType || (CustomFieldConfigType = {}));
    var CustomFieldType;
    (function (CustomFieldType) {
        CustomFieldType["SELECT"] = "SELECT";
        CustomFieldType["TEXT"] = "TEXT";
    })(CustomFieldType || (CustomFieldType = {}));
    var CustomTicketFieldConfigType;
    (function (CustomTicketFieldConfigType) {
        CustomTicketFieldConfigType["TEXT"] = "TEXT";
        CustomTicketFieldConfigType["TEXTAREA"] = "TEXTAREA";
        CustomTicketFieldConfigType["HYPERLINK"] = "HYPERLINK";
        CustomTicketFieldConfigType["CHECKBOX"] = "CHECKBOX";
        CustomTicketFieldConfigType["LIST"] = "LIST";
        CustomTicketFieldConfigType["DATE"] = "DATE";
        CustomTicketFieldConfigType["DATETIME"] = "DATETIME";
        CustomTicketFieldConfigType["INTEGER"] = "INTEGER";
        CustomTicketFieldConfigType["DECIMAL"] = "DECIMAL";
        CustomTicketFieldConfigType["REGEX"] = "REGEX";
        CustomTicketFieldConfigType["PHONEBOOK_INTERNAL"] = "PHONEBOOK_INTERNAL";
        CustomTicketFieldConfigType["PHONEBOOK_GLOBAL"] = "PHONEBOOK_GLOBAL";
        CustomTicketFieldConfigType["PHONEBOOK_COMPANY"] = "PHONEBOOK_COMPANY";
        CustomTicketFieldConfigType["PHONEBOOK_CONTACT"] = "PHONEBOOK_CONTACT";
    })(CustomTicketFieldConfigType || (CustomTicketFieldConfigType = {}));
    var CustomerJourneyCallStatus;
    (function (CustomerJourneyCallStatus) {
        CustomerJourneyCallStatus["HANGUP"] = "HANGUP";
        CustomerJourneyCallStatus["CLOSED_BY_SYSTEM"] = "CLOSED_BY_SYSTEM";
        CustomerJourneyCallStatus["CLOSED_WITH_TRANSFER"] = "CLOSED_WITH_TRANSFER";
        CustomerJourneyCallStatus["ANSWERED_CLOSED_BY_CALLER"] = "ANSWERED_CLOSED_BY_CALLER";
        CustomerJourneyCallStatus["ANSWERED_CLOSED_BY_CALLED"] = "ANSWERED_CLOSED_BY_CALLED";
        CustomerJourneyCallStatus["ANSWERED_WITH_BLIND_TRANSFER"] = "ANSWERED_WITH_BLIND_TRANSFER";
        CustomerJourneyCallStatus["ANSWERED_WITH_CONSULTATION_TRANSFER"] = "ANSWERED_WITH_CONSULTATION_TRANSFER";
        CustomerJourneyCallStatus["ERROR"] = "ERROR";
        CustomerJourneyCallStatus["CLOSED_LIMIT_INBOUND"] = "CLOSED_LIMIT_INBOUND";
        CustomerJourneyCallStatus["CLOSED_LIMIT_QUEUE"] = "CLOSED_LIMIT_QUEUE";
        CustomerJourneyCallStatus["CLOSED_NO_SELECTION"] = "CLOSED_NO_SELECTION";
    })(CustomerJourneyCallStatus || (CustomerJourneyCallStatus = {}));
    var CustomerJourneyCallbackStatus;
    (function (CustomerJourneyCallbackStatus) {
        CustomerJourneyCallbackStatus["NEW"] = "NEW";
        CustomerJourneyCallbackStatus["LOCKED"] = "LOCKED";
        CustomerJourneyCallbackStatus["UNLOCKED"] = "UNLOCKED";
        CustomerJourneyCallbackStatus["CLOSED_SUCCESS"] = "CLOSED_SUCCESS";
        CustomerJourneyCallbackStatus["CLOSED_DELETED_BY_AGENT"] = "CLOSED_DELETED_BY_AGENT";
        CustomerJourneyCallbackStatus["CLOSED_EXPIRED"] = "CLOSED_EXPIRED";
        CustomerJourneyCallbackStatus["CLOSED_RETRY_EXCEEDED"] = "CLOSED_RETRY_EXCEEDED";
        CustomerJourneyCallbackStatus["CLOSED_CONTACT_RECALL"] = "CLOSED_CONTACT_RECALL";
        CustomerJourneyCallbackStatus["CLOSED_SUCCESS_FROM_CALLBACK"] = "CLOSED_SUCCESS_FROM_CALLBACK";
        CustomerJourneyCallbackStatus["CLOSED_DELETED_BY_AGENT_FROM_CALLBACK"] = "CLOSED_DELETED_BY_AGENT_FROM_CALLBACK";
        CustomerJourneyCallbackStatus["CLOSED_SUCCESS_FROM_ABANDONED"] = "CLOSED_SUCCESS_FROM_ABANDONED";
        CustomerJourneyCallbackStatus["CLOSED_DELETED_BY_AGENT_FROM_ABANDONED"] = "CLOSED_DELETED_BY_AGENT_FROM_ABANDONED";
        CustomerJourneyCallbackStatus["CLOSED"] = "CLOSED";
    })(CustomerJourneyCallbackStatus || (CustomerJourneyCallbackStatus = {}));
    var CustomerJourneyInstantMessagingStatus;
    (function (CustomerJourneyInstantMessagingStatus) {
        CustomerJourneyInstantMessagingStatus["INSTANT_MESSAGING_DELIVERED"] = "INSTANT_MESSAGING_DELIVERED";
        CustomerJourneyInstantMessagingStatus["INSTANT_MESSAGING_SENT"] = "INSTANT_MESSAGING_SENT";
        CustomerJourneyInstantMessagingStatus["INSTANT_MESSAGING_FAILED"] = "INSTANT_MESSAGING_FAILED";
    })(CustomerJourneyInstantMessagingStatus || (CustomerJourneyInstantMessagingStatus = {}));
    var CustomerJourneyInteractionSubType;
    (function (CustomerJourneyInteractionSubType) {
        CustomerJourneyInteractionSubType["EMAIL"] = "EMAIL";
        CustomerJourneyInteractionSubType["SMS"] = "SMS";
        CustomerJourneyInteractionSubType["CHAT"] = "CHAT";
        CustomerJourneyInteractionSubType["FAX"] = "FAX";
        CustomerJourneyInteractionSubType["PHONE"] = "PHONE";
        CustomerJourneyInteractionSubType["TWITTER_STATUS"] = "TWITTER_STATUS";
        CustomerJourneyInteractionSubType["TWITTER_DIRECT_MESSAGE"] = "TWITTER_DIRECT_MESSAGE";
        CustomerJourneyInteractionSubType["FACEBOOK_FEED_POST"] = "FACEBOOK_FEED_POST";
        CustomerJourneyInteractionSubType["FACEBOOK_FEED_COMMENT"] = "FACEBOOK_FEED_COMMENT";
        CustomerJourneyInteractionSubType["NOTE"] = "NOTE";
        CustomerJourneyInteractionSubType["WEB"] = "WEB";
        CustomerJourneyInteractionSubType["TELEGRAM_PERSONAL_MESSAGE"] = "TELEGRAM_PERSONAL_MESSAGE";
    })(CustomerJourneyInteractionSubType || (CustomerJourneyInteractionSubType = {}));
    var CustomerJourneyInteractionType;
    (function (CustomerJourneyInteractionType) {
        CustomerJourneyInteractionType["CALL"] = "CALL";
        CustomerJourneyInteractionType["CALL_SERVICE"] = "CALL_SERVICE";
        CustomerJourneyInteractionType["SMS"] = "SMS";
        CustomerJourneyInteractionType["CALLBACK_IVR"] = "CALLBACK_IVR";
        CustomerJourneyInteractionType["CALLBACK_WEB"] = "CALLBACK_WEB";
        CustomerJourneyInteractionType["ABANDONED_CALL"] = "ABANDONED_CALL";
        CustomerJourneyInteractionType["VIDEO"] = "VIDEO";
        CustomerJourneyInteractionType["TICKET"] = "TICKET";
        CustomerJourneyInteractionType["CHAT"] = "CHAT";
        CustomerJourneyInteractionType["WHATSAPP_TWILIO"] = "WHATSAPP_TWILIO";
        CustomerJourneyInteractionType["IOT"] = "IOT";
        CustomerJourneyInteractionType["FAX"] = "FAX";
        CustomerJourneyInteractionType["VOICEMAIL"] = "VOICEMAIL";
        CustomerJourneyInteractionType["INSTANT_MESSAGING_PD"] = "INSTANT_MESSAGING_PD";
    })(CustomerJourneyInteractionType || (CustomerJourneyInteractionType = {}));
    var CustomerJourneySmsStatus;
    (function (CustomerJourneySmsStatus) {
        CustomerJourneySmsStatus["SMS_FAILED"] = "SMS_FAILED";
        CustomerJourneySmsStatus["SMS_ANSWERED"] = "SMS_ANSWERED";
    })(CustomerJourneySmsStatus || (CustomerJourneySmsStatus = {}));
    var CustomerJourneyTicketStatus;
    (function (CustomerJourneyTicketStatus) {
        CustomerJourneyTicketStatus["NEW"] = "NEW";
        CustomerJourneyTicketStatus["OPEN"] = "OPEN";
        CustomerJourneyTicketStatus["PENDING_REMINDER"] = "PENDING_REMINDER";
        CustomerJourneyTicketStatus["CLOSED"] = "CLOSED";
        CustomerJourneyTicketStatus["MERGED"] = "MERGED";
        CustomerJourneyTicketStatus["REMOVED"] = "REMOVED";
        CustomerJourneyTicketStatus["PENDING_CLOSE"] = "PENDING_CLOSE";
    })(CustomerJourneyTicketStatus || (CustomerJourneyTicketStatus = {}));
    var CustomerPortalRole;
    (function (CustomerPortalRole) {
        CustomerPortalRole["USER"] = "USER";
        CustomerPortalRole["USER_FACTORY"] = "USER_FACTORY";
    })(CustomerPortalRole || (CustomerPortalRole = {}));
    var DTOStatus;
    (function (DTOStatus) {
        DTOStatus["DELETED"] = "DELETED";
        DTOStatus["NEW"] = "NEW";
        DTOStatus["MODIFIED"] = "MODIFIED";
    })(DTOStatus || (DTOStatus = {}));
    var DelayedTaskStatus;
    (function (DelayedTaskStatus) {
        DelayedTaskStatus["WAITING"] = "WAITING";
        DelayedTaskStatus["RUNNING"] = "RUNNING";
        DelayedTaskStatus["END"] = "END";
        DelayedTaskStatus["ERROR"] = "ERROR";
    })(DelayedTaskStatus || (DelayedTaskStatus = {}));
    var DelayedTaskType;
    (function (DelayedTaskType) {
        DelayedTaskType["CONTACT_MERGE"] = "CONTACT_MERGE";
        DelayedTaskType["CONTACT_FORGET"] = "CONTACT_FORGET";
    })(DelayedTaskType || (DelayedTaskType = {}));
    var DevStatus;
    (function (DevStatus) {
        DevStatus["TRASF"] = "TRASF";
        DevStatus["TRASF_CANCEL"] = "TRASF_CANCEL";
        DevStatus["TRASF_ANSWER"] = "TRASF_ANSWER";
        DevStatus["TRASF_VM"] = "TRASF_VM";
        DevStatus["TRASF_VM_NO"] = "TRASF_VM_NO";
        DevStatus["RETURN"] = "RETURN";
    })(DevStatus || (DevStatus = {}));
    var DeviceCommandRequest;
    (function (DeviceCommandRequest) {
        DeviceCommandRequest["DIAL"] = "DIAL";
        DeviceCommandRequest["ANSWER"] = "ANSWER";
        DeviceCommandRequest["CANCEL"] = "CANCEL";
        DeviceCommandRequest["HOLD"] = "HOLD";
        DeviceCommandRequest["UNHOLD"] = "UNHOLD";
        DeviceCommandRequest["DTMF"] = "DTMF";
        DeviceCommandRequest["TRANSFER_BLIND"] = "TRANSFER_BLIND";
        DeviceCommandRequest["TRANSFER_ATTENDED"] = "TRANSFER_ATTENDED";
    })(DeviceCommandRequest || (DeviceCommandRequest = {}));
    var DeviceCommandResult;
    (function (DeviceCommandResult) {
        DeviceCommandResult["OK"] = "OK";
        DeviceCommandResult["FAILED"] = "FAILED";
        DeviceCommandResult["TIMEOUT_EXPIRED"] = "TIMEOUT_EXPIRED";
        DeviceCommandResult["DEVICE_CLOSED"] = "DEVICE_CLOSED";
        DeviceCommandResult["FEATURE_UNSUPPORTED"] = "FEATURE_UNSUPPORTED";
    })(DeviceCommandResult || (DeviceCommandResult = {}));
    var DeviceEventType;
    (function (DeviceEventType) {
        DeviceEventType["CALL_NEW_INCOMING"] = "CALL_NEW_INCOMING";
        DeviceEventType["CALL_NEW_OUTGOING"] = "CALL_NEW_OUTGOING";
    })(DeviceEventType || (DeviceEventType = {}));
    var DialStatus;
    (function (DialStatus) {
        DialStatus["CHANUNAVAIL"] = "CHANUNAVAIL";
        DialStatus["CONGESTION"] = "CONGESTION";
        DialStatus["NOANSWER"] = "NOANSWER";
        DialStatus["BUSY"] = "BUSY";
        DialStatus["ANSWER"] = "ANSWER";
        DialStatus["CANCEL"] = "CANCEL";
        DialStatus["ERROR"] = "ERROR";
        DialStatus["NON_PRESENTE"] = "NON_PRESENTE";
        DialStatus["ALWAYS"] = "ALWAYS";
        DialStatus["ENABLE_FROM_PHONE"] = "ENABLE_FROM_PHONE";
        DialStatus["PICKUPED"] = "PICKUPED";
        DialStatus["PICKUPER"] = "PICKUPER";
        DialStatus["TVOX_NO_PERMISSION"] = "TVOX_NO_PERMISSION";
        DialStatus["DONTCALL"] = "DONTCALL";
        DialStatus["REJECTED"] = "REJECTED";
    })(DialStatus || (DialStatus = {}));
    var Direction;
    (function (Direction) {
        Direction["IN"] = "IN";
        Direction["OUT"] = "OUT";
        Direction["UNKNOWN"] = "UNKNOWN";
    })(Direction || (Direction = {}));
    var EmailBoxTicketingResult;
    (function (EmailBoxTicketingResult) {
        EmailBoxTicketingResult["SUCCESS"] = "success";
        EmailBoxTicketingResult["DUPLICATE"] = "duplicate";
        EmailBoxTicketingResult["INVALID"] = "invalid";
        EmailBoxTicketingResult["OK"] = "ok";
    })(EmailBoxTicketingResult || (EmailBoxTicketingResult = {}));
    var EmailVerifyModeEnum;
    (function (EmailVerifyModeEnum) {
        EmailVerifyModeEnum["NONE"] = "NONE";
    })(EmailVerifyModeEnum || (EmailVerifyModeEnum = {}));
    var Enable;
    (function (Enable) {
        Enable["ENABLED"] = "ENABLED";
        Enable["DISABLED"] = "DISABLED";
    })(Enable || (Enable = {}));
    var Enabled;
    (function (Enabled) {
        Enabled["ENABLED"] = "ENABLED";
        Enabled["DISABLED"] = "DISABLED";
        Enabled["DEFAULT"] = "DEFAULT";
    })(Enabled || (Enabled = {}));
    var EventColor;
    (function (EventColor) {
        EventColor["WHITE"] = "WHITE";
        EventColor["YELLOW"] = "YELLOW";
        EventColor["RED"] = "RED";
        EventColor["GREEN"] = "GREEN";
        EventColor["ORANGE"] = "ORANGE";
    })(EventColor || (EventColor = {}));
    var EventType;
    (function (EventType) {
        EventType["MESSAGE"] = "MESSAGE";
        EventType["OPEN_SESSION"] = "OPEN_SESSION";
        EventType["CLOSE_SESSION"] = "CLOSE_SESSION";
    })(EventType || (EventType = {}));
    var ExeOpenType;
    (function (ExeOpenType) {
        ExeOpenType["DISABLED"] = "DISABLED";
        ExeOpenType["WEBVIEW_SINGLE"] = "WEBVIEW_SINGLE";
        ExeOpenType["WEBVIEW_MULTI"] = "WEBVIEW_MULTI";
        ExeOpenType["WEBVIEW_NEW_TAB"] = "WEBVIEW_NEW_TAB";
        ExeOpenType["BROWSER"] = "BROWSER";
    })(ExeOpenType || (ExeOpenType = {}));
    var ExtenStatus;
    (function (ExtenStatus) {
        ExtenStatus["IDLE"] = "IDLE";
        ExtenStatus["IN_USE"] = "IN_USE";
        ExtenStatus["BUSY"] = "BUSY";
        ExtenStatus["UNAVAILABLE"] = "UNAVAILABLE";
        ExtenStatus["RINGING"] = "RINGING";
        ExtenStatus["IN_USE_AND_RINGING"] = "IN_USE_AND_RINGING";
        ExtenStatus["HOLD"] = "HOLD";
        ExtenStatus["IN_USE_AND_HOLD"] = "IN_USE_AND_HOLD";
        ExtenStatus["UNKNOWN"] = "UNKNOWN";
    })(ExtenStatus || (ExtenStatus = {}));
    var ExtenType;
    (function (ExtenType) {
        ExtenType["MCS_SIP"] = "MCS_SIP";
        ExtenType["MCS_APP"] = "MCS_APP";
        ExtenType["MCS_APP_WEBRTC"] = "MCS_APP_WEBRTC";
        ExtenType["SIP"] = "SIP";
        ExtenType["EXTERNAL"] = "EXTERNAL";
        ExtenType["WEBRTC"] = "WEBRTC";
    })(ExtenType || (ExtenType = {}));
    var ExternalAccountScope;
    (function (ExternalAccountScope) {
        ExternalAccountScope["BLF"] = "BLF";
        ExternalAccountScope["T4YOU"] = "T4YOU";
        ExternalAccountScope["SURVEY"] = "SURVEY";
        ExternalAccountScope["MAIL"] = "MAIL";
        ExternalAccountScope["SUPPORT"] = "SUPPORT";
        ExternalAccountScope["FACEBOOK_POST"] = "FACEBOOK_POST";
    })(ExternalAccountScope || (ExternalAccountScope = {}));
    var FavouriteUserItemType;
    (function (FavouriteUserItemType) {
        FavouriteUserItemType["USER"] = "USER";
        FavouriteUserItemType["GROUP"] = "GROUP";
    })(FavouriteUserItemType || (FavouriteUserItemType = {}));
    var FaxDocumentStatus;
    (function (FaxDocumentStatus) {
        FaxDocumentStatus["IDLE"] = "IDLE";
        FaxDocumentStatus["CREATING_FILE"] = "CREATING_FILE";
        FaxDocumentStatus["TO_SEND"] = "TO_SEND";
        FaxDocumentStatus["CALLING"] = "CALLING";
        FaxDocumentStatus["SENDING"] = "SENDING";
        FaxDocumentStatus["SEND"] = "SEND";
        FaxDocumentStatus["RECEIVING"] = "RECEIVING";
        FaxDocumentStatus["RECEIVED"] = "RECEIVED";
        FaxDocumentStatus["ERROR"] = "ERROR";
        FaxDocumentStatus["ERROR_NO_LICENSE"] = "ERROR_NO_LICENSE";
        FaxDocumentStatus["ERROR_CALLING"] = "ERROR_CALLING";
        FaxDocumentStatus["ERROR_CREATE_FILE"] = "ERROR_CREATE_FILE";
        FaxDocumentStatus["ERROR_SENDING"] = "ERROR_SENDING";
        FaxDocumentStatus["ERROR_NO_USER_FAXBOX"] = "ERROR_NO_USER_FAXBOX";
        FaxDocumentStatus["ERROR_NO_USER_FAXBOX_SEND_ENABLED"] = "ERROR_NO_USER_FAXBOX_SEND_ENABLED";
    })(FaxDocumentStatus || (FaxDocumentStatus = {}));
    var FaxDocumentType;
    (function (FaxDocumentType) {
        FaxDocumentType["INBOUND"] = "INBOUND";
        FaxDocumentType["OUTBOUND"] = "OUTBOUND";
    })(FaxDocumentType || (FaxDocumentType = {}));
    var Field;
    (function (Field) {
        Field["dtoStatus"] = "dtoStatus";
        Field["ownerPanels"] = "ownerPanels";
    })(Field || (Field = {}));
    var FieldType;
    (function (FieldType) {
        FieldType["MAIN"] = "MAIN";
        FieldType["WORK"] = "WORK";
        FieldType["CELL"] = "CELL";
        FieldType["HOME"] = "HOME";
        FieldType["NONE"] = "NONE";
        FieldType["FAX"] = "FAX";
    })(FieldType || (FieldType = {}));
    var GeneralParamType;
    (function (GeneralParamType) {
        GeneralParamType["NUMBER"] = "NUMBER";
        GeneralParamType["STRING"] = "STRING";
        GeneralParamType["BOOLEAN"] = "BOOLEAN";
    })(GeneralParamType || (GeneralParamType = {}));
    var ICIChannelReason;
    (function (ICIChannelReason) {
        ICIChannelReason["DIRECT"] = "DIRECT";
        ICIChannelReason["REDIRECT"] = "REDIRECT";
        ICIChannelReason["FWDNOANSWER"] = "FWDNOANSWER";
        ICIChannelReason["FWDBUSY"] = "FWDBUSY";
        ICIChannelReason["FWDUNCOND"] = "FWDUNCOND";
        ICIChannelReason["UNAVAIL"] = "UNAVAIL";
    })(ICIChannelReason || (ICIChannelReason = {}));
    var IciReason;
    (function (IciReason) {
        IciReason["DIRECT"] = "DIRECT";
        IciReason["REDIRECT"] = "REDIRECT";
        IciReason["FWDNOANSWER"] = "FWDNOANSWER";
        IciReason["FWDBUSY"] = "FWDBUSY";
        IciReason["FWDUNCOND"] = "FWDUNCOND";
        IciReason["UNAVAIL"] = "UNAVAIL";
    })(IciReason || (IciReason = {}));
    var IciType;
    (function (IciType) {
        IciType["INTERNAL"] = "INTERNAL";
        IciType["EXTERNAL"] = "EXTERNAL";
        IciType["REMOTE"] = "REMOTE";
    })(IciType || (IciType = {}));
    var Id;
    (function (Id) {
        Id["NONE"] = "NONE";
        Id["CLASS"] = "CLASS";
        Id["MINIMAL_CLASS"] = "MINIMAL_CLASS";
        Id["NAME"] = "NAME";
        Id["DEDUCTION"] = "DEDUCTION";
        Id["CUSTOM"] = "CUSTOM";
    })(Id || (Id = {}));
    var IdType;
    (function (IdType) {
        IdType["CALL"] = "CALL";
        IdType["MC_1"] = "MC_1";
        IdType["MC_2"] = "MC_2";
        IdType["MC_3"] = "MC_3";
        IdType["MC_VIDEO"] = "MC_VIDEO";
        IdType["MC_MAIL_IFRAME"] = "MC_MAIL_IFRAME";
        IdType["MC_CHAT"] = "MC_CHAT";
        IdType["MC_WHATSAPP_TWILIO"] = "MC_WHATSAPP_TWILIO";
        IdType["MC_OMNIDESK"] = "MC_OMNIDESK";
    })(IdType || (IdType = {}));
    var IdleReason;
    (function (IdleReason) {
        IdleReason["HANGUP"] = "HANGUP";
        IdleReason["BUSY"] = "BUSY";
        IdleReason["CONGESTION"] = "CONGESTION";
    })(IdleReason || (IdleReason = {}));
    var JQGridOp;
    (function (JQGridOp) {
        JQGridOp["AND"] = "AND";
        JQGridOp["OR"] = "OR";
    })(JQGridOp || (JQGridOp = {}));
    var JQGridRuleOp;
    (function (JQGridRuleOp) {
        JQGridRuleOp["EQUAL"] = "EQUAL";
        JQGridRuleOp["NOT_EQUAL"] = "NOT_EQUAL";
        JQGridRuleOp["LESS"] = "LESS";
        JQGridRuleOp["LESS_EQUAL"] = "LESS_EQUAL";
        JQGridRuleOp["GREATER"] = "GREATER";
        JQGridRuleOp["GREATER_EQUAL"] = "GREATER_EQUAL";
        JQGridRuleOp["CONTAINS"] = "CONTAINS";
        JQGridRuleOp["NOT_CONTAINS"] = "NOT_CONTAINS";
        JQGridRuleOp["BEGIN_WITH"] = "BEGIN_WITH";
        JQGridRuleOp["NOT_BEGIN_WITH"] = "NOT_BEGIN_WITH";
        JQGridRuleOp["END_WITH"] = "END_WITH";
        JQGridRuleOp["NOT_END_WITH"] = "NOT_END_WITH";
        JQGridRuleOp["IS_NULL"] = "IS_NULL";
        JQGridRuleOp["IS_NOT_NULL"] = "IS_NOT_NULL";
        JQGridRuleOp["IS_IN"] = "IS_IN";
        JQGridRuleOp["IS_NOT_IN"] = "IS_NOT_IN";
    })(JQGridRuleOp || (JQGridRuleOp = {}));
    var KnowledgeBaseCategoryViewType;
    (function (KnowledgeBaseCategoryViewType) {
        KnowledgeBaseCategoryViewType["FAQ"] = "FAQ";
        KnowledgeBaseCategoryViewType["TREE"] = "TREE";
    })(KnowledgeBaseCategoryViewType || (KnowledgeBaseCategoryViewType = {}));
    var KnowledgebaseUserEnabling;
    (function (KnowledgebaseUserEnabling) {
        KnowledgebaseUserEnabling["DISABLED"] = "DISABLED";
        KnowledgebaseUserEnabling["READ"] = "READ";
        KnowledgebaseUserEnabling["READWRITE"] = "READWRITE";
    })(KnowledgebaseUserEnabling || (KnowledgebaseUserEnabling = {}));
    var Language;
    (function (Language) {
        Language["IT"] = "IT";
        Language["it_IT"] = "it_IT";
        Language["EN"] = "EN";
        Language["en_US"] = "en_US";
        Language["FR"] = "FR";
        Language["fr_FR"] = "fr_FR";
        Language["NL"] = "NL";
        Language["nl_NL"] = "nl_NL";
    })(Language || (Language = {}));
    var LastActivityType;
    (function (LastActivityType) {
        LastActivityType["CHAT"] = "CHAT";
        LastActivityType["CALL"] = "CALL";
        LastActivityType["MAIL"] = "MAIL";
        LastActivityType["WEB"] = "WEB";
        LastActivityType["FACEBOOK"] = "FACEBOOK";
        LastActivityType["TWITTER"] = "TWITTER";
        LastActivityType["VIDEO"] = "VIDEO";
        LastActivityType["TELEGRAM"] = "TELEGRAM";
        LastActivityType["CHANNEL_1"] = "CHANNEL_1";
        LastActivityType["CHANNEL_2"] = "CHANNEL_2";
        LastActivityType["CHANNEL_3"] = "CHANNEL_3";
    })(LastActivityType || (LastActivityType = {}));
    var LicenseModule;
    (function (LicenseModule) {
        LicenseModule["ABBANDONED_CALL"] = "ABBANDONED_CALL";
        LicenseModule["ABOT"] = "ABOT";
        LicenseModule["AGENT"] = "AGENT";
        LicenseModule["AGENT_CLIENT"] = "AGENT_CLIENT";
        LicenseModule["AGENT_MULTICHANNEL_1"] = "AGENT_MULTICHANNEL_1";
        LicenseModule["AGENT_MULTICHANNEL_2"] = "AGENT_MULTICHANNEL_2";
        LicenseModule["AGENT_MULTICHANNEL_3"] = "AGENT_MULTICHANNEL_3";
        LicenseModule["AGENT_MULTICHANNEL_CALLBACK"] = "AGENT_MULTICHANNEL_CALLBACK";
        LicenseModule["AGENT_MULTICHANNEL_CHAT"] = "AGENT_MULTICHANNEL_CHAT";
        LicenseModule["AGENT_MULTICHANNEL_LIVEHELP"] = "AGENT_MULTICHANNEL_LIVEHELP";
        LicenseModule["AGENT_MULTICHANNEL_MAIL"] = "AGENT_MULTICHANNEL_MAIL";
        LicenseModule["AGENT_MULTICHANNEL_VIDEO"] = "AGENT_MULTICHANNEL_VIDEO";
        LicenseModule["AGENT_MULTICHANNEL_WHATSAPP_TWILIO"] = "AGENT_MULTICHANNEL_WHATSAPP_TWILIO";
        LicenseModule["AGENT_MULTICHANNEL_OMNIDESK"] = "AGENT_MULTICHANNEL_OMNIDESK";
        LicenseModule["AGENT_PICKUP_SERVICE"] = "AGENT_PICKUP_SERVICE";
        LicenseModule["APP_USERS"] = "APP_USERS";
        LicenseModule["ASSET"] = "ASSET";
        LicenseModule["AVAIL"] = "AVAIL";
        LicenseModule["BLF_SIP"] = "BLF_SIP";
        LicenseModule["BLF_SKYPE"] = "BLF_SKYPE";
        LicenseModule["BRANCH_OFFICE"] = "BRANCH_OFFICE";
        LicenseModule["BRANCH_OFFICE_CLIENT"] = "BRANCH_OFFICE_CLIENT";
        LicenseModule["CAC"] = "CAC";
        LicenseModule["CALLBACK"] = "CALLBACK";
        LicenseModule["CALLBACK_POWERDIALER"] = "CALLBACK_POWERDIALER";
        LicenseModule["CDR"] = "CDR";
        LicenseModule["CUSTOMER"] = "CUSTOMER";
        LicenseModule["CUSTOMER_JOURNEY"] = "CUSTOMER_JOURNEY";
        LicenseModule["CUSTOMER_JOURNEY_SERVER"] = "CUSTOMER_JOURNEY_SERVER";
        LicenseModule["DISASTER_RECOVERY"] = "DISASTER_RECOVERY";
        LicenseModule["DISASTER_RECOVERY_CLIENT"] = "DISASTER_RECOVERY_CLIENT";
        LicenseModule["DLLREC"] = "DLLREC";
        LicenseModule["EXTERNAL_ADDRESSBOOK"] = "EXTERNAL_ADDRESSBOOK";
        LicenseModule["FAULT_TOLERANCE"] = "FAULT_TOLERANCE";
        LicenseModule["FAX_SERVER"] = "FAX_SERVER";
        LicenseModule["GRTD"] = "GRTD";
        LicenseModule["IDM"] = "IDM";
        LicenseModule["INSIGHT"] = "INSIGHT";
        LicenseModule["KB_SERVER"] = "KB_SERVER";
        LicenseModule["KB_USER"] = "KB_USER";
        LicenseModule["LDAP_EXPORT_USERS"] = "LDAP_EXPORT_USERS";
        LicenseModule["MCS"] = "MCS";
        LicenseModule["MCS_APP_USERS"] = "MCS_APP_USERS";
        LicenseModule["MCS_APP_WEBRTC"] = "MCS_APP_WEBRTC";
        LicenseModule["MCS_USERS"] = "MCS_USERS";
        LicenseModule["MCS_CERT"] = "MCS_CERT";
        LicenseModule["MC_TICKET_SERVER"] = "MC_TICKET_SERVER";
        LicenseModule["MOBILITY"] = "MOBILITY";
        LicenseModule["MRCP"] = "MRCP";
        LicenseModule["MRCP_RM"] = "MRCP_RM";
        LicenseModule["MSOP"] = "MSOP";
        LicenseModule["MULTICHANNEL_1"] = "MULTICHANNEL_1";
        LicenseModule["MULTICHANNEL_2"] = "MULTICHANNEL_2";
        LicenseModule["MULTICHANNEL_3"] = "MULTICHANNEL_3";
        LicenseModule["MULTICHANNEL_CALLBACK"] = "MULTICHANNEL_CALLBACK";
        LicenseModule["MULTICHANNEL_CHAT"] = "MULTICHANNEL_CHAT";
        LicenseModule["MULTICHANNEL_LIVEHELP"] = "MULTICHANNEL_LIVEHELP";
        LicenseModule["MULTICHANNEL_MAIL"] = "MULTICHANNEL_MAIL";
        LicenseModule["MULTICHANNEL_VIDEO"] = "MULTICHANNEL_VIDEO";
        LicenseModule["MULTICHANNEL_WHATSAPP_TWILIO"] = "MULTICHANNEL_WHATSAPP_TWILIO";
        LicenseModule["MULTICHANNEL_OMNIDESK"] = "MULTICHANNEL_OMNIDESK";
        LicenseModule["OMNIDESK"] = "OMNIDESK";
        LicenseModule["OPERATOR"] = "OPERATOR";
        LicenseModule["OPERATOR_PICKUP_SERVICE"] = "OPERATOR_PICKUP_SERVICE";
        LicenseModule["OTRS"] = "OTRS";
        LicenseModule["POWER_DIALER"] = "POWER_DIALER";
        LicenseModule["PROVISIONING"] = "PROVISIONING";
        LicenseModule["PURE_CLOUD"] = "PURE_CLOUD";
        LicenseModule["QUALITY_INTERVIEW"] = "QUALITY_INTERVIEW";
        LicenseModule["QUALITY_INTERVIEW_AUTO"] = "QUALITY_INTERVIEW_AUTO";
        LicenseModule["QUEUE"] = "QUEUE";
        LicenseModule["SCALE"] = "SCALE";
        LicenseModule["SEDE"] = "SEDE";
        LicenseModule["SKT_SCHEDULE"] = "SKT_SCHEDULE";
        LicenseModule["SMARTREC"] = "SMARTREC";
        LicenseModule["SMARTREC_AUTO"] = "SMARTREC_AUTO";
        LicenseModule["SMS"] = "SMS";
        LicenseModule["SNMP_FWD"] = "SNMP_FWD";
        LicenseModule["SOFTPHONE"] = "SOFTPHONE";
        LicenseModule["T4YOU"] = "T4YOU";
        LicenseModule["T4YOU_CENTRALIZED"] = "T4YOU_CENTRALIZED";
        LicenseModule["T4YOU_CUSTOM"] = "T4YOU_CUSTOM";
        LicenseModule["T4YOU_EXCHANGE"] = "T4YOU_EXCHANGE";
        LicenseModule["T4YOU_FILEXMLCSV"] = "T4YOU_FILEXMLCSV";
        LicenseModule["T4YOU_GOOGLE"] = "T4YOU_GOOGLE";
        LicenseModule["T4YOU_LDAP"] = "T4YOU_LDAP";
        LicenseModule["T4YOU_MYSQL"] = "T4YOU_MYSQL";
        LicenseModule["T4YOU_ORACLE"] = "T4YOU_ORACLE";
        LicenseModule["T4YOU_SOAP"] = "T4YOU_SOAP";
        LicenseModule["T4YOU_SQLSERVER"] = "T4YOU_SQLSERVER";
        LicenseModule["T4YOU_SUITECRM"] = "T4YOU_SUITECRM";
        LicenseModule["T4YOU_VTE"] = "T4YOU_VTE";
        LicenseModule["T4YOU_ZIMBRA"] = "T4YOU_ZIMBRA";
        LicenseModule["T4YOU_MICROSOFT365"] = "T4YOU_MICROSOFT365";
        LicenseModule["TADS"] = "TADS";
        LicenseModule["TCC_EXTERNAL"] = "TCC_EXTERNAL";
        LicenseModule["TUC_REMOTE"] = "TUC_REMOTE";
        LicenseModule["TCC_REMOTE"] = "TCC_REMOTE";
        LicenseModule["TEMP"] = "TEMP";
        LicenseModule["TICKET"] = "TICKET";
        LicenseModule["TLS"] = "TLS";
        LicenseModule["TSAM"] = "TSAM";
        LicenseModule["TSAM_ACCOUNTING"] = "TSAM_ACCOUNTING";
        LicenseModule["TSAM_MONITORING"] = "TSAM_MONITORING";
        LicenseModule["TSAM_TICKET"] = "TSAM_TICKET";
        LicenseModule["TTS"] = "TTS";
        LicenseModule["TTS_PROMPT"] = "TTS_PROMPT";
        LicenseModule["TVOX"] = "TVOX";
        LicenseModule["TVOX_SERVICE_OUTBOUND"] = "TVOX_SERVICE_OUTBOUND";
        LicenseModule["TWIN"] = "TWIN";
        LicenseModule["USER"] = "USER";
        LicenseModule["USER_ACD"] = "USER_ACD";
        LicenseModule["USER_ACD_CLIENT"] = "USER_ACD_CLIENT";
        LicenseModule["USER_CLIENT"] = "USER_CLIENT";
        LicenseModule["USER_SUPPORT_LIGHT"] = "USER_SUPPORT_LIGHT";
        LicenseModule["VIP"] = "VIP";
        LicenseModule["VIP_ACD"] = "VIP_ACD";
        LicenseModule["ES_SERVER"] = "ES_SERVER";
        LicenseModule["WAC_IPO"] = "WAC_IPO";
        LicenseModule["WAC_SV"] = "WAC_SV";
        LicenseModule["WAC_BB"] = "WAC_BB";
        LicenseModule["WEBRTC"] = "WEBRTC";
    })(LicenseModule || (LicenseModule = {}));
    var LinkType;
    (function (LinkType) {
        LinkType["PARENT"] = "parent";
        LinkType["CHILD"] = "child";
        LinkType["NORMAL"] = "normal";
    })(LinkType || (LinkType = {}));
    var LoginProfileStatus;
    (function (LoginProfileStatus) {
        LoginProfileStatus["UNKNOWN"] = "UNKNOWN";
        LoginProfileStatus["LOGGED"] = "LOGGED";
        LoginProfileStatus["NOTLOGGED"] = "NOTLOGGED";
        LoginProfileStatus["RETRY"] = "RETRY";
        LoginProfileStatus["REFRESH"] = "REFRESH";
        LoginProfileStatus["SOCKET_NOTLOGGED"] = "SOCKET_NOTLOGGED";
        LoginProfileStatus["PASSWORD_EXPIRED"] = "PASSWORD_EXPIRED";
        LoginProfileStatus["SOCKET_CLOSED_REQUEST_FORCE"] = "SOCKET_CLOSED_REQUEST_FORCE";
        LoginProfileStatus["SOCKET_CLOSED_BY_USER"] = "SOCKET_CLOSED_BY_USER";
        LoginProfileStatus["SOCKET_CLOSED_USER_NOT_ENABLED"] = "SOCKET_CLOSED_USER_NOT_ENABLED";
        LoginProfileStatus["SOCKET_CLOSED_USER_NOT_ENABLED_MCS"] = "SOCKET_CLOSED_USER_NOT_ENABLED_MCS";
    })(LoginProfileStatus || (LoginProfileStatus = {}));
    var LookupResult;
    (function (LookupResult) {
        LookupResult["SUCCESS"] = "SUCCESS";
        LookupResult["MULTIPLE"] = "MULTIPLE";
        LookupResult["ERROR"] = "ERROR";
        LookupResult["NONE"] = "NONE";
    })(LookupResult || (LookupResult = {}));
    var Mode;
    (function (Mode) {
        Mode["EMAIL"] = "EMAIL";
        Mode["SMS"] = "SMS";
    })(Mode || (Mode = {}));
    var MultiChannelCategory;
    (function (MultiChannelCategory) {
        MultiChannelCategory["STANDARD"] = "STANDARD";
        MultiChannelCategory["TELEPHONY"] = "TELEPHONY";
        MultiChannelCategory["VIDEOCALL"] = "VIDEOCALL";
        MultiChannelCategory["CHAT"] = "CHAT";
        MultiChannelCategory["EMAIL"] = "EMAIL";
    })(MultiChannelCategory || (MultiChannelCategory = {}));
    var NoteRemainderStatus;
    (function (NoteRemainderStatus) {
        NoteRemainderStatus["WITHOUT_EXPIRED_TIME"] = "WITHOUT_EXPIRED_TIME";
        NoteRemainderStatus["WITH_EXPIRED_TIME"] = "WITH_EXPIRED_TIME";
        NoteRemainderStatus["EXPIRED"] = "EXPIRED";
        NoteRemainderStatus["EXPIRING"] = "EXPIRING";
        NoteRemainderStatus["NOT_EXPIRED"] = "NOT_EXPIRED";
    })(NoteRemainderStatus || (NoteRemainderStatus = {}));
    var NoteType;
    (function (NoteType) {
        NoteType["NOTE"] = "NOTE";
        NoteType["LIST"] = "LIST";
    })(NoteType || (NoteType = {}));
    var NotificationMode;
    (function (NotificationMode) {
        NotificationMode["MAIL"] = "MAIL";
        NotificationMode["SMS"] = "SMS";
    })(NotificationMode || (NotificationMode = {}));
    var NotifyChange;
    (function (NotifyChange) {
        NotifyChange["ALWAYS"] = "ALWAYS";
        NotifyChange["ONETIME"] = "ONETIME";
        NotifyChange["NEVER"] = "NEVER";
    })(NotifyChange || (NotifyChange = {}));
    var NotifyMethod;
    (function (NotifyMethod) {
        NotifyMethod["CALL"] = "CALL";
        NotifyMethod["MAIL"] = "MAIL";
        NotifyMethod["SMS"] = "SMS";
        NotifyMethod["CHAT"] = "CHAT";
        NotifyMethod["ALL"] = "ALL";
    })(NotifyMethod || (NotifyMethod = {}));
    var Nulls;
    (function (Nulls) {
        Nulls["SET"] = "SET";
        Nulls["SKIP"] = "SKIP";
        Nulls["FAIL"] = "FAIL";
        Nulls["AS_EMPTY"] = "AS_EMPTY";
        Nulls["DEFAULT"] = "DEFAULT";
    })(Nulls || (Nulls = {}));
    var NumberType;
    (function (NumberType) {
        NumberType["INTERNAL"] = "INTERNAL";
        NumberType["EXTERNAL"] = "EXTERNAL";
        NumberType["REMOTE"] = "REMOTE";
    })(NumberType || (NumberType = {}));
    var OmnideskDndState;
    (function (OmnideskDndState) {
        OmnideskDndState["NO"] = "NO";
        OmnideskDndState["KEEP"] = "KEEP";
        OmnideskDndState["NO_KEEP"] = "NO_KEEP";
    })(OmnideskDndState || (OmnideskDndState = {}));
    var OmnideskFeature;
    (function (OmnideskFeature) {
        OmnideskFeature["microphone"] = "microphone";
        OmnideskFeature["camera"] = "camera";
        OmnideskFeature["closedcaptions"] = "closedcaptions";
        OmnideskFeature["desktop"] = "desktop";
        OmnideskFeature["fodeviceselection"] = "fodeviceselection";
        OmnideskFeature["hangup"] = "hangup";
        OmnideskFeature["recording"] = "recording";
        OmnideskFeature["livestreaming"] = "livestreaming";
        OmnideskFeature["sharedvideo"] = "sharedvideo";
        OmnideskFeature["settings"] = "settings";
        OmnideskFeature["raisehand"] = "raisehand";
        OmnideskFeature["videoquality"] = "videoquality";
        OmnideskFeature["invite"] = "invite";
        OmnideskFeature["feedback"] = "feedback";
        OmnideskFeature["stats"] = "stats";
        OmnideskFeature["select_background"] = "select_background";
        OmnideskFeature["mute_everyone"] = "mute_everyone";
        OmnideskFeature["mute_video_everyone"] = "mute_video_everyone";
    })(OmnideskFeature || (OmnideskFeature = {}));
    var OmnideskMeetingEventParticipantFeature;
    (function (OmnideskMeetingEventParticipantFeature) {
        OmnideskMeetingEventParticipantFeature["LIVE_STREAMING"] = "LIVE_STREAMING";
        OmnideskMeetingEventParticipantFeature["RECORDING"] = "RECORDING";
        OmnideskMeetingEventParticipantFeature["MODERATOR"] = "MODERATOR";
        OmnideskMeetingEventParticipantFeature["ORGANIZER"] = "ORGANIZER";
    })(OmnideskMeetingEventParticipantFeature || (OmnideskMeetingEventParticipantFeature = {}));
    var OmnideskMeetingEventParticipantStatus;
    (function (OmnideskMeetingEventParticipantStatus) {
        OmnideskMeetingEventParticipantStatus["ACCEPTED"] = "ACCEPTED";
        OmnideskMeetingEventParticipantStatus["DECLINED"] = "DECLINED";
        OmnideskMeetingEventParticipantStatus["PENDING_RESPONSE"] = "PENDING_RESPONSE";
        OmnideskMeetingEventParticipantStatus["COMPLETED"] = "COMPLETED";
    })(OmnideskMeetingEventParticipantStatus || (OmnideskMeetingEventParticipantStatus = {}));
    var OperationType;
    (function (OperationType) {
        OperationType["EQUAL"] = "EQUAL";
        OperationType["NOT_EQUAL"] = "NOT_EQUAL";
        OperationType["CONTAINS"] = "CONTAINS";
        OperationType["GT"] = "GT";
        OperationType["GE"] = "GE";
        OperationType["LT"] = "LT";
        OperationType["LE"] = "LE";
        OperationType["NOT_NULL"] = "NOT_NULL";
        OperationType["BETWEEN"] = "BETWEEN";
    })(OperationType || (OperationType = {}));
    var Operator;
    (function (Operator) {
        Operator["is"] = "is";
        Operator["isNot"] = "is not";
        Operator["hasChanged"] = "has changed";
        Operator["contains"] = "contains";
        Operator["containsNot"] = "contains not";
        Operator["absoluteBefore"] = "before (absolute)";
        Operator["relativeBefore"] = "before (relative)";
        Operator["absoluteAfter"] = "after (absolute)";
        Operator["relativeAfter"] = "after (relative)";
        Operator["relativeWithinNext"] = "within next (relative)";
        Operator["relativeWithinLast"] = "within last (relative)";
        Operator["AND"] = "AND";
        Operator["OR"] = "OR";
        Operator["NOT"] = "NOT";
    })(Operator || (Operator = {}));
    var OperatorLogic;
    (function (OperatorLogic) {
        OperatorLogic["AND"] = "AND";
        OperatorLogic["OR"] = "OR";
        OperatorLogic["NOT"] = "NOT";
    })(OperatorLogic || (OperatorLogic = {}));
    var OrderType;
    (function (OrderType) {
        OrderType["ASC"] = "ASC";
        OrderType["DESC"] = "DESC";
    })(OrderType || (OrderType = {}));
    var OrdinationType;
    (function (OrdinationType) {
        OrdinationType["ASC"] = "ASC";
        OrdinationType["DESC"] = "DESC";
    })(OrdinationType || (OrdinationType = {}));
    var POAction;
    (function (POAction) {
        POAction["HELP"] = "HELP";
        POAction["RUBINT"] = "RUBINT";
        POAction["RUBEST"] = "RUBEST";
        POAction["RUBGLOB"] = "RUBGLOB";
        POAction["PO"] = "PO";
        POAction["PARK"] = "PARK";
        POAction["DTMF"] = "DTMF";
        POAction["BNOTES"] = "BNOTES";
        POAction["TQM"] = "TQM";
        POAction["POSTIT"] = "POSTIT";
        POAction["RICALT"] = "RICALT";
        POAction["INVIOCH"] = "INVIOCH";
    })(POAction || (POAction = {}));
    var POBrailleFeature;
    (function (POBrailleFeature) {
        POBrailleFeature["on_addressbook"] = "on_addressbook";
        POBrailleFeature["on_console"] = "on_console";
    })(POBrailleFeature || (POBrailleFeature = {}));
    var POFeatureCustomTelNumber;
    (function (POFeatureCustomTelNumber) {
        POFeatureCustomTelNumber["TEL1"] = "TEL1";
        POFeatureCustomTelNumber["TEL2"] = "TEL2";
        POFeatureCustomTelNumber["TEL3"] = "TEL3";
        POFeatureCustomTelNumber["TEL4"] = "TEL4";
        POFeatureCustomTelNumber["TEL5"] = "TEL5";
        POFeatureCustomTelNumber["TEL6"] = "TEL6";
        POFeatureCustomTelNumber["TEL7"] = "TEL7";
        POFeatureCustomTelNumber["TEL8"] = "TEL8";
        POFeatureCustomTelNumber["TEL9"] = "TEL9";
    })(POFeatureCustomTelNumber || (POFeatureCustomTelNumber = {}));
    var POIpoFeature;
    (function (POIpoFeature) {
        POIpoFeature["ici_top"] = "ici_top";
        POIpoFeature["plus_time"] = "plus_time";
    })(POIpoFeature || (POIpoFeature = {}));
    var POKey;
    (function (POKey) {
        POKey["F1"] = "F1";
        POKey["F2"] = "F2";
        POKey["F3"] = "F3";
        POKey["F4"] = "F4";
        POKey["F5"] = "F5";
        POKey["F6"] = "F6";
        POKey["F7"] = "F7";
        POKey["F8"] = "F8";
        POKey["F9"] = "F9";
        POKey["F10"] = "F10";
        POKey["F11"] = "F11";
        POKey["F12"] = "F12";
    })(POKey || (POKey = {}));
    var POSynthVocalFeature;
    (function (POSynthVocalFeature) {
        POSynthVocalFeature["on_number"] = "on_number";
        POSynthVocalFeature["on_keypad"] = "on_keypad";
        POSynthVocalFeature["on_queued_call"] = "on_queued_call";
        POSynthVocalFeature["stop_after_answer"] = "stop_after_answer";
        POSynthVocalFeature["on_addressbook"] = "on_addressbook";
        POSynthVocalFeature["on_console"] = "on_console";
    })(POSynthVocalFeature || (POSynthVocalFeature = {}));
    var PartType;
    (function (PartType) {
        PartType["START"] = "START";
        PartType["END"] = "END";
    })(PartType || (PartType = {}));
    var PeerStatus;
    (function (PeerStatus) {
        PeerStatus["UNKNOWN"] = "UNKNOWN";
        PeerStatus["UNREGISTERED"] = "UNREGISTERED";
        PeerStatus["LAGGED"] = "LAGGED";
        PeerStatus["UNMONITORED"] = "UNMONITORED";
        PeerStatus["UNREACHABLE"] = "UNREACHABLE";
        PeerStatus["REGISTERED"] = "REGISTERED";
        PeerStatus["REACHABLE"] = "REACHABLE";
    })(PeerStatus || (PeerStatus = {}));
    var PeerType;
    (function (PeerType) {
        PeerType["SIP"] = "SIP";
        PeerType["IAX2"] = "IAX2";
        PeerType["ENUM"] = "ENUM";
        PeerType["UNKNOWN"] = "UNKNOWN";
    })(PeerType || (PeerType = {}));
    var Phase;
    (function (Phase) {
        Phase["START_REMOVE"] = "START_REMOVE";
        Phase["END_REMOVE"] = "END_REMOVE";
        Phase["START_IMPORT"] = "START_IMPORT";
        Phase["NOTIFY_IMPORT"] = "NOTIFY_IMPORT";
        Phase["END_IMPORT"] = "END_IMPORT";
        Phase["MSG"] = "MSG";
        Phase["NO_IMPORT_RUNNING"] = "NO_IMPORT_RUNNING";
    })(Phase || (Phase = {}));
    var Platform$1;
    (function (Platform) {
        Platform["WEB"] = "WEB";
        Platform["IOS"] = "IOS";
        Platform["ANDROID"] = "ANDROID";
        Platform["EXE"] = "EXE";
    })(Platform$1 || (Platform$1 = {}));
    var PoInstrument;
    (function (PoInstrument) {
        PoInstrument["sv"] = "sv";
        PoInstrument["ipoplus"] = "ipoplus";
        PoInstrument["braille"] = "braille";
    })(PoInstrument || (PoInstrument = {}));
    var PoType;
    (function (PoType) {
        PoType["v"] = "v";
        PoType["nv"] = "nv";
        PoType["ipo"] = "ipo";
    })(PoType || (PoType = {}));
    var PresenceStatus;
    (function (PresenceStatus) {
        PresenceStatus["chat"] = "chat";
        PresenceStatus["available"] = "available";
        PresenceStatus["away"] = "away";
        PresenceStatus["xa"] = "xa";
        PresenceStatus["dnd"] = "dnd";
        PresenceStatus["unavailable"] = "unavailable";
    })(PresenceStatus || (PresenceStatus = {}));
    var ProductPrefix;
    (function (ProductPrefix) {
        ProductPrefix["TVOX"] = "TVOX";
        ProductPrefix["TSAM"] = "TSAM";
        ProductPrefix["TAM"] = "TAM";
        ProductPrefix["LDAP"] = "LDAP";
        ProductPrefix["SYSTEM"] = "SYSTEM";
        ProductPrefix["T4YOU"] = "T4YOU";
        ProductPrefix["WEB_CLIENT_PROXY"] = "WEB_CLIENT_PROXY";
        ProductPrefix["MCS"] = "MCS";
        ProductPrefix["CUSTOMER"] = "CUSTOMER";
    })(ProductPrefix || (ProductPrefix = {}));
    var Products;
    (function (Products) {
        Products["WSO2IS"] = "WSO2IS";
        Products["MCS_SERVER"] = "MCS_SERVER";
        Products["T4YOU"] = "T4YOU";
        Products["TCS"] = "TCS";
        Products["TSAM"] = "TSAM";
        Products["TVOX"] = "TVOX";
    })(Products || (Products = {}));
    var ProfileType;
    (function (ProfileType) {
        ProfileType["UC"] = "UC";
        ProfileType["AG"] = "AG";
        ProfileType["AG_EXTERNAL"] = "AG_EXTERNAL";
        ProfileType["AG_REMOTE"] = "AG_REMOTE";
        ProfileType["TQM"] = "TQM";
    })(ProfileType || (ProfileType = {}));
    var Reason;
    (function (Reason) {
        Reason["FILE_EXISTS"] = "FILE_EXISTS";
        Reason["WRONG_PERMISSION"] = "WRONG_PERMISSION";
        Reason["UNMANAGED_FILE_FORMAT"] = "UNMANAGED_FILE_FORMAT";
        Reason["GENERIC_ERROR"] = "GENERIC_ERROR";
    })(Reason || (Reason = {}));
    var RecType;
    (function (RecType) {
        RecType["ondemand"] = "ondemand";
        RecType["service"] = "service";
        RecType["automatic"] = "automatic";
        RecType["ondemand_start"] = "ondemand_start";
        RecType["ondemand_stop"] = "ondemand_stop";
        RecType["error"] = "error";
    })(RecType || (RecType = {}));
    var Recipient;
    (function (Recipient) {
        Recipient["article_last_sender"] = "article_last_sender";
        Recipient["ticket_owner"] = "ticket_owner";
        Recipient["ticket_customer"] = "ticket_customer";
        Recipient["ticket_agents"] = "ticket_agents";
    })(Recipient || (Recipient = {}));
    var RegistrationConfiguration;
    (function (RegistrationConfiguration) {
        RegistrationConfiguration["DISABLED"] = "DISABLED";
        RegistrationConfiguration["ENABLED"] = "ENABLED";
        RegistrationConfiguration["CUSTOMIZABLE"] = "CUSTOMIZABLE";
        RegistrationConfiguration["AUTO"] = "AUTO";
        RegistrationConfiguration["AUTO_CUSTOMIZABLE"] = "AUTO_CUSTOMIZABLE";
        RegistrationConfiguration["ENABLED_ON_PHONE"] = "ENABLED_ON_PHONE";
    })(RegistrationConfiguration || (RegistrationConfiguration = {}));
    var Result;
    (function (Result) {
        Result["SUCCESS"] = "SUCCESS";
        Result["ERR_INITIALIZATION"] = "ERR_INITIALIZATION";
        Result["ERR_OPTIONS"] = "ERR_OPTIONS";
        Result["IN_PROGRESS"] = "IN_PROGRESS";
        Result["MRCP_FAILURE"] = "MRCP_FAILURE";
        Result["MRCP_TERMINATE"] = "MRCP_TERMINATE";
        Result["MRCP_CANCEL"] = "MRCP_CANCEL";
        Result["MRCP_UNKNOWN"] = "MRCP_UNKNOWN";
        Result["PARAM_ERROR"] = "PARAM_ERROR";
        Result["UNKNOWN"] = "UNKNOWN";
    })(Result || (Result = {}));
    var Roles;
    (function (Roles) {
        Roles["ADMIN"] = "Admin";
        Roles["AGENT"] = "Agent";
        Roles["CUSTOMER"] = "Customer";
    })(Roles || (Roles = {}));
    var RunPhase;
    (function (RunPhase) {
        RunPhase["START_REMOVE"] = "START_REMOVE";
        RunPhase["END_REMOVE"] = "END_REMOVE";
        RunPhase["START_IMPORT"] = "START_IMPORT";
        RunPhase["NOTIFY_IMPORT"] = "NOTIFY_IMPORT";
        RunPhase["END_IMPORT"] = "END_IMPORT";
        RunPhase["MSG"] = "MSG";
        RunPhase["NO_IMPORT_RUNNING"] = "NO_IMPORT_RUNNING";
    })(RunPhase || (RunPhase = {}));
    var SIPCompatibility;
    (function (SIPCompatibility) {
        SIPCompatibility["full"] = "full";
        SIPCompatibility["applicationLayerGateway"] = "applicationLayerGateway";
    })(SIPCompatibility || (SIPCompatibility = {}));
    var ScheduledJobTimeplanDays;
    (function (ScheduledJobTimeplanDays) {
        ScheduledJobTimeplanDays["Mon"] = "Mon";
        ScheduledJobTimeplanDays["Tue"] = "Tue";
        ScheduledJobTimeplanDays["Wed"] = "Wed";
        ScheduledJobTimeplanDays["Thu"] = "Thu";
        ScheduledJobTimeplanDays["Fri"] = "Fri";
        ScheduledJobTimeplanDays["Sat"] = "Sat";
        ScheduledJobTimeplanDays["Sun"] = "Sun";
    })(ScheduledJobTimeplanDays || (ScheduledJobTimeplanDays = {}));
    var SearchFilterApplication;
    (function (SearchFilterApplication) {
        SearchFilterApplication["ALL"] = "ALL";
        SearchFilterApplication["WEBCLIENT"] = "WEBCLIENT";
        SearchFilterApplication["ELEMENTMANAGER"] = "ELEMENTMANAGER";
        SearchFilterApplication["REPORT"] = "REPORT";
    })(SearchFilterApplication || (SearchFilterApplication = {}));
    var SearchFilterFieldComparator;
    (function (SearchFilterFieldComparator) {
        SearchFilterFieldComparator["EQ"] = "EQ";
        SearchFilterFieldComparator["NOTEQ"] = "NOTEQ";
        SearchFilterFieldComparator["IN"] = "IN";
        SearchFilterFieldComparator["NOTIN"] = "NOTIN";
        SearchFilterFieldComparator["CONTAIN"] = "CONTAIN";
        SearchFilterFieldComparator["NOTCONTAIN"] = "NOTCONTAIN";
        SearchFilterFieldComparator["STARTWITH"] = "STARTWITH";
        SearchFilterFieldComparator["ENDWITH"] = "ENDWITH";
        SearchFilterFieldComparator["GREATER"] = "GREATER";
        SearchFilterFieldComparator["GREATEREQ"] = "GREATEREQ";
        SearchFilterFieldComparator["LESS"] = "LESS";
        SearchFilterFieldComparator["LESSEQ"] = "LESSEQ";
    })(SearchFilterFieldComparator || (SearchFilterFieldComparator = {}));
    var SearchFilterScope;
    (function (SearchFilterScope) {
        SearchFilterScope["TICKET"] = "TICKET";
        SearchFilterScope["CALL"] = "CALL";
        SearchFilterScope["CHAT"] = "CHAT";
        SearchFilterScope["PHONEBOOK"] = "PHONEBOOK";
    })(SearchFilterScope || (SearchFilterScope = {}));
    var SearchFilterType;
    (function (SearchFilterType) {
        SearchFilterType["SYSTEM"] = "SYSTEM";
        SearchFilterType["PUBLIC"] = "PUBLIC";
        SearchFilterType["PRIVATE"] = "PRIVATE";
    })(SearchFilterType || (SearchFilterType = {}));
    var ServiceDevStatus;
    (function (ServiceDevStatus) {
        ServiceDevStatus["TRANSFER_TO_SERVICE"] = "TRANSFER_TO_SERVICE";
        ServiceDevStatus["TRANSFER_TO_NUMBER"] = "TRANSFER_TO_NUMBER";
        ServiceDevStatus["TRANSFER_TO_CALLBACK"] = "TRANSFER_TO_CALLBACK";
    })(ServiceDevStatus || (ServiceDevStatus = {}));
    var ServiceType;
    (function (ServiceType) {
        ServiceType["UC"] = "UC";
        ServiceType["CALLCENTER"] = "CALLCENTER";
        ServiceType["POWER_DIALER"] = "POWER_DIALER";
        ServiceType["TQM"] = "TQM";
        ServiceType["IVR"] = "IVR";
    })(ServiceType || (ServiceType = {}));
    var SocialAccountType;
    (function (SocialAccountType) {
        SocialAccountType["PAGE"] = "PAGE";
        SocialAccountType["PERSONAL"] = "PERSONAL";
    })(SocialAccountType || (SocialAccountType = {}));
    var SocialType;
    (function (SocialType) {
        SocialType["instagram"] = "instagram";
        SocialType["facebook"] = "facebook";
        SocialType["telegram"] = "telegram";
        SocialType["twitter"] = "twitter";
        SocialType["google"] = "google";
    })(SocialType || (SocialType = {}));
    var Status;
    (function (Status) {
        Status["CLIENT_ENABLED"] = "CLIENT_ENABLED";
        Status["SERVER_ENABLED"] = "SERVER_ENABLED";
        Status["DISABLED"] = "DISABLED";
    })(Status || (Status = {}));
    var StatusManagement;
    (function (StatusManagement) {
        StatusManagement["MANUAL"] = "MANUAL";
        StatusManagement["ALL_READY"] = "ALL_READY";
        StatusManagement["PRESERVE_READY"] = "PRESERVE_READY";
    })(StatusManagement || (StatusManagement = {}));
    var SwitchToGSMType;
    (function (SwitchToGSMType) {
        SwitchToGSMType["DISABLED"] = "DISABLED";
        SwitchToGSMType["BEFORE_ANSWER"] = "BEFORE_ANSWER";
        SwitchToGSMType["AFTER_ANSWER"] = "AFTER_ANSWER";
    })(SwitchToGSMType || (SwitchToGSMType = {}));
    var TQMTransferMode;
    (function (TQMTransferMode) {
        TQMTransferMode["QUEUE"] = "QUEUE";
        TQMTransferMode["BLIND"] = "BLIND";
    })(TQMTransferMode || (TQMTransferMode = {}));
    var TicketChannel;
    (function (TicketChannel) {
        TicketChannel["EMAIL"] = "EMAIL";
        TicketChannel["PHONE"] = "PHONE";
        TicketChannel["NOTE"] = "NOTE";
        TicketChannel["TWITTER"] = "TWITTER";
        TicketChannel["FACEBOOK"] = "FACEBOOK";
        TicketChannel["TELEGRAM"] = "TELEGRAM";
        TicketChannel["CHAT"] = "CHAT";
        TicketChannel["WEB"] = "WEB";
    })(TicketChannel || (TicketChannel = {}));
    var TicketEscalationLevel;
    (function (TicketEscalationLevel) {
        TicketEscalationLevel["ESCALATION_NEAR"] = "ESCALATION_NEAR";
        TicketEscalationLevel["ESCALATION_DONE"] = "ESCALATION_DONE";
    })(TicketEscalationLevel || (TicketEscalationLevel = {}));
    var TicketFieldMultiUpdate;
    (function (TicketFieldMultiUpdate) {
        TicketFieldMultiUpdate["state_id"] = "state_id";
        TicketFieldMultiUpdate["group"] = "group";
        TicketFieldMultiUpdate["owner_username"] = "owner_username";
        TicketFieldMultiUpdate["priority_id"] = "priority_id";
        TicketFieldMultiUpdate["read"] = "read";
        TicketFieldMultiUpdate["unread"] = "unread";
        TicketFieldMultiUpdate["t_custom_01"] = "t_custom_01";
        TicketFieldMultiUpdate["t_custom_02"] = "t_custom_02";
        TicketFieldMultiUpdate["t_custom_03"] = "t_custom_03";
        TicketFieldMultiUpdate["t_custom_04"] = "t_custom_04";
        TicketFieldMultiUpdate["t_custom_05"] = "t_custom_05";
        TicketFieldMultiUpdate["t_custom_06"] = "t_custom_06";
        TicketFieldMultiUpdate["t_custom_07"] = "t_custom_07";
        TicketFieldMultiUpdate["t_custom_08"] = "t_custom_08";
        TicketFieldMultiUpdate["t_custom_09"] = "t_custom_09";
        TicketFieldMultiUpdate["t_custom_10"] = "t_custom_10";
        TicketFieldMultiUpdate["t_custom_11"] = "t_custom_11";
        TicketFieldMultiUpdate["t_custom_12"] = "t_custom_12";
        TicketFieldMultiUpdate["t_custom_13"] = "t_custom_13";
        TicketFieldMultiUpdate["t_custom_14"] = "t_custom_14";
        TicketFieldMultiUpdate["t_custom_15"] = "t_custom_15";
        TicketFieldMultiUpdate["t_custom_16"] = "t_custom_16";
        TicketFieldMultiUpdate["t_custom_17"] = "t_custom_17";
        TicketFieldMultiUpdate["t_custom_18"] = "t_custom_18";
        TicketFieldMultiUpdate["t_custom_19"] = "t_custom_19";
        TicketFieldMultiUpdate["t_custom_20"] = "t_custom_20";
    })(TicketFieldMultiUpdate || (TicketFieldMultiUpdate = {}));
    var TicketMergeResult;
    (function (TicketMergeResult) {
        TicketMergeResult["SUCCESS"] = "success";
        TicketMergeResult["FAILED"] = "failed";
    })(TicketMergeResult || (TicketMergeResult = {}));
    var TicketPriority;
    (function (TicketPriority) {
        TicketPriority["LOW"] = "1 low";
        TicketPriority["NORMAL"] = "2 normal";
        TicketPriority["HIGH"] = "3 high";
    })(TicketPriority || (TicketPriority = {}));
    var TicketQueueType;
    (function (TicketQueueType) {
        TicketQueueType["PICKUP"] = "PICKUP";
        TicketQueueType["ACD"] = "ACD";
    })(TicketQueueType || (TicketQueueType = {}));
    var TicketState;
    (function (TicketState) {
        TicketState["NEW"] = "new";
        TicketState["OPEN"] = "open";
        TicketState["PENDING_REMINDER"] = "pending reminder";
        TicketState["CLOSED"] = "closed";
        TicketState["MERGED"] = "merged";
        TicketState["REMOVED"] = "removed";
        TicketState["PENDING_CLOSE"] = "pending close";
    })(TicketState || (TicketState = {}));
    var TicketStateId;
    (function (TicketStateId) {
        TicketStateId["NEW"] = "NEW";
        TicketStateId["OPEN"] = "OPEN";
        TicketStateId["PENDING_REMINDER"] = "PENDING_REMINDER";
        TicketStateId["CLOSED"] = "CLOSED";
        TicketStateId["MERGED"] = "MERGED";
        TicketStateId["REMOVED"] = "REMOVED";
        TicketStateId["PENDING_CLOSE"] = "PENDING_CLOSE";
    })(TicketStateId || (TicketStateId = {}));
    var TicketUnmanagedType;
    (function (TicketUnmanagedType) {
        TicketUnmanagedType["EMAIL"] = "EMAIL";
        TicketUnmanagedType["TWITTER"] = "TWITTER";
        TicketUnmanagedType["FACEBOOK"] = "FACEBOOK";
        TicketUnmanagedType["TELEGRAM"] = "TELEGRAM";
        TicketUnmanagedType["TICKET"] = "TICKET";
    })(TicketUnmanagedType || (TicketUnmanagedType = {}));
    var TransportType;
    (function (TransportType) {
        TransportType["PHONE"] = "PHONE";
        TransportType["VOICEMAIL"] = "VOICEMAIL";
        TransportType["FAX"] = "FAX";
        TransportType["SMS"] = "SMS";
    })(TransportType || (TransportType = {}));
    var TypeValue;
    (function (TypeValue) {
        TypeValue["CALL"] = "CALL";
        TypeValue["CHANNEL_1"] = "CHANNEL_1";
        TypeValue["CHANNEL_2"] = "CHANNEL_2";
        TypeValue["CHANNEL_3"] = "CHANNEL_3";
        TypeValue["MAIL"] = "MAIL";
        TypeValue["LIVEHELP"] = "LIVEHELP";
        TypeValue["VIDEO"] = "VIDEO";
        TypeValue["CHAT"] = "CHAT";
        TypeValue["WHATSAPP"] = "WHATSAPP";
        TypeValue["OMNIDESK"] = "OMNIDESK";
        TypeValue["CALLBACK"] = "CALLBACK";
    })(TypeValue || (TypeValue = {}));
    var UseDTLS;
    (function (UseDTLS) {
        UseDTLS["YES"] = "YES";
        UseDTLS["NO"] = "NO";
    })(UseDTLS || (UseDTLS = {}));
    var UserFavouriteContactType;
    (function (UserFavouriteContactType) {
        UserFavouriteContactType["user"] = "user";
        UserFavouriteContactType["service"] = "service";
        UserFavouriteContactType["external_addressbook"] = "external_addressbook";
        UserFavouriteContactType["personal_addressbook"] = "personal_addressbook";
        UserFavouriteContactType["short_number"] = "short_number";
    })(UserFavouriteContactType || (UserFavouriteContactType = {}));
    var UserInteractionServiceCode;
    (function (UserInteractionServiceCode) {
        UserInteractionServiceCode["DIR_GO"] = "DIR_GO";
        UserInteractionServiceCode["INBOUND_CALL_LIMIT"] = "INBOUND_CALL_LIMIT";
        UserInteractionServiceCode["AUTH_CODE"] = "AUTH_CODE";
        UserInteractionServiceCode["BLOCCO_TEL"] = "BLOCCO_TEL";
        UserInteractionServiceCode["VOICEMAIL"] = "VOICEMAIL";
        UserInteractionServiceCode["VOICEMAIL_SERVIZI"] = "VOICEMAIL_SERVIZI";
        UserInteractionServiceCode["LOGIN"] = "LOGIN";
        UserInteractionServiceCode["Ready_NotReady"] = "Ready_NotReady";
        UserInteractionServiceCode["CFWD"] = "CFWD";
        UserInteractionServiceCode["CFWD_VOICEMAIL"] = "CFWD_VOICEMAIL";
        UserInteractionServiceCode["CFWD_INT"] = "CFWD_INT";
        UserInteractionServiceCode["CFWD_CFWD_INT_VMAIL"] = "CFWD_CFWD_INT_VMAIL";
        UserInteractionServiceCode["CFWD_EXT"] = "CFWD_EXT";
        UserInteractionServiceCode["CFWD_CFWD_EXT_VMAIL"] = "CFWD_CFWD_EXT_VMAIL";
        UserInteractionServiceCode["CHANSPY"] = "CHANSPY";
        UserInteractionServiceCode["SEND_ALARM"] = "SEND_ALARM";
        UserInteractionServiceCode["ECHO_CODE"] = "ECHO_CODE";
        UserInteractionServiceCode["PRIVATE_CONFERENCE"] = "PRIVATE_CONFERENCE";
        UserInteractionServiceCode["PUBLIC_CONFERENCE"] = "PUBLIC_CONFERENCE";
        UserInteractionServiceCode["PARK"] = "PARK";
        UserInteractionServiceCode["PICKUP"] = "PICKUP";
        UserInteractionServiceCode["DND"] = "DND";
        UserInteractionServiceCode["REMOTE_FOWARD"] = "REMOTE_FOWARD";
    })(UserInteractionServiceCode || (UserInteractionServiceCode = {}));
    var UserInteractionStatus;
    (function (UserInteractionStatus) {
        UserInteractionStatus["ACTIVE"] = "ACTIVE";
        UserInteractionStatus["REMAINDER"] = "REMAINDER";
        UserInteractionStatus["CLOSED"] = "CLOSED";
    })(UserInteractionStatus || (UserInteractionStatus = {}));
    var UserInteractionType;
    (function (UserInteractionType) {
        UserInteractionType["call"] = "call";
        UserInteractionType["chat"] = "chat";
        UserInteractionType["note"] = "note";
        UserInteractionType["voicemail"] = "voicemail";
        UserInteractionType["fax"] = "fax";
        UserInteractionType["ticket"] = "ticket";
    })(UserInteractionType || (UserInteractionType = {}));
    var UserNoteType;
    (function (UserNoteType) {
        UserNoteType["note"] = "note";
        UserNoteType["list"] = "list";
    })(UserNoteType || (UserNoteType = {}));
    var UserOfGenericType;
    (function (UserOfGenericType) {
        UserOfGenericType["MOH"] = "MOH";
        UserOfGenericType["REC"] = "REC";
        UserOfGenericType["SERVICE"] = "SERVICE";
        UserOfGenericType["SERVICE_CODE"] = "SERVICE_CODE";
        UserOfGenericType["SKILLSET"] = "SKILLSET";
        UserOfGenericType["SKILLSET_SCHEDULE"] = "SKILLSET_SCHEDULE";
        UserOfGenericType["ADS_ALARM"] = "ADS_ALARM";
        UserOfGenericType["ADS_ALARM_LIST"] = "ADS_ALARM_LIST";
        UserOfGenericType["CONFERENCE"] = "CONFERENCE";
        UserOfGenericType["CONFERENCE_USER"] = "CONFERENCE_USER";
        UserOfGenericType["PARK"] = "PARK";
        UserOfGenericType["MOBILITY"] = "MOBILITY";
        UserOfGenericType["IVR"] = "IVR";
        UserOfGenericType["IVR_NODE"] = "IVR_NODE";
        UserOfGenericType["USER"] = "USER";
        UserOfGenericType["EXTEN"] = "EXTEN";
        UserOfGenericType["FAX"] = "FAX";
        UserOfGenericType["UNKNOWN"] = "UNKNOWN";
        UserOfGenericType["UC_DIRETTORE"] = "UC_DIRETTORE";
        UserOfGenericType["UC_ASSESSORE"] = "UC_ASSESSORE";
        UserOfGenericType["UC_SEGRETARIA"] = "UC_SEGRETARIA";
        UserOfGenericType["QUALITY_INTERVIEW"] = "QUALITY_INTERVIEW";
        UserOfGenericType["INBOUND_RULE"] = "INBOUND_RULE";
        UserOfGenericType["OUTBOUND_RULE"] = "OUTBOUND_RULE";
        UserOfGenericType["EMAIL_BOX"] = "EMAIL_BOX";
        UserOfGenericType["CALLRESULT_CODE"] = "CALLRESULT_CODE";
        UserOfGenericType["SWITCH_TO_GSM_HOLD"] = "SWITCH_TO_GSM_HOLD";
        UserOfGenericType["ABILITAZIONE_CALL"] = "ABILITAZIONE_CALL";
        UserOfGenericType["EMERGENCY_NUMBERS"] = "EMERGENCY_NUMBERS";
        UserOfGenericType["SITE"] = "SITE";
        UserOfGenericType["TRUNK"] = "TRUNK";
        UserOfGenericType["GENERIC_PARAM"] = "GENERIC_PARAM";
        UserOfGenericType["PICKUP_GROUP"] = "PICKUP_GROUP";
        UserOfGenericType["SHORT_NUMBER"] = "SHORT_NUMBER";
        UserOfGenericType["SLA"] = "SLA";
        UserOfGenericType["WIDGET"] = "WIDGET";
        UserOfGenericType["POWERDIALER_CAMPAIGN"] = "POWERDIALER_CAMPAIGN";
        UserOfGenericType["EXTERNAL_ACCOUNT"] = "EXTERNAL_ACCOUNT";
        UserOfGenericType["MEETING"] = "MEETING";
        UserOfGenericType["TCONSOLE_BLFSERVER"] = "TCONSOLE_BLFSERVER";
        UserOfGenericType["SUPPORT_CUSTOM_FIELD"] = "SUPPORT_CUSTOM_FIELD";
        UserOfGenericType["BPM_PROCESS"] = "BPM_PROCESS";
        UserOfGenericType["SURVEY"] = "SURVEY";
        UserOfGenericType["APPLICATION"] = "APPLICATION";
        UserOfGenericType["ADDRESSBOOK_PERSONAL"] = "ADDRESSBOOK_PERSONAL";
    })(UserOfGenericType || (UserOfGenericType = {}));
    var UserPermission;
    (function (UserPermission) {
        UserPermission["SUPERUSER"] = "SUPERUSER";
        UserPermission["SYSTEM_ADMIN"] = "SYSTEM_ADMIN";
        UserPermission["SUPERVISOR"] = "SUPERVISOR";
        UserPermission["UC_USERS"] = "UC_USERS";
        UserPermission["UC_SERVICES"] = "UC_SERVICES";
        UserPermission["UC_GROUP"] = "UC_GROUP";
        UserPermission["CC_USERS"] = "CC_USERS";
        UserPermission["CC_SERVICES"] = "CC_SERVICES";
        UserPermission["CC_SKILLSET"] = "CC_SKILLSET";
        UserPermission["ADDRESSBOOK"] = "ADDRESSBOOK";
        UserPermission["ACTIVITY_CODES"] = "ACTIVITY_CODES";
        UserPermission["CALL_RESULTS"] = "CALL_RESULTS";
        UserPermission["SURVEY"] = "SURVEY";
        UserPermission["AUDIO"] = "AUDIO";
        UserPermission["POPUP_MANAGER"] = "POPUP_MANAGER";
        UserPermission["MAIL_CHANNEL"] = "MAIL_CHANNEL";
        UserPermission["FACEBOOK_CHANNEL"] = "FACEBOOK_CHANNEL";
        UserPermission["TWITTER_CHANNEL"] = "TWITTER_CHANNEL";
        UserPermission["TELEGRAM_CHANNEL"] = "TELEGRAM_CHANNEL";
        UserPermission["IVR"] = "IVR";
        UserPermission["DEVICES"] = "DEVICES";
        UserPermission["DIALPLAN_ROUTING"] = "DIALPLAN_ROUTING";
        UserPermission["SHORT_NUMBERS"] = "SHORT_NUMBERS";
        UserPermission["CONFERENCE"] = "CONFERENCE";
        UserPermission["PICKUP_GROUPS"] = "PICKUP_GROUPS";
        UserPermission["FAX"] = "FAX";
        UserPermission["ADVANCED_SETTINGS"] = "ADVANCED_SETTINGS";
        UserPermission["EMAIL_SETTINGS"] = "EMAIL_SETTINGS";
        UserPermission["WIDGET"] = "WIDGET";
        UserPermission["CALENDAR"] = "CALENDAR";
        UserPermission["GRTD"] = "GRTD";
        UserPermission["CALL_NAVIGATOR"] = "CALL_NAVIGATOR";
        UserPermission["DOWNLOAD_FILE_AUDIO_RECORDED"] = "DOWNLOAD_FILE_AUDIO_RECORDED";
        UserPermission["CHAT_NAVIGATOR"] = "CHAT_NAVIGATOR";
        UserPermission["TICKET_NAVIGATOR"] = "TICKET_NAVIGATOR";
        UserPermission["LIVE_HELP_NAVIGATOR"] = "LIVE_HELP_NAVIGATOR";
        UserPermission["VIDEO_NAVIGATOR"] = "VIDEO_NAVIGATOR";
        UserPermission["SEND_ADMIN_CHAT"] = "SEND_ADMIN_CHAT";
        UserPermission["RESET_PASSWORD"] = "RESET_PASSWORD";
        UserPermission["CHANSPY"] = "CHANSPY";
        UserPermission["KNOWLEDGEBASE_READ"] = "KNOWLEDGEBASE_READ";
        UserPermission["KNOWLEDGEBASE_WRITE"] = "KNOWLEDGEBASE_WRITE";
        UserPermission["SUPPORT_EMAIL_FILTER"] = "SUPPORT_EMAIL_FILTER";
        UserPermission["REPORT_EXPORT"] = "REPORT_EXPORT";
        UserPermission["CUSTOM_CHANNEL_NAVIGATOR"] = "CUSTOM_CHANNEL_NAVIGATOR";
        UserPermission["INTRANET_CONFIG"] = "INTRANET_CONFIG";
        UserPermission["REPORT_MULTICHANNEL_AGENT"] = "REPORT_MULTICHANNEL_AGENT";
        UserPermission["TVOX_UPGRADE"] = "TVOX_UPGRADE";
        UserPermission["INSIGHT"] = "INSIGHT";
        UserPermission["SYSTEM_MONITOR"] = "SYSTEM_MONITOR";
        UserPermission["BPMN"] = "BPMN";
        UserPermission["CUSTOMER_PORTAL_ADMIN"] = "CUSTOMER_PORTAL_ADMIN";
        UserPermission["CDR"] = "CDR";
    })(UserPermission || (UserPermission = {}));
    var UserRoleType;
    (function (UserRoleType) {
        UserRoleType["TAM"] = "TAM";
        UserRoleType["TVOX"] = "TVOX";
        UserRoleType["TSAM"] = "TSAM";
        UserRoleType["MCS"] = "MCS";
        UserRoleType["CUSTOM"] = "CUSTOM";
    })(UserRoleType || (UserRoleType = {}));
    var UserStatus;
    (function (UserStatus) {
        UserStatus["BOOKED"] = "BOOKED";
        UserStatus["BUSY"] = "BUSY";
        UserStatus["NOTLOGGED"] = "NOTLOGGED";
        UserStatus["NR"] = "NR";
        UserStatus["NR_BUSY"] = "NR_BUSY";
        UserStatus["READY"] = "READY";
        UserStatus["WNR"] = "WNR";
    })(UserStatus || (UserStatus = {}));
    var WebOpenType;
    (function (WebOpenType) {
        WebOpenType["DISABLED"] = "DISABLED";
        WebOpenType["IFRAME"] = "IFRAME";
        WebOpenType["NEW_TAB"] = "NEW_TAB";
    })(WebOpenType || (WebOpenType = {}));
    var WhatToDoWithList;
    (function (WhatToDoWithList) {
        WhatToDoWithList["ADD"] = "ADD";
        WhatToDoWithList["DEL"] = "DEL";
        WhatToDoWithList["SUBSTITUTE"] = "SUBSTITUTE";
    })(WhatToDoWithList || (WhatToDoWithList = {}));
    var ZammadTriggerValue;
    (function (ZammadTriggerValue) {
        ZammadTriggerValue["create"] = "create";
        ZammadTriggerValue["update"] = "update";
    })(ZammadTriggerValue || (ZammadTriggerValue = {}));
    function isUserContact(addressBookContact) {
        return addressBookContact.type === "USER";
    }
    function isServiceContact(addressBookContact) {
        return addressBookContact.type === "SERVICE";
    }
    function isShortNumberContact(addressBookContact) {
        return addressBookContact.type === "SHORT_NUMBER";
    }
    function isExternalContact(addressBookContact) {
        return addressBookContact.type === "EXTERNAL_ITEM";
    }
    function isPersonalContact(addressBookContact) {
        return addressBookContact.type === "PERSONAL_ITEM";
    }
    function isExternalOrganizationContact(addressBookContact) {
        return addressBookContact.type === "EXTERNAL_ORGANIZATION";
    }

    class WebAPI {
        constructor(data) {
            this.clazz = data.clazz;
            this.code = data.code;
            this.exceptionName = data.exceptionName;
            this.cause = data.cause;
            this.stackTrace = data.stackTrace;
            this.localizedMessage = data.localizedMessage;
            this.message = data.message;
            this.suppressed = data.suppressed;
        }
    }
    class GenericObject extends WebAPI {
        constructor(data) {
            super(data);
            this.value = data.value;
            this.field = data.field;
            this.className = data.className || "GenericObjectException";
        }
    }
    class NoRouteToHost extends WebAPI {
        constructor(data) {
            super(data);
            this.exceptionName = data.exceptionName || "NoRouteToHostException";
        }
    }
    class ReconnectingInProgress extends WebAPI {
        constructor(data) {
            super(data);
            this.exceptionName = data.exceptionName || "ReconnectingInProgressException";
        }
    }
    class SocketClosed extends WebAPI {
        constructor(data) {
            super(data);
            this.exceptionName = data.exceptionName || "SocketClosedException";
        }
    }
    class StopOpenSocket extends WebAPI {
        constructor(data) {
            super(data);
            this.exceptionName = data.exceptionName || "StopOpenSocketException";
        }
    }
    class AuthorizationRequired extends WebAPI {
        constructor(data) {
            super(data);
            this.sessionId = data.sessionId;
            this.exceptionName = data.exceptionName || "AuthorizationRequiredException";
        }
    }
    AuthorizationRequired.CODE = 401;
    class PasswordExpired extends WebAPI {
        static newInstance(username, publicUsername, checkPasswordSecurityEnabled) {
            const result = new PasswordExpired({
                clazz: "",
                code: PasswordExpired.CODE,
                exceptionName: "PasswordExpiredException",
                message: "Password expired",
            });
            result.username = username;
            result.publicUsername = publicUsername;
            result.checkPasswordSecurityEnabled = checkPasswordSecurityEnabled;
            return result;
        }
    }
    PasswordExpired.CODE = 403;
    class UserNotEnabledOnMcs extends WebAPI {
        static newInstance(username, publicUsername) {
            const result = new UserNotEnabledOnMcs({
                clazz: "",
                code: UserNotEnabledOnMcs.CODE,
                exceptionName: "UserNotEnabledOnMcsException",
                message: "Login via MCS not enabled for user",
            });
            result.username = username;
            result.publicUsername = publicUsername;
            return result;
        }
    }
    UserNotEnabledOnMcs.CODE = 497;
    class UserNotEnabled extends WebAPI {
        static newInstance(username, publicUsername) {
            const result = new UserNotEnabled({
                clazz: "",
                code: UserNotEnabled.CODE,
                exceptionName: "UserNotEnabled",
                message: "Login not enabled for user",
            });
            result.username = username;
            result.publicUsername = publicUsername;
            return result;
        }
    }
    UserNotEnabled.CODE = 498;
    class CallInProgress extends WebAPI {
        static newInstance(callId) {
            const result = new CallInProgress({
                clazz: "",
                code: 803,
                exceptionName: "CallInProgressException",
                message: "Call is in progress",
            });
            result.callId = callId;
            return result;
        }
    }
    class TimeoutResponse extends WebAPI {
        constructor() {
            super({
                code: 1003,
                clazz: "",
                exceptionName: "TimeoutResponseException",
                message: "Timeout has occurred",
            });
        }
        static newInstance(message) {
            const result = new TimeoutResponse();
            if (message) {
                result.message = message;
            }
            return result;
        }
    }
    class CacheLimitSizeExceeded extends WebAPI {
        constructor(data) {
            super(data);
            this.exceededByte = data.exceededByte;
        }
    }
    class GenericObjectExists extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectFormat extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectIsInUse extends GenericObject {
        constructor(data) {
            super(data);
            this.users = data.users;
        }
    }
    class GenericObjectMinSize extends GenericObject {
        constructor(data) {
            super(data);
            this.minSize = data.minSize;
        }
    }
    class GenericObjectMaxSize extends GenericObject {
        constructor(data) {
            super(data);
            this.maxSize = data.maxSize;
        }
    }
    class GenericObjectRangeValue extends GenericObject {
        constructor(data) {
            super(data);
            this.minValue = data.minValue;
            this.maxValue = data.maxValue;
        }
    }
    class GenericObjectMaxValue extends GenericObjectRangeValue {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectMinValue extends GenericObjectRangeValue {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectRequiredDigitValue extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectRequiredNumberValue extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectSameSize extends GenericObject {
        constructor(data) {
            super(data);
            this.maxSize = data.maxSize;
        }
    }
    class GenericObjectUnchangeable extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class LogoutNotEnable extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class UseOfAgExternalNotEnableCauseNoMobilePhone extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class GenericObjectWasNotFound extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class InvalidArgument extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class InvalidAction extends GenericObject {
        constructor(data) {
            super(data);
        }
    }
    class InvalidLicence extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class LicenceExceeded extends WebAPI {
        constructor(data) {
            super(data);
            this.module = data.module;
        }
    }
    class MaxRetryExceeded extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class NoFileOnCache extends WebAPI {
        constructor(data) {
            super(data);
            this.fileName = data.fileName;
        }
    }
    class OperationIsNotAllowedToUser extends GenericObject {
        constructor(data) {
            super(data);
            this.sessionId = data.sessionId;
            this.mandatoryPermission = data.mandatoryPermission;
        }
    }
    class ActionNotPermitCauseActiveSession extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class WriteOperationIsNotAllowedToUser extends OperationIsNotAllowedToUser {
        constructor(data) {
            super(data);
        }
    }
    class WrongSessionId extends WebAPI {
        constructor(data) {
            super(data);
            this.sessionId = data.sessionId;
            this.newSessionId = data.newSessionId;
        }
    }
    class WrongVersion extends WebAPI {
        constructor(data) {
            super(data);
            this.sessionId = data.sessionId;
            this.versionRequired = data.versionRequired;
        }
    }
    class ConvertFile extends WebAPI {
        constructor(data) {
            super(data);
            this.reason = data.reason;
        }
    }
    class GenericObjectRequired extends GenericObject {
        constructor(data) {
            super(data);
            this.mandatoryFields = data.mandatoryFields;
        }
    }
    class DeviceRequestFailed extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class DeviceClosed extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class DeviceTimeout extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class TTS extends WebAPI {
        constructor(data) {
            super(data);
            this.result = data.result;
        }
    }
    class WidgetFormUpdate extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class ConfigurationError extends WebAPI {
        static newInstance(parameter, value, data) {
            const result = new ConfigurationError({
                clazz: "",
                code: 498,
                exceptionName: "ConfigurationErrorException",
                message: value ? `Invalid value ${JSON.stringify(value, MapOrSet_toJSON)} for parameter "${parameter}"` : `Missing parameter: ${parameter}`,
            });
            result.parameter = parameter;
            result.value = value;
            result.data = data;
            return result;
        }
    }

    function arrayConcat(...args) {
        let result = [];
        if (args && args.length) {
            args.forEach((arr) => {
                if (Array.isArray(arr) && !isEmpty(arr)) {
                    result.push.apply(result, arr);
                }
            });
        }
        return result;
    }
    function isEmpty(value) {
        return value === null || value === "" || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === "number" && isNaN(value));
    }
    const functionCheck = (value) => {
        return typeof value == "function" ? value : undefined;
    };
    const objectCheck = (value) => {
        return typeof value == "object" ? value : undefined;
    };
    const stringCheck = (value) => {
        return typeof value == "string" ? value : undefined;
    };
    const numberCheck = (value) => {
        return typeof value == "number" ? value : undefined;
    };
    const booleanCheck = (value) => {
        return typeof value == "boolean" ? value : undefined;
    };
    function loadConfig(prefix = [], checks, destination, source) {
        if (source == null || typeof source !== "object") {
            throw new Error("Configuration is not valid object");
        }
        prefix = arrayConcat(prefix);
        for (let parameter in checks.mandatory) {
            if (!source.hasOwnProperty(parameter)) {
                throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."));
            }
            else {
                const value = source[parameter];
                try {
                    const checked_value = checks.mandatory[parameter](value, prefix);
                    if (checked_value === undefined) {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."), value);
                    }
                    else {
                        destination[parameter] = checked_value;
                    }
                }
                catch (e) {
                    if (e.parameter) {
                        throw e;
                    }
                    else {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."), value, e);
                    }
                }
            }
        }
        for (let parameter in checks.optional) {
            if (source.hasOwnProperty(parameter)) {
                const value = source[parameter];
                if (isEmpty(value)) {
                    continue;
                }
                try {
                    const checked_value = checks.optional[parameter](value, prefix);
                    if (checked_value === undefined) {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."), value);
                    }
                    else {
                        destination[parameter] = checked_value;
                    }
                }
                catch (e) {
                    if (e.parameter) {
                        throw e;
                    }
                    else {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."), value, e);
                    }
                }
            }
        }
        return destination;
    }

    var MediaParam;
    (function (MediaParam) {
        function of(mediaParam) {
            return mediaParam instanceof MediaParamImpl ? mediaParam : new MediaParamImpl(mediaParam);
        }
        MediaParam.of = of;
        function toCallMedia(mediaParam) {
            return of(mediaParam).toCallMedia();
        }
        MediaParam.toCallMedia = toCallMedia;
    })(MediaParam || (MediaParam = {}));
    function buildMediaParam(callMedia) {
        return MediaParam.of(callMedia === null || callMedia === void 0 ? void 0 : callMedia.reduce((mediaParam, callMedia) => {
            if (callMedia) {
                mediaParam[callMedia.trim().toLowerCase()] = true;
            }
            return mediaParam;
        }, {}));
    }
    class MediaParamImpl {
        constructor(mediaParam) {
            this.audio = false;
            this.video = false;
            this.desktop = false;
            this.data = false;
            if (mediaParam) {
                this.audio = !!mediaParam.audio;
                this.video = !!mediaParam.video;
                this.desktop = !!mediaParam.desktop;
                this.data = !!mediaParam.data;
            }
        }
        _hasMedia() {
            return this.audio || this.video || this.desktop;
        }
        toCallMedia() {
            const callMedia = [];
            if (this.audio)
                callMedia.push(CallMedia.audio);
            if (this.video)
                callMedia.push(CallMedia.video);
            if (this.desktop)
                callMedia.push(CallMedia.desktop);
            if (this.data)
                callMedia.push(CallMedia.data);
            return callMedia;
        }
    }
    class RetryOptions {
        constructor(retry, prefix) {
            this.retries = 10;
            this.factor = 1.2;
            this.minTimeout = 5000;
            this.maxTimeout = 30000;
            this.randomize = true;
            this.forever = true;
            if (!retry)
                return;
            loadConfig(prefix, RetryOptions.CHECK_OPTIONS, this, retry);
        }
    }
    RetryOptions.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            retries: numberCheck,
            factor: numberCheck,
            minTimeout: numberCheck,
            maxTimeout: numberCheck,
            randomize: booleanCheck,
            forever: booleanCheck,
        },
    };

    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 browserExports = {};
    var browser$1 = {
      get exports(){ return browserExports; },
      set exports(v){ browserExports = v; },
    };

    var ms;
    var hasRequiredMs;
    function requireMs () {
    	if (hasRequiredMs) return ms;
    	hasRequiredMs = 1;
    	var s = 1000;
    	var m = s * 60;
    	var h = m * 60;
    	var d = h * 24;
    	var w = d * 7;
    	var y = d * 365.25;
    	ms = function(val, options) {
    	  options = options || {};
    	  var type = typeof val;
    	  if (type === 'string' && val.length > 0) {
    	    return parse(val);
    	  } else if (type === 'number' && isFinite(val)) {
    	    return options.long ? fmtLong(val) : fmtShort(val);
    	  }
    	  throw new Error(
    	    'val is not a non-empty string or a valid number. val=' +
    	      JSON.stringify(val)
    	  );
    	};
    	function parse(str) {
    	  str = String(str);
    	  if (str.length > 100) {
    	    return;
    	  }
    	  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
    	    str
    	  );
    	  if (!match) {
    	    return;
    	  }
    	  var n = parseFloat(match[1]);
    	  var type = (match[2] || 'ms').toLowerCase();
    	  switch (type) {
    	    case 'years':
    	    case 'year':
    	    case 'yrs':
    	    case 'yr':
    	    case 'y':
    	      return n * y;
    	    case 'weeks':
    	    case 'week':
    	    case 'w':
    	      return n * w;
    	    case 'days':
    	    case 'day':
    	    case 'd':
    	      return n * d;
    	    case 'hours':
    	    case 'hour':
    	    case 'hrs':
    	    case 'hr':
    	    case 'h':
    	      return n * h;
    	    case 'minutes':
    	    case 'minute':
    	    case 'mins':
    	    case 'min':
    	    case 'm':
    	      return n * m;
    	    case 'seconds':
    	    case 'second':
    	    case 'secs':
    	    case 'sec':
    	    case 's':
    	      return n * s;
    	    case 'milliseconds':
    	    case 'millisecond':
    	    case 'msecs':
    	    case 'msec':
    	    case 'ms':
    	      return n;
    	    default:
    	      return undefined;
    	  }
    	}
    	function fmtShort(ms) {
    	  var msAbs = Math.abs(ms);
    	  if (msAbs >= d) {
    	    return Math.round(ms / d) + 'd';
    	  }
    	  if (msAbs >= h) {
    	    return Math.round(ms / h) + 'h';
    	  }
    	  if (msAbs >= m) {
    	    return Math.round(ms / m) + 'm';
    	  }
    	  if (msAbs >= s) {
    	    return Math.round(ms / s) + 's';
    	  }
    	  return ms + 'ms';
    	}
    	function fmtLong(ms) {
    	  var msAbs = Math.abs(ms);
    	  if (msAbs >= d) {
    	    return plural(ms, msAbs, d, 'day');
    	  }
    	  if (msAbs >= h) {
    	    return plural(ms, msAbs, h, 'hour');
    	  }
    	  if (msAbs >= m) {
    	    return plural(ms, msAbs, m, 'minute');
    	  }
    	  if (msAbs >= s) {
    	    return plural(ms, msAbs, s, 'second');
    	  }
    	  return ms + ' ms';
    	}
    	function plural(ms, msAbs, n, name) {
    	  var isPlural = msAbs >= n * 1.5;
    	  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
    	}
    	return ms;
    }

    function setup(env) {
    	createDebug.debug = createDebug;
    	createDebug.default = createDebug;
    	createDebug.coerce = coerce;
    	createDebug.disable = disable;
    	createDebug.enable = enable;
    	createDebug.enabled = enabled;
    	createDebug.humanize = requireMs();
    	createDebug.destroy = destroy;
    	Object.keys(env).forEach(key => {
    		createDebug[key] = env[key];
    	});
    	createDebug.names = [];
    	createDebug.skips = [];
    	createDebug.formatters = {};
    	function selectColor(namespace) {
    		let hash = 0;
    		for (let i = 0; i < namespace.length; i++) {
    			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
    			hash |= 0;
    		}
    		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
    	}
    	createDebug.selectColor = selectColor;
    	function createDebug(namespace) {
    		let prevTime;
    		let enableOverride = null;
    		let namespacesCache;
    		let enabledCache;
    		function debug(...args) {
    			if (!debug.enabled) {
    				return;
    			}
    			const self = debug;
    			const curr = Number(new Date());
    			const ms = curr - (prevTime || curr);
    			self.diff = ms;
    			self.prev = prevTime;
    			self.curr = curr;
    			prevTime = curr;
    			args[0] = createDebug.coerce(args[0]);
    			if (typeof args[0] !== 'string') {
    				args.unshift('%O');
    			}
    			let index = 0;
    			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
    				if (match === '%%') {
    					return '%';
    				}
    				index++;
    				const formatter = createDebug.formatters[format];
    				if (typeof formatter === 'function') {
    					const val = args[index];
    					match = formatter.call(self, val);
    					args.splice(index, 1);
    					index--;
    				}
    				return match;
    			});
    			createDebug.formatArgs.call(self, args);
    			const logFn = self.log || createDebug.log;
    			logFn.apply(self, args);
    		}
    		debug.namespace = namespace;
    		debug.useColors = createDebug.useColors();
    		debug.color = createDebug.selectColor(namespace);
    		debug.extend = extend;
    		debug.destroy = createDebug.destroy;
    		Object.defineProperty(debug, 'enabled', {
    			enumerable: true,
    			configurable: false,
    			get: () => {
    				if (enableOverride !== null) {
    					return enableOverride;
    				}
    				if (namespacesCache !== createDebug.namespaces) {
    					namespacesCache = createDebug.namespaces;
    					enabledCache = createDebug.enabled(namespace);
    				}
    				return enabledCache;
    			},
    			set: v => {
    				enableOverride = v;
    			}
    		});
    		if (typeof createDebug.init === 'function') {
    			createDebug.init(debug);
    		}
    		return debug;
    	}
    	function extend(namespace, delimiter) {
    		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
    		newDebug.log = this.log;
    		return newDebug;
    	}
    	function enable(namespaces) {
    		createDebug.save(namespaces);
    		createDebug.namespaces = namespaces;
    		createDebug.names = [];
    		createDebug.skips = [];
    		let i;
    		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
    		const len = split.length;
    		for (i = 0; i < len; i++) {
    			if (!split[i]) {
    				continue;
    			}
    			namespaces = split[i].replace(/\*/g, '.*?');
    			if (namespaces[0] === '-') {
    				createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
    			} else {
    				createDebug.names.push(new RegExp('^' + namespaces + '$'));
    			}
    		}
    	}
    	function disable() {
    		const namespaces = [
    			...createDebug.names.map(toNamespace),
    			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
    		].join(',');
    		createDebug.enable('');
    		return namespaces;
    	}
    	function enabled(name) {
    		if (name[name.length - 1] === '*') {
    			return true;
    		}
    		let i;
    		let len;
    		for (i = 0, len = createDebug.skips.length; i < len; i++) {
    			if (createDebug.skips[i].test(name)) {
    				return false;
    			}
    		}
    		for (i = 0, len = createDebug.names.length; i < len; i++) {
    			if (createDebug.names[i].test(name)) {
    				return true;
    			}
    		}
    		return false;
    	}
    	function toNamespace(regexp) {
    		return regexp.toString()
    			.substring(2, regexp.toString().length - 2)
    			.replace(/\.\*\?$/, '*');
    	}
    	function coerce(val) {
    		if (val instanceof Error) {
    			return val.stack || val.message;
    		}
    		return val;
    	}
    	function destroy() {
    		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
    	}
    	createDebug.enable(createDebug.load());
    	return createDebug;
    }
    var common = setup;

    (function (module, exports) {
    	exports.formatArgs = formatArgs;
    	exports.save = save;
    	exports.load = load;
    	exports.useColors = useColors;
    	exports.storage = localstorage();
    	exports.destroy = (() => {
    		let warned = false;
    		return () => {
    			if (!warned) {
    				warned = true;
    				console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
    			}
    		};
    	})();
    	exports.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'
    	];
    	function useColors() {
    		if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
    			return true;
    		}
    		if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
    			return false;
    		}
    		return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
    			(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
    			(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
    			(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
    	}
    	function formatArgs(args) {
    		args[0] = (this.useColors ? '%c' : '') +
    			this.namespace +
    			(this.useColors ? ' %c' : ' ') +
    			args[0] +
    			(this.useColors ? '%c ' : ' ') +
    			'+' + module.exports.humanize(this.diff);
    		if (!this.useColors) {
    			return;
    		}
    		const c = 'color: ' + this.color;
    		args.splice(1, 0, c, 'color: inherit');
    		let index = 0;
    		let lastC = 0;
    		args[0].replace(/%[a-zA-Z%]/g, match => {
    			if (match === '%%') {
    				return;
    			}
    			index++;
    			if (match === '%c') {
    				lastC = index;
    			}
    		});
    		args.splice(lastC, 0, c);
    	}
    	exports.log = console.debug || console.log || (() => {});
    	function save(namespaces) {
    		try {
    			if (namespaces) {
    				exports.storage.setItem('debug', namespaces);
    			} else {
    				exports.storage.removeItem('debug');
    			}
    		} catch (error) {
    		}
    	}
    	function load() {
    		let r;
    		try {
    			r = exports.storage.getItem('debug');
    		} catch (error) {
    		}
    		if (!r && typeof process !== 'undefined' && 'env' in process) {
    			r = process.env.DEBUG;
    		}
    		return r;
    	}
    	function localstorage() {
    		try {
    			return localStorage;
    		} catch (error) {
    		}
    	}
    	module.exports = common(exports);
    	const {formatters} = module.exports;
    	formatters.j = function (v) {
    		try {
    			return JSON.stringify(v);
    		} catch (error) {
    			return '[UnexpectedJSONParseError]: ' + error.message;
    		}
    	};
    } (browser$1, browserExports));

    var LogLevel;
    (function (LogLevel) {
        LogLevel[LogLevel["Verbose"] = 1] = "Verbose";
        LogLevel[LogLevel["Debug"] = 2] = "Debug";
        LogLevel[LogLevel["Info"] = 3] = "Info";
        LogLevel[LogLevel["Warn"] = 4] = "Warn";
        LogLevel[LogLevel["Error"] = 5] = "Error";
        LogLevel[LogLevel["Fatal"] = 6] = "Fatal";
        LogLevel[LogLevel["None"] = 7] = "None";
    })(LogLevel || (LogLevel = {}));
    class LogStorageConfig {
        constructor(options, prefix) {
            if (!options)
                return;
            loadConfig(prefix, LogStorageConfig.CHECK_OPTIONS, this, options);
        }
    }
    LogStorageConfig.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            store: functionCheck,
            dump: functionCheck,
        },
    };
    class LogConfig {
        constructor(options, prefix) {
            this.enabled = true;
            this.prefix = "WebAPIclient";
            this.objectToJson = false;
            this.instanceIdLogged = false;
            this.logLevel = LogLevel.Debug;
            this.timestamp = true;
            if (!options)
                return;
            loadConfig(prefix, LogConfig.CHECK_OPTIONS, this, options);
        }
    }
    LogConfig.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            enabled: booleanCheck,
            prefix: stringCheck,
            objectToJson: booleanCheck,
            instanceIdLogged: booleanCheck,
            timestamp: booleanCheck,
            logLevel: (logLevel) => {
                if (logLevel && logLevel >= LogLevel.Verbose && logLevel <= LogLevel.None) {
                    return logLevel;
                }
                else {
                    return undefined;
                }
            },
            storage: (storageConfiguration, prefix) => {
                const value = objectCheck(storageConfiguration);
                return value ? new LogStorageConfig(value, arrayConcat(prefix, ["storage"])) : value;
            },
        },
    };

    browserExports.formatters.j = function (obj) {
        try {
            return undefined === obj ? "" : JSON.stringify(obj, MapOrSet_toJSON);
        }
        catch (error) {
            return "[UnexpectedJSONParseError]: " + error.message;
        }
    };
    class Logger {
    }
    class DefaultLogger extends Logger {
        constructor(
        conf) {
            super();
            this.conf = conf;
        }
        get objectToJson() {
            var _a;
            return (_a = this.conf.objectToJson) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.objectToJson;
        }
        get instanceIdLogged() {
            var _a;
            return (_a = this.conf.instanceIdLogged) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.instanceIdLogged;
        }
        get logLevel() {
            var _a;
            return (_a = this.conf.logLevel) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.logLevel;
        }
        get prefix() {
            var _a;
            return (_a = this.conf.prefix) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.prefix;
        }
        get timestamp() {
            var _a;
            return (_a = this.conf.timestamp) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.timestamp;
        }
        get storeLog() {
            var _a, _b, _c;
            return (_b = (_a = this.conf.storage) === null || _a === void 0 ? void 0 : _a.store) !== null && _b !== void 0 ? _b : (_c = DefaultLogConfigInstance.storage) === null || _c === void 0 ? void 0 : _c.store;
        }
    }
    const storeLogErrorHandler = (entry, err) => {
        try {
            console.error("error on store log entry", entry, err);
        }
        catch (e) { }
    };
    const LogLevelToString = new Map([
        [LogLevel.Verbose, LogLevel[LogLevel.Verbose].toUpperCase()],
        [LogLevel.Debug, LogLevel[LogLevel.Debug].toUpperCase()],
        [LogLevel.Info, LogLevel[LogLevel.Info].toUpperCase()],
        [LogLevel.Warn, LogLevel[LogLevel.Warn].toUpperCase()],
        [LogLevel.Error, LogLevel[LogLevel.Error].toUpperCase()],
        [LogLevel.Fatal, LogLevel[LogLevel.Fatal].toUpperCase()],
    ]);
    const DefaultLogConfigInstance = new LogConfig();
    const DefaultLogConfiguratorInstance = new DefaultLogger(DefaultLogConfigInstance);
    const debugMethods = new Map();
    class LogUtils {
        static dateToString(time) {
            if (typeof time === "string") {
                time = new Date(time);
            }
            return `${time.getFullYear()}-${zeroLeftPad(time.getMonth() + 1)}-${zeroLeftPad(time.getDate())} ${zeroLeftPad(time.getHours())}:${zeroLeftPad(time.getMinutes())}:${zeroLeftPad(time.getSeconds())}.${zeroLeftPad(time.getMilliseconds(), 3)}`;
        }
        static logEntryToString(logEntry) {
            var _a;
            return `${LogUtils.dateToString(logEntry.time)} [${(_a = LogLevelToString.get(logEntry.level)) === null || _a === void 0 ? void 0 : _a.substring(0, 4)}] ${logEntry.message}`;
        }
        static logEntryToStringObservableOperator() {
            return (source$) => {
                return source$.pipe(map(LogUtils.logEntryToString));
            };
        }
        static logEntryIterableToStringIterable(logs) {
            if (logs && !logs[Symbol.iterator]) {
                throw new Error("logEntryIterableToStringIterable - logs is not iterable, not implement Symbol.iterator");
            }
            return {
                *[Symbol.iterator]() {
                    if (logs) {
                        for (const logEntry of logs) {
                            yield LogUtils.logEntryToString(logEntry);
                        }
                    }
                },
            };
        }
    }
    let Log$1 = class Log {
        constructor(
        _pkg,
        _instanceId,
        _config) {
            this._pkg = _pkg;
            this._instanceId = _instanceId;
            this._config = _config;
            this.storeChain = Promise.resolve();
            this.logEntryInternalToLogEntry = (() => {
                const printLogOptions = { disableColors: true, timestamp: false, objectToJson: true, ignoreLogLevel: true, messageSeparator: "- " };
                let logData = null;
                const logCatcher = (...args) => {
                    logData = args;
                };
                return (logEntryInternal) => {
                    logData = [];
                    this.printlogTo(logEntryInternal, printLogOptions, logCatcher);
                    try {
                        if (!(logData && logData.length)) {
                            const logPrefix = [];
                            logPrefix.push("-");
                            logPrefix.push(logEntryInternal.message);
                            logData = logPrefix;
                        }
                        const logEntry = {
                            level: logEntryInternal.level,
                            time: logEntryInternal.time,
                            message: logData.join(" "),
                        };
                        return logEntry;
                    }
                    finally {
                        logData = null;
                    }
                };
            })();
            this.verbose = (message, ...args) => this._log(LogLevel.Verbose, null, message, args);
            this.debug = (message, ...args) => this._log(LogLevel.Debug, null, message, args);
            this.info = (message, ...args) => this._log(LogLevel.Info, null, message, args);
            this.warn = (message, ...args) => this._log(LogLevel.Warn, null, message, args);
            this.error = (message, ...args) => this._log(LogLevel.Error, null, message, args);
            this.fatal = (message, ...args) => this._log(LogLevel.Fatal, null, message, args);
            if (!_instanceId) {
                this._instanceId = "";
            }
            if (!_config) {
                this._config = DefaultLogConfiguratorInstance;
            }
        }
        static of(pkg, client) {
            const logger = Log.create(pkg);
            logger.client = client;
            return logger;
        }
        static create(pkg, instanceId, config) {
            return new Log(pkg, instanceId, config);
        }
        set client(client) {
            if (client) {
                this.instanceId = client.instanceId;
                this.config = client.logger;
            }
        }
        get config() {
            return this._config;
        }
        set config(config) {
            if (config) {
                this._config = config;
            }
        }
        get instanceId() {
            return this._instanceId;
        }
        set instanceId(instanceId) {
            this._instanceId = instanceId || "";
        }
        getDebugMethod(logEntry, config) {
            const packageName = `${this.config.prefix}${this.config.instanceIdLogged ? "_" + this._instanceId : ""}${logEntry.package ? `:${logEntry.package}` : ""}${(config === null || config === void 0 ? void 0 : config.ignoreLogLevel) ? "" : `:${LogLevelToString.get(logEntry.level)}`}`;
            let debugMethod = debugMethods.get(packageName);
            if (!debugMethod) {
                debugMethod = browserExports(packageName);
                debugMethods.set(packageName, debugMethod);
            }
            return debugMethod;
        }
        printlogTo(logEntry, config = { timestamp: this.config.timestamp, disableColors: false, objectToJson: this.config.objectToJson }, output) {
            const debug = this.getDebugMethod(logEntry, config);
            const defaultLogOutputter = debug.log;
            const defaultLogUseColor = debug.useColors;
            try {
                if (output) {
                    debug.log = output;
                }
                if (config.disableColors) {
                    debug.useColors = false;
                }
                const logMessage = [];
                if (config.timestamp) {
                    logMessage.push(LogUtils.dateToString(logEntry.time));
                    logMessage.push(" ");
                }
                if (config.messageSeparator) {
                    logMessage.push(config.messageSeparator);
                }
                logMessage.push(logEntry.message);
                if (config.objectToJson && logEntry.arguments.length) {
                    logMessage.push(" ");
                    logMessage.push("%j");
                }
                if (logEntry.arguments.length) {
                    debug(logMessage.join(""), ...logEntry.arguments);
                }
                else {
                    debug(logMessage.join(""));
                }
            }
            finally {
                debug.log = defaultLogOutputter;
                debug.useColors = defaultLogUseColor;
            }
        }
        storelog(logEntryInternal) {
            const storeLog = this.config.storeLog;
            if (storeLog) {
                const logEntry = this.logEntryInternalToLogEntry(logEntryInternal);
                this.storeChain = this.storeChain.then(storeLog.bind(this, logEntry)).catch(storeLogErrorHandler.bind(this, logEntry));
            }
        }
        _log(level, time, message, args) {
            if (level && level < LogLevel.None && level >= this.config.logLevel) {
                const logEntry = {
                    time: time !== null && time !== void 0 ? time : new Date(),
                    package: this._pkg,
                    level,
                    message,
                    arguments: args !== null && args !== void 0 ? args : [],
                };
                if (typeof message !== "string") {
                    logEntry.arguments.splice(0, 0, message);
                    logEntry.message = "";
                }
                this.printlogTo(logEntry);
                this.storelog(logEntry);
            }
        }
        log(level, message, ...args) {
            this._log(level, null, message, args);
        }
        logWithTimestamp(level, time, message, ...args) {
            this._log(level, time, message, args);
        }
    };
    const zeroLeftPad = (value, len = 2) => {
        let val = value.toString();
        try {
            return val.padStart(len, "0");
        }
        catch (e) {
            return val.length < len ? `0${val}` : val;
        }
    };

    var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
    var freeGlobal$1 = freeGlobal;

    var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
    var root = freeGlobal$1 || freeSelf || Function('return this')();
    var root$1 = root;

    var Symbol$1 = root$1.Symbol;
    var Symbol$2 = Symbol$1;

    var objectProto$5 = Object.prototype;
    var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
    var nativeObjectToString$1 = objectProto$5.toString;
    var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : undefined;
    function getRawTag(value) {
      var isOwn = hasOwnProperty$4.call(value, symToStringTag$1),
          tag = value[symToStringTag$1];
      try {
        value[symToStringTag$1] = undefined;
        var unmasked = true;
      } catch (e) {}
      var result = nativeObjectToString$1.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag$1] = tag;
        } else {
          delete value[symToStringTag$1];
        }
      }
      return result;
    }

    var objectProto$4 = Object.prototype;
    var nativeObjectToString = objectProto$4.toString;
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }

    var nullTag = '[object Null]',
        undefinedTag = '[object Undefined]';
    var symToStringTag = Symbol$2 ? Symbol$2.toStringTag : undefined;
    function baseGetTag(value) {
      if (value == null) {
        return value === undefined ? undefinedTag : nullTag;
      }
      return (symToStringTag && symToStringTag in Object(value))
        ? getRawTag(value)
        : objectToString(value);
    }

    function isObjectLike(value) {
      return value != null && typeof value == 'object';
    }

    var symbolTag = '[object Symbol]';
    function isSymbol(value) {
      return typeof value == 'symbol' ||
        (isObjectLike(value) && baseGetTag(value) == symbolTag);
    }

    var isArray = Array.isArray;
    var isArray$1 = isArray;

    var reWhitespace = /\s/;
    function trimmedEndIndex(string) {
      var index = string.length;
      while (index-- && reWhitespace.test(string.charAt(index))) {}
      return index;
    }

    var reTrimStart = /^\s+/;
    function baseTrim(string) {
      return string
        ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
        : string;
    }

    function isObject$2(value) {
      var type = typeof value;
      return value != null && (type == 'object' || type == 'function');
    }

    var NAN = 0 / 0;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    function toNumber(value) {
      if (typeof value == 'number') {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject$2(value)) {
        var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
        value = isObject$2(other) ? (other + '') : other;
      }
      if (typeof value != 'string') {
        return value === 0 ? value : +value;
      }
      value = baseTrim(value);
      var isBinary = reIsBinary.test(value);
      return (isBinary || reIsOctal.test(value))
        ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
        : (reIsBadHex.test(value) ? NAN : +value);
    }

    function identity(value) {
      return value;
    }

    var asyncTag = '[object AsyncFunction]',
        funcTag = '[object Function]',
        genTag = '[object GeneratorFunction]',
        proxyTag = '[object Proxy]';
    function isFunction(value) {
      if (!isObject$2(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
    }

    var coreJsData = root$1['__core-js_shared__'];
    var coreJsData$1 = coreJsData;

    var maskSrcKey = (function() {
      var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || '');
      return uid ? ('Symbol(src)_1.' + uid) : '';
    }());
    function isMasked(func) {
      return !!maskSrcKey && (maskSrcKey in func);
    }

    var funcProto$1 = Function.prototype;
    var funcToString$1 = funcProto$1.toString;
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString$1.call(func);
        } catch (e) {}
        try {
          return (func + '');
        } catch (e) {}
      }
      return '';
    }

    var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
    var reIsHostCtor = /^\[object .+?Constructor\]$/;
    var funcProto = Function.prototype,
        objectProto$3 = Object.prototype;
    var funcToString = funcProto.toString;
    var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
    var reIsNative = RegExp('^' +
      funcToString.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')
      .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
    );
    function baseIsNative(value) {
      if (!isObject$2(value) || isMasked(value)) {
        return false;
      }
      var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
      return pattern.test(toSource(value));
    }

    function getValue(object, key) {
      return object == null ? undefined : object[key];
    }

    function getNative(object, key) {
      var value = getValue(object, key);
      return baseIsNative(value) ? value : undefined;
    }

    function apply(func, thisArg, args) {
      switch (args.length) {
        case 0: return func.call(thisArg);
        case 1: return func.call(thisArg, args[0]);
        case 2: return func.call(thisArg, args[0], args[1]);
        case 3: return func.call(thisArg, args[0], args[1], args[2]);
      }
      return func.apply(thisArg, args);
    }

    function noop() {
    }

    var HOT_COUNT = 800,
        HOT_SPAN = 16;
    var nativeNow = Date.now;
    function shortOut(func) {
      var count = 0,
          lastCalled = 0;
      return function() {
        var stamp = nativeNow(),
            remaining = HOT_SPAN - (stamp - lastCalled);
        lastCalled = stamp;
        if (remaining > 0) {
          if (++count >= HOT_COUNT) {
            return arguments[0];
          }
        } else {
          count = 0;
        }
        return func.apply(undefined, arguments);
      };
    }

    function constant(value) {
      return function() {
        return value;
      };
    }

    var defineProperty = (function() {
      try {
        var func = getNative(Object, 'defineProperty');
        func({}, '', {});
        return func;
      } catch (e) {}
    }());
    var defineProperty$1 = defineProperty;

    var baseSetToString = !defineProperty$1 ? identity : function(func, string) {
      return defineProperty$1(func, 'toString', {
        'configurable': true,
        'enumerable': false,
        'value': constant(string),
        'writable': true
      });
    };
    var baseSetToString$1 = baseSetToString;

    var setToString = shortOut(baseSetToString$1);
    var setToString$1 = setToString;

    function baseFindIndex(array, predicate, fromIndex, fromRight) {
      var length = array.length,
          index = fromIndex + (fromRight ? 1 : -1);
      while ((fromRight ? index-- : ++index < length)) {
        if (predicate(array[index], index, array)) {
          return index;
        }
      }
      return -1;
    }

    function baseIsNaN(value) {
      return value !== value;
    }

    function strictIndexOf(array, value, fromIndex) {
      var index = fromIndex - 1,
          length = array.length;
      while (++index < length) {
        if (array[index] === value) {
          return index;
        }
      }
      return -1;
    }

    function baseIndexOf(array, value, fromIndex) {
      return value === value
        ? strictIndexOf(array, value, fromIndex)
        : baseFindIndex(array, baseIsNaN, fromIndex);
    }

    function arrayIncludes(array, value) {
      var length = array == null ? 0 : array.length;
      return !!length && baseIndexOf(array, value, 0) > -1;
    }

    function eq(value, other) {
      return value === other || (value !== value && other !== other);
    }

    var nativeMax$1 = Math.max;
    function overRest(func, start, transform) {
      start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0);
      return function() {
        var args = arguments,
            index = -1,
            length = nativeMax$1(args.length - start, 0),
            array = Array(length);
        while (++index < length) {
          array[index] = args[start + index];
        }
        index = -1;
        var otherArgs = Array(start + 1);
        while (++index < start) {
          otherArgs[index] = args[index];
        }
        otherArgs[start] = transform(array);
        return apply(func, this, otherArgs);
      };
    }

    function baseRest(func, start) {
      return setToString$1(overRest(func, start, identity), func + '');
    }

    var MAX_SAFE_INTEGER = 9007199254740991;
    function isLength(value) {
      return typeof value == 'number' &&
        value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
    }

    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction(value);
    }

    var argsTag = '[object Arguments]';
    function baseIsArguments(value) {
      return isObjectLike(value) && baseGetTag(value) == argsTag;
    }

    var objectProto$2 = Object.prototype;
    var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
    var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
    var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
      return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
        !propertyIsEnumerable.call(value, 'callee');
    };
    var isArguments$1 = isArguments;

    var nativeCreate = getNative(Object, 'create');
    var nativeCreate$1 = nativeCreate;

    function hashClear() {
      this.__data__ = nativeCreate$1 ? nativeCreate$1(null) : {};
      this.size = 0;
    }

    function hashDelete(key) {
      var result = this.has(key) && delete this.__data__[key];
      this.size -= result ? 1 : 0;
      return result;
    }

    var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
    var objectProto$1 = Object.prototype;
    var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
    function hashGet(key) {
      var data = this.__data__;
      if (nativeCreate$1) {
        var result = data[key];
        return result === HASH_UNDEFINED$2 ? undefined : result;
      }
      return hasOwnProperty$1.call(data, key) ? data[key] : undefined;
    }

    var objectProto = Object.prototype;
    var hasOwnProperty = objectProto.hasOwnProperty;
    function hashHas(key) {
      var data = this.__data__;
      return nativeCreate$1 ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
    }

    var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
    function hashSet(key, value) {
      var data = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data[key] = (nativeCreate$1 && value === undefined) ? HASH_UNDEFINED$1 : value;
      return this;
    }

    function Hash(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    Hash.prototype.clear = hashClear;
    Hash.prototype['delete'] = hashDelete;
    Hash.prototype.get = hashGet;
    Hash.prototype.has = hashHas;
    Hash.prototype.set = hashSet;

    function listCacheClear() {
      this.__data__ = [];
      this.size = 0;
    }

    function assocIndexOf(array, key) {
      var length = array.length;
      while (length--) {
        if (eq(array[length][0], key)) {
          return length;
        }
      }
      return -1;
    }

    var arrayProto = Array.prototype;
    var splice = arrayProto.splice;
    function listCacheDelete(key) {
      var data = this.__data__,
          index = assocIndexOf(data, key);
      if (index < 0) {
        return false;
      }
      var lastIndex = data.length - 1;
      if (index == lastIndex) {
        data.pop();
      } else {
        splice.call(data, index, 1);
      }
      --this.size;
      return true;
    }

    function listCacheGet(key) {
      var data = this.__data__,
          index = assocIndexOf(data, key);
      return index < 0 ? undefined : data[index][1];
    }

    function listCacheHas(key) {
      return assocIndexOf(this.__data__, key) > -1;
    }

    function listCacheSet(key, value) {
      var data = this.__data__,
          index = assocIndexOf(data, key);
      if (index < 0) {
        ++this.size;
        data.push([key, value]);
      } else {
        data[index][1] = value;
      }
      return this;
    }

    function ListCache(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype['delete'] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;

    var Map$1 = getNative(root$1, 'Map');
    var Map$2 = Map$1;

    function mapCacheClear() {
      this.size = 0;
      this.__data__ = {
        'hash': new Hash,
        'map': new (Map$2 || ListCache),
        'string': new Hash
      };
    }

    function isKeyable(value) {
      var type = typeof value;
      return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
        ? (value !== '__proto__')
        : (value === null);
    }

    function getMapData(map, key) {
      var data = map.__data__;
      return isKeyable(key)
        ? data[typeof key == 'string' ? 'string' : 'hash']
        : data.map;
    }

    function mapCacheDelete(key) {
      var result = getMapData(this, key)['delete'](key);
      this.size -= result ? 1 : 0;
      return result;
    }

    function mapCacheGet(key) {
      return getMapData(this, key).get(key);
    }

    function mapCacheHas(key) {
      return getMapData(this, key).has(key);
    }

    function mapCacheSet(key, value) {
      var data = getMapData(this, key),
          size = data.size;
      data.set(key, value);
      this.size += data.size == size ? 0 : 1;
      return this;
    }

    function MapCache(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype['delete'] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;

    function arrayPush(array, values) {
      var index = -1,
          length = values.length,
          offset = array.length;
      while (++index < length) {
        array[offset + index] = values[index];
      }
      return array;
    }

    var spreadableSymbol = Symbol$2 ? Symbol$2.isConcatSpreadable : undefined;
    function isFlattenable(value) {
      return isArray$1(value) || isArguments$1(value) ||
        !!(spreadableSymbol && value && value[spreadableSymbol]);
    }

    function baseFlatten(array, depth, predicate, isStrict, result) {
      var index = -1,
          length = array.length;
      predicate || (predicate = isFlattenable);
      result || (result = []);
      while (++index < length) {
        var value = array[index];
        if (depth > 0 && predicate(value)) {
          if (depth > 1) {
            baseFlatten(value, depth - 1, predicate, isStrict, result);
          } else {
            arrayPush(result, value);
          }
        } else if (!isStrict) {
          result[result.length] = value;
        }
      }
      return result;
    }

    var Set$1 = getNative(root$1, 'Set');
    var Set$2 = Set$1;

    var HASH_UNDEFINED = '__lodash_hash_undefined__';
    function setCacheAdd(value) {
      this.__data__.set(value, HASH_UNDEFINED);
      return this;
    }

    function setCacheHas(value) {
      return this.__data__.has(value);
    }

    function SetCache(values) {
      var index = -1,
          length = values == null ? 0 : values.length;
      this.__data__ = new MapCache;
      while (++index < length) {
        this.add(values[index]);
      }
    }
    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
    SetCache.prototype.has = setCacheHas;

    function cacheHas(cache, key) {
      return cache.has(key);
    }

    function setToArray(set) {
      var index = -1,
          result = Array(set.size);
      set.forEach(function(value) {
        result[++index] = value;
      });
      return result;
    }

    var now = function() {
      return root$1.Date.now();
    };
    var now$1 = now;

    var FUNC_ERROR_TEXT = 'Expected a function';
    var nativeMax = Math.max,
        nativeMin = Math.min;
    function debounce(func, wait, options) {
      var lastArgs,
          lastThis,
          maxWait,
          result,
          timerId,
          lastCallTime,
          lastInvokeTime = 0,
          leading = false,
          maxing = false,
          trailing = true;
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject$2(options)) {
        leading = !!options.leading;
        maxing = 'maxWait' in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time) {
        var args = lastArgs,
            thisArg = lastThis;
        lastArgs = lastThis = undefined;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result;
      }
      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime,
            timeWaiting = wait - timeSinceLastCall;
        return maxing
          ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
          : timeWaiting;
      }
      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime;
        return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
          (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
      }
      function timerExpired() {
        var time = now$1();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
      }
      function trailingEdge(time) {
        timerId = undefined;
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = undefined;
        return result;
      }
      function cancel() {
        if (timerId !== undefined) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = undefined;
      }
      function flush() {
        return timerId === undefined ? result : trailingEdge(now$1());
      }
      function debounced() {
        var time = now$1(),
            isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
          if (timerId === undefined) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            clearTimeout(timerId);
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === undefined) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }

    function isArrayLikeObject(value) {
      return isObjectLike(value) && isArrayLike(value);
    }

    function arrayIncludesWith(array, value, comparator) {
      var index = -1,
          length = array == null ? 0 : array.length;
      while (++index < length) {
        if (comparator(value, array[index])) {
          return true;
        }
      }
      return false;
    }

    var INFINITY = 1 / 0;
    var createSet = !(Set$2 && (1 / setToArray(new Set$2([,-0]))[1]) == INFINITY) ? noop : function(values) {
      return new Set$2(values);
    };
    var createSet$1 = createSet;

    var LARGE_ARRAY_SIZE = 200;
    function baseUniq(array, iteratee, comparator) {
      var index = -1,
          includes = arrayIncludes,
          length = array.length,
          isCommon = true,
          result = [],
          seen = result;
      if (comparator) {
        isCommon = false;
        includes = arrayIncludesWith;
      }
      else if (length >= LARGE_ARRAY_SIZE) {
        var set = iteratee ? null : createSet$1(array);
        if (set) {
          return setToArray(set);
        }
        isCommon = false;
        includes = cacheHas;
        seen = new SetCache;
      }
      else {
        seen = iteratee ? [] : result;
      }
      outer:
      while (++index < length) {
        var value = array[index],
            computed = iteratee ? iteratee(value) : value;
        value = (comparator || value !== 0) ? value : 0;
        if (isCommon && computed === computed) {
          var seenIndex = seen.length;
          while (seenIndex--) {
            if (seen[seenIndex] === computed) {
              continue outer;
            }
          }
          if (iteratee) {
            seen.push(computed);
          }
          result.push(value);
        }
        else if (!includes(seen, computed, comparator)) {
          if (seen !== result) {
            seen.push(computed);
          }
          result.push(value);
        }
      }
      return result;
    }

    var union = baseRest(function(arrays) {
      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
    });
    var union$1 = union;

    function toPromise$1(source) {
        return lastValueFrom(source, { defaultValue: undefined });
    }

    class LiveResultPromiseWrapper {
        constructor( liveResult) {
            this.liveResult = liveResult;
        }
        get result() {
            return toPromise$1(this.liveResult.result);
        }
        get notification() {
            return this.liveResult.notification;
        }
        get resultSync() {
            return this.liveResult.resultSync.pipe(map(toPromise$1));
        }
        get errorResolver() {
            return this.liveResult.errorResolver;
        }
        get stopResult() {
            return this.liveResult.stopResult;
        }
        get stopNotification() {
            return this.liveResult.stopNotification;
        }
    }
    class DialParams {
        constructor(params) {
            this.params = {
                privateCall: false,
                channelId: ChannelType.PhoneCall,
            };
            if (params && isObject$2(params)) {
                for (const key in params) {
                    this.params[key] = params[key];
                }
            }
            this.params.media = new MediaParamImpl(this.params.media);
        }
        equals(builder) {
            if (!builder) {
                return false;
            }
            for (var key in builder.params) {
                if (builder.params[key] !== this.params[key]) {
                    return false;
                }
            }
            return true;
        }
        isForApp() {
            var _a, _b;
            return (_b = (_a = this.params.fromDevice) === null || _a === void 0 ? void 0 : _a.startsWith("_app_")) !== null && _b !== void 0 ? _b : false;
        }
        toRequestParams(phoneManagerActive) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
            return [
                phoneManagerActive ? (_a = this.params.fromDeviceType) !== null && _a !== void 0 ? _a : null : null,
                phoneManagerActive ? (_b = this.params.fromDevice) !== null && _b !== void 0 ? _b : null : null,
                MediaParam.toCallMedia(this.params.media),
                (_c = this.params.accessCode) !== null && _c !== void 0 ? _c : null,
                this.params.contact ? this.params.contact.value : null,
                this.params.privateCall,
                (_d = this.params.calldata) !== null && _d !== void 0 ? _d : null,
                channelTypeToId((_e = this.params.channelId) !== null && _e !== void 0 ? _e : ChannelType.PhoneCall),
                null,
                (_f = this.params.serviceCode) !== null && _f !== void 0 ? _f : null,
                (_g = this.params.note1) !== null && _g !== void 0 ? _g : null,
                (_h = this.params.note2) !== null && _h !== void 0 ? _h : null,
                (_j = this.params.abandonedCallId) !== null && _j !== void 0 ? _j : null,
                this.params.contact,
                (_k = this.params.callbackRequestId) !== null && _k !== void 0 ? _k : null,
            ];
        }
    }
    class MethodExecutor {
        constructor(client) {
            this.client = client;
            this.log = Log$1.of("methods", client);
            this.transport = client.transport;
        }
        executeRequestPromise(request, requestTimeout) {
            return request.execute(this.client, requestTimeout);
        }
        executeRequestChunked(request, requestTimeout) {
            return request.execute(this.client, requestTimeout);
        }
        executeRequestPromiseUpdate(request, requestTimeout) {
            return request.execute(this.client, requestTimeout);
        }
        executeRequestChunkedUpdate(request, requestTimeout) {
            return request.execute(this.client, requestTimeout);
        }
        _buildResponse(request) {
            try {
                this._loadTransport(request);
            }
            catch (error) {
                return this.transport.emitError(request, error);
            }
            this.log.info(`Call method: ${request.method}`, request.parameters);
            return this.transport.buildResponse(request);
        }
        _loadTransport(request) {
            if (!this.transport.loading && !this.transport.connected && (!this.transport.getCrossStorage() || this.transport.getCrossStorage().getLevel() == Storagelevel.master)) {
                this.transport.load();
            }
        }
    }
    class NotificationManager {
        constructor(client, notificationId, request, result, modifyNotification) {
            this.client = client;
            this.request = request;
            this.result = result;
            this.modifyNotification = modifyNotification;
            this._started = false;
            this.log = Log$1.of(`NotificationManager:${notificationId}`, client);
        }
        get started() {
            return this._started;
        }
        start(requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                const stopResult = yield this.stop();
                if (stopResult) {
                    const response = this.request(requestTimeout);
                    const notify = toPromise$1(response.resultSync.pipe(first(), concatMap(identity$1)));
                    response.resultSync.pipe(skip(1), concatMap(identity$1), take(1)).subscribe(() => {
                        this.log.warn("Notification restored");
                    });
                    response.notification
                        .pipe(map((data) => this.modifyNotification(data)), catchError((e) => {
                        this.log.warn("Error on modifyNotification", e);
                        return of(null);
                    }))
                        .subscribe((data) => {
                        if (data) {
                            try {
                                this.result.next(data);
                            }
                            catch (e) {
                                this.log.error("Error on handle notification", e);
                            }
                        }
                    });
                    this.stopNotification = response.stopNotification;
                    this._started = true;
                    return notify;
                }
                else {
                    return stopResult;
                }
            });
        }
        stop() {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (yield ((_a = this.stopNotification) === null || _a === void 0 ? void 0 : _a.call(this))) {
                    this.stopNotification = undefined;
                    this._started = false;
                }
                return true;
            });
        }
    }

    class ExtenUsedBy extends WebAPI {
        constructor(data) {
            super(data);
            this.exten = data.exten;
            this.extenType = data.extenType;
            this.usedBy = data.usedBy;
            this.nameUsedBy = data.nameUsedBy;
        }
    }
    class InternalErrorWebAPI extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class FeatureNotSupported extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class FeatureNotAllowed extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class InvalidDateRange extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class MobileAccessNotSupported extends WebAPI {
        constructor(data) {
            super(data);
        }
    }
    class NRUserExcedeed extends WebAPI {
        constructor(data) {
            super(data);
        }
    }

    var Errors = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ActionNotPermitCauseActiveSession: ActionNotPermitCauseActiveSession,
        AuthorizationRequired: AuthorizationRequired,
        CacheLimitSizeExceeded: CacheLimitSizeExceeded,
        CallInProgress: CallInProgress,
        ConfigurationError: ConfigurationError,
        ConvertFile: ConvertFile,
        DeviceClosed: DeviceClosed,
        DeviceRequestFailed: DeviceRequestFailed,
        DeviceTimeout: DeviceTimeout,
        ExtenUsedBy: ExtenUsedBy,
        FeatureNotAllowed: FeatureNotAllowed,
        FeatureNotSupported: FeatureNotSupported,
        GenericObject: GenericObject,
        GenericObjectExists: GenericObjectExists,
        GenericObjectFormat: GenericObjectFormat,
        GenericObjectIsInUse: GenericObjectIsInUse,
        GenericObjectMaxSize: GenericObjectMaxSize,
        GenericObjectMaxValue: GenericObjectMaxValue,
        GenericObjectMinSize: GenericObjectMinSize,
        GenericObjectMinValue: GenericObjectMinValue,
        GenericObjectRangeValue: GenericObjectRangeValue,
        GenericObjectRequired: GenericObjectRequired,
        GenericObjectRequiredDigitValue: GenericObjectRequiredDigitValue,
        GenericObjectRequiredNumberValue: GenericObjectRequiredNumberValue,
        GenericObjectSameSize: GenericObjectSameSize,
        GenericObjectUnchangeable: GenericObjectUnchangeable,
        GenericObjectWasNotFound: GenericObjectWasNotFound,
        InternalErrorWebAPI: InternalErrorWebAPI,
        InvalidAction: InvalidAction,
        InvalidArgument: InvalidArgument,
        InvalidDateRange: InvalidDateRange,
        InvalidLicence: InvalidLicence,
        LicenceExceeded: LicenceExceeded,
        LogoutNotEnable: LogoutNotEnable,
        MaxRetryExceeded: MaxRetryExceeded,
        MobileAccessNotSupported: MobileAccessNotSupported,
        NRUserExcedeed: NRUserExcedeed,
        NoFileOnCache: NoFileOnCache,
        NoRouteToHost: NoRouteToHost,
        OperationIsNotAllowedToUser: OperationIsNotAllowedToUser,
        PasswordExpired: PasswordExpired,
        ReconnectingInProgress: ReconnectingInProgress,
        SocketClosed: SocketClosed,
        StopOpenSocket: StopOpenSocket,
        TTS: TTS,
        TimeoutResponse: TimeoutResponse,
        UseOfAgExternalNotEnableCauseNoMobilePhone: UseOfAgExternalNotEnableCauseNoMobilePhone,
        UserNotEnabled: UserNotEnabled,
        UserNotEnabledOnMcs: UserNotEnabledOnMcs,
        WebAPI: WebAPI,
        WidgetFormUpdate: WidgetFormUpdate,
        WriteOperationIsNotAllowedToUser: WriteOperationIsNotAllowedToUser,
        WrongSessionId: WrongSessionId,
        WrongVersion: WrongVersion
    });

    function isSendFeedbackCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.SEND_FEEDBACK;
    }
    function isDialCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.DIAL;
    }
    function isAnswerCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.ANSWER;
    }
    function isHoldCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.HOLD;
    }
    function isUnholdCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.UNHOLD;
    }
    function isCancelCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.CANCEL;
    }
    function isAttendedTransferCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.ATTENDED_TRANSFER;
    }
    function isBlindTransferCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.BLIND_TRANSFER;
    }
    function isSendDTMFCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.SEND_DTMF;
    }
    function isDialATXferOnGenericDeviceCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.ATXFER_GENERIC_DEVICE;
    }
    function isCancelTransferOnGenericDeviceCommand(clientCommand) {
        return clientCommand.command === ClientCommandRequest.CANCEL_ON_TRANSFER_GENERIC_DEVICE;
    }

    var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
            if (ar || !(i in from)) {
                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                ar[i] = from[i];
            }
        }
        return to.concat(ar || Array.prototype.slice.call(from));
    };
    var BrowserInfo =  (function () {
        function BrowserInfo(name, version, os) {
            this.name = name;
            this.version = version;
            this.os = os;
            this.type = 'browser';
        }
        return BrowserInfo;
    }());
    var NodeInfo =  (function () {
        function NodeInfo(version) {
            this.version = version;
            this.type = 'node';
            this.name = 'node';
            this.os = process.platform;
        }
        return NodeInfo;
    }());
    var SearchBotDeviceInfo =  (function () {
        function SearchBotDeviceInfo(name, version, os, bot) {
            this.name = name;
            this.version = version;
            this.os = os;
            this.bot = bot;
            this.type = 'bot-device';
        }
        return SearchBotDeviceInfo;
    }());
    var BotInfo =  (function () {
        function BotInfo() {
            this.type = 'bot';
            this.bot = true;
            this.name = 'bot';
            this.version = null;
            this.os = null;
        }
        return BotInfo;
    }());
    var ReactNativeInfo =  (function () {
        function ReactNativeInfo() {
            this.type = 'react-native';
            this.name = 'react-native';
            this.version = null;
            this.os = null;
        }
        return ReactNativeInfo;
    }());
    var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/;
    var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/;
    var REQUIRED_VERSION_PARTS = 3;
    var userAgentRules = [
        ['aol', /AOLShield\/([0-9\._]+)/],
        ['edge', /Edge\/([0-9\._]+)/],
        ['edge-ios', /EdgiOS\/([0-9\._]+)/],
        ['yandexbrowser', /YaBrowser\/([0-9\._]+)/],
        ['kakaotalk', /KAKAOTALK\s([0-9\.]+)/],
        ['samsung', /SamsungBrowser\/([0-9\.]+)/],
        ['silk', /\bSilk\/([0-9._-]+)\b/],
        ['miui', /MiuiBrowser\/([0-9\.]+)$/],
        ['beaker', /BeakerBrowser\/([0-9\.]+)/],
        ['edge-chromium', /EdgA?\/([0-9\.]+)/],
        [
            'chromium-webview',
            /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/,
        ],
        ['chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],
        ['phantomjs', /PhantomJS\/([0-9\.]+)(:?\s|$)/],
        ['crios', /CriOS\/([0-9\.]+)(:?\s|$)/],
        ['firefox', /Firefox\/([0-9\.]+)(?:\s|$)/],
        ['fxios', /FxiOS\/([0-9\.]+)/],
        ['opera-mini', /Opera Mini.*Version\/([0-9\.]+)/],
        ['opera', /Opera\/([0-9\.]+)(?:\s|$)/],
        ['opera', /OPR\/([0-9\.]+)(:?\s|$)/],
        ['pie', /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],
        ['pie', /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],
        ['netfront', /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],
        ['ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],
        ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],
        ['ie', /MSIE\s(7\.0)/],
        ['bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/],
        ['android', /Android\s([0-9\.]+)/],
        ['ios', /Version\/([0-9\._]+).*Mobile.*Safari.*/],
        ['safari', /Version\/([0-9\._]+).*Safari/],
        ['facebook', /FB[AS]V\/([0-9\.]+)/],
        ['instagram', /Instagram\s([0-9\.]+)/],
        ['ios-webview', /AppleWebKit\/([0-9\.]+).*Mobile/],
        ['ios-webview', /AppleWebKit\/([0-9\.]+).*Gecko\)$/],
        ['curl', /^curl\/([0-9\.]+)$/],
        ['searchbot', SEARCHBOX_UA_REGEX],
    ];
    var operatingSystemRules = [
        ['iOS', /iP(hone|od|ad)/],
        ['Android OS', /Android/],
        ['BlackBerry OS', /BlackBerry|BB10/],
        ['Windows Mobile', /IEMobile/],
        ['Amazon OS', /Kindle/],
        ['Windows 3.11', /Win16/],
        ['Windows 95', /(Windows 95)|(Win95)|(Windows_95)/],
        ['Windows 98', /(Windows 98)|(Win98)/],
        ['Windows 2000', /(Windows NT 5.0)|(Windows 2000)/],
        ['Windows XP', /(Windows NT 5.1)|(Windows XP)/],
        ['Windows Server 2003', /(Windows NT 5.2)/],
        ['Windows Vista', /(Windows NT 6.0)/],
        ['Windows 7', /(Windows NT 6.1)/],
        ['Windows 8', /(Windows NT 6.2)/],
        ['Windows 8.1', /(Windows NT 6.3)/],
        ['Windows 10', /(Windows NT 10.0)/],
        ['Windows ME', /Windows ME/],
        ['Windows CE', /Windows CE|WinCE|Microsoft Pocket Internet Explorer/],
        ['Open BSD', /OpenBSD/],
        ['Sun OS', /SunOS/],
        ['Chrome OS', /CrOS/],
        ['Linux', /(Linux)|(X11)/],
        ['Mac OS', /(Mac_PowerPC)|(Macintosh)/],
        ['QNX', /QNX/],
        ['BeOS', /BeOS/],
        ['OS/2', /OS\/2/],
    ];
    function detect(userAgent) {
        if (!!userAgent) {
            return parseUserAgent(userAgent);
        }
        if (typeof document === 'undefined' &&
            typeof navigator !== 'undefined' &&
            navigator.product === 'ReactNative') {
            return new ReactNativeInfo();
        }
        if (typeof navigator !== 'undefined') {
            return parseUserAgent(navigator.userAgent);
        }
        return getNodeVersion();
    }
    function matchUserAgent(ua) {
        return (ua !== '' &&
            userAgentRules.reduce(function (matched, _a) {
                var browser = _a[0], regex = _a[1];
                if (matched) {
                    return matched;
                }
                var uaMatch = regex.exec(ua);
                return !!uaMatch && [browser, uaMatch];
            }, false));
    }
    function parseUserAgent(ua) {
        var matchedRule = matchUserAgent(ua);
        if (!matchedRule) {
            return null;
        }
        var name = matchedRule[0], match = matchedRule[1];
        if (name === 'searchbot') {
            return new BotInfo();
        }
        var versionParts = match[1] && match[1].split('.').join('_').split('_').slice(0, 3);
        if (versionParts) {
            if (versionParts.length < REQUIRED_VERSION_PARTS) {
                versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true);
            }
        }
        else {
            versionParts = [];
        }
        var version = versionParts.join('.');
        var os = detectOS(ua);
        var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua);
        if (searchBotMatch && searchBotMatch[1]) {
            return new SearchBotDeviceInfo(name, version, os, searchBotMatch[1]);
        }
        return new BrowserInfo(name, version, os);
    }
    function detectOS(ua) {
        for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) {
            var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1];
            var match = regex.exec(ua);
            if (match) {
                return os;
            }
        }
        return null;
    }
    function getNodeVersion() {
        var isNode = typeof process !== 'undefined' && process.version;
        return isNode ? new NodeInfo(process.version.slice(1)) : null;
    }
    function createVersionParts(count) {
        var output = [];
        for (var ii = 0; ii < count; ii++) {
            output.push('0');
        }
        return output;
    }

    var TLinkError = (function () {
        function TLinkError(message, parent) {
            this.message = message;
            this.parent = parent;
        }
        return TLinkError;
    }());

    var LogProvider = (function () {
        function LogProvider() {
        }
        LogProvider.prototype.isLogEnabled = function (level) {
            return level && level < Level.None && level >= this.logLevel;
        };
        return LogProvider;
    }());
    var LogPrefix = "[TLink] ";
    var DefaultLogProvider = (function (_super) {
        __extends(DefaultLogProvider, _super);
        function DefaultLogProvider() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(DefaultLogProvider.prototype, "logLevel", {
            get: function () {
                return Level.Verbose;
            },
            enumerable: false,
            configurable: true
        });
        DefaultLogProvider.prototype.log = function (event) {
            switch (event.level) {
                case Level.Verbose:
                case Level.Debug:
                case Level.Info:
                    if (event.error) {
                        console.log(LogPrefix + event.message, event.error);
                    }
                    else {
                        console.log(LogPrefix + event.message);
                    }
                    break;
                case Level.Warn:
                    if (event.error) {
                        console.warn(LogPrefix + event.message, event.error);
                    }
                    else {
                        console.warn(LogPrefix + event.message);
                    }
                    break;
                case Level.Error:
                    if (event.error) {
                        console.error(LogPrefix + event.message, event.error);
                    }
                    else {
                        console.error(LogPrefix + event.message);
                    }
                    break;
            }
        };
        return DefaultLogProvider;
    }(LogProvider));
    var provider = new DefaultLogProvider();
    function registerProvider(logProvider) {
        provider = logProvider;
    }
    function debug(message, error) {
        log$1(Level.Debug, message, error);
    }
    function info(message, error) {
        log$1(Level.Info, message, error);
    }
    function log$1(level, message, error) {
        provider.log(new LogEvent(level, message, error));
    }
    var Level;
    (function (Level) {
        Level[Level["Verbose"] = 1] = "Verbose";
        Level[Level["Debug"] = 2] = "Debug";
        Level[Level["Info"] = 3] = "Info";
        Level[Level["Warn"] = 4] = "Warn";
        Level[Level["Error"] = 5] = "Error";
        Level[Level["None"] = 7] = "None";
    })(Level || (Level = {}));
    var LogEvent = (function () {
        function LogEvent(level, message, error) {
            this.level = level;
            this.message = message;
            this.error = error;
            this.timestamp = new Date();
        }
        return LogEvent;
    }());

    var AudioContextClass = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext;
    var audioContextInstance$1;
    function getAudioContextInstance() {
        if (!audioContextInstance$1) {
            audioContextInstance$1 = newAudioContext();
        }
        return audioContextInstance$1;
    }
    function newAudioContext() {
        return new AudioContextClass();
    }
    function retriveAudioContextState() {
        return __awaiter(this, void 0, void 0, function () {
            var _audioContext, closeAudioContext, audioContextState;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _audioContext = null;
                        closeAudioContext = false;
                        audioContextState = null;
                        if (AudioContextClass) {
                            try {
                                _audioContext = new AudioContextClass();
                                closeAudioContext = true;
                            }
                            catch (e) {
                                _audioContext = audioContextInstance$1;
                            }
                            audioContextState = _audioContext ? _audioContext.state : null;
                        }
                        if (!closeAudioContext) return [3, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4, (_audioContext === null || _audioContext === void 0 ? void 0 : _audioContext.close())];
                    case 2:
                        _a.sent();
                        _audioContext = null;
                        return [3, 4];
                    case 3:
                        _a.sent();
                        return [3, 4];
                    case 4: return [2, audioContextState];
                }
            });
        });
    }
    var gestureRequiredValue = true;
    function isGestureRequiredForPlay() {
        return gestureRequiredValue;
    }
    function userGestureIsRequiredForMediaElement() {
        return __awaiter(this, void 0, void 0, function () {
            var audioSilence, autoPlayAllowed, mediaElement, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        audioSilence = "data:audio/wav;base64,UklGRjIAAABXQVZFZm10IBIAAAABAAEAQB8AAEAfAAABAAgAAABmYWN0BAAAAAAAAABkYXRhAAAAAA==";
                        autoPlayAllowed = true;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 6, , 7]);
                        mediaElement = new Audio();
                        mediaElement.src = audioSilence;
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4, mediaElement.play()];
                    case 3:
                        _a.sent();
                        return [3, 5];
                    case 4:
                        error_1 = _a.sent();
                        if (error_1.name == "NotAllowedError") {
                            autoPlayAllowed = false;
                        }
                        return [3, 5];
                    case 5:
                        if (autoPlayAllowed) {
                            mediaElement.pause();
                            mediaElement = null;
                        }
                        return [2, autoPlayAllowed];
                    case 6:
                        _a.sent();
                        return [2, false];
                    case 7: return [2];
                }
            });
        });
    }
    function checkUserGestureRequired() {
        return __awaiter(this, void 0, void 0, function () {
            var result, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        debug("CheckUserGesture START");
                        return [4, Promise.all([retriveAudioContextState(), userGestureIsRequiredForMediaElement()])];
                    case 1:
                        result = _a.sent();
                        debug("CheckUserGesture END: AudioContext state '".concat(result[0], "' - AudioElement autoPlay allowed '").concat(result[1], "'"));
                        response = result[0] === "suspended" || !result[1];
                        if (response) {
                            debug("User gesture is required for play audio");
                        }
                        else {
                            debug("User gesture is not required for play audio");
                        }
                        return [2, response];
                }
            });
        });
    }
    var documentClickHandler = debounce(function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    debug("document emit click event so checking can play audio");
                    return [4, checkUserGestureRequired()];
                case 1:
                    if (_a.sent()) {
                        gestureRequiredValue = true;
                    }
                    else {
                        document.removeEventListener("click", documentClickHandler);
                        gestureRequiredValue = false;
                        if (audioContextInstance$1) {
                            audioContextInstance$1.resume();
                        }
                    }
                    return [2];
            }
        });
    }); }, 5000, { leading: true });
    (function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4, checkUserGestureRequired()];
                case 1:
                    if (_a.sent()) {
                        document.addEventListener("click", documentClickHandler);
                        gestureRequiredValue = true;
                    }
                    else {
                        gestureRequiredValue = false;
                    }
                    return [2];
            }
        });
    }); })();

    function vuMeterOfMediaStream(mediaStream, onLevel, updateIntervalInMS) {
        if (updateIntervalInMS === void 0) { updateIntervalInMS = 25; }
        return __awaiter(this, void 0, void 0, function () {
            var audioContext;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, getAudioContextForVuMeter()];
                    case 1:
                        audioContext = _a.sent();
                        if (window.AudioWorkletNode) {
                            return [2, new VUMeterNodeImpl(audioContext, mediaStream, onLevel, updateIntervalInMS !== null && updateIntervalInMS !== void 0 ? updateIntervalInMS : 25)];
                        }
                        else {
                            return [2, new VUMeter(audioContext, mediaStream, onLevel)];
                        }
                }
            });
        });
    }
    var VUMeterNodeImpl = (function () {
        function VUMeterNodeImpl(audioContext, mediaStream, onLevel, updateIntervalInMS) {
            var _this = this;
            this.onLevel = onLevel;
            this.started = false;
            this.onprocessorerror = null;
            this._audioWorkletNode = new AudioWorkletNode(audioContext, "vumeter", {
                numberOfInputs: 1,
                numberOfOutputs: 0,
                channelCount: 1,
                processorOptions: { updateIntervalInMS: updateIntervalInMS < 0 ? 25 : updateIntervalInMS },
            });
            this._audioWorkletNode.onprocessorerror = function (ev) {
                var _a;
                (_a = _this.onprocessorerror) === null || _a === void 0 ? void 0 : _a.call(_this, ev);
            };
            this._mediaStream = audioContext.createMediaStreamSource(mediaStream);
            this._updateIntervalInMS = updateIntervalInMS;
            this._audioWorkletNode.port.onmessage = function (event) {
                var _a;
                if (event.data.volume)
                    (_a = _this.onLevel) === null || _a === void 0 ? void 0 : _a.call(_this, event.data.volume);
            };
        }
        Object.defineProperty(VUMeterNodeImpl.prototype, "updateInterval", {
            get: function () {
                return this._updateIntervalInMS;
            },
            set: function (updateIntervalInMS) {
                this._updateIntervalInMS = updateIntervalInMS;
                this._audioWorkletNode.port.postMessage({ updateIntervalInMS: updateIntervalInMS });
            },
            enumerable: false,
            configurable: true
        });
        VUMeterNodeImpl.prototype.start = function () {
            if (!this.started) {
                this._mediaStream.connect(this._audioWorkletNode);
                this.started = true;
            }
        };
        VUMeterNodeImpl.prototype.stop = function () {
            if (this.started) {
                this._mediaStream.disconnect(this._audioWorkletNode);
                this.started = false;
            }
        };
        return VUMeterNodeImpl;
    }());
    var VUMeter = (function () {
        function VUMeter(audioContext, mediaStream, onLevel) {
            this.audioContext = audioContext;
            this.mediaStream = mediaStream;
            this.onLevel = onLevel;
            this.onprocessorerror = null;
            this.started = false;
        }
        VUMeter.prototype.start = function () {
            var _this = this;
            var _a, _b, _c;
            if (!this.started) {
                this._mediaStream = this.audioContext.createMediaStreamSource(this.mediaStream);
                this._audioAnalyser = this.audioContext.createAnalyser();
                this._audioScriptNode = this.audioContext.createScriptProcessor(2048, 1, 1);
                (_a = this._mediaStream) === null || _a === void 0 ? void 0 : _a.connect(this._audioAnalyser);
                (_b = this._audioAnalyser) === null || _b === void 0 ? void 0 : _b.connect(this._audioScriptNode);
                (_c = this._audioScriptNode) === null || _c === void 0 ? void 0 : _c.connect(this.audioContext.destination);
                this._audioScriptNode.onaudioprocess = function (event) {
                    var input = event.inputBuffer.getChannelData(0);
                    var sum = 0;
                    for (var i = 0; i < input.length; ++i)
                        sum += input[i] * input[i];
                    _this.onLevel(Math.sqrt(sum / input.length));
                };
                this.started = true;
            }
        };
        VUMeter.prototype.stop = function () {
            if (this.started) {
                if (this._mediaStream) {
                    if (this._audioAnalyser) {
                        this._mediaStream.disconnect(this._audioAnalyser);
                    }
                    this._mediaStream = null;
                }
                if (this._audioAnalyser) {
                    if (this._audioScriptNode) {
                        this._audioAnalyser.disconnect(this._audioScriptNode);
                    }
                    this._audioAnalyser = null;
                }
                if (this._audioScriptNode) {
                    if (this.audioContext) {
                        this._audioScriptNode.disconnect(this.audioContext.destination);
                    }
                    this._audioScriptNode = null;
                }
                this.started = false;
            }
        };
        return VUMeter;
    }());
    var vumeterProcessorModule;
    function getAudioContextForVuMeter() {
        return __awaiter(this, void 0, void 0, function () {
            var audioContext, node;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        audioContext = getAudioContextInstance();
                        if (!window.AudioWorkletNode) return [3, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 2, , 4]);
                        node = new window.AudioWorkletNode(audioContext, "vumeter", {
                            numberOfInputs: 1,
                            numberOfOutputs: 0,
                            channelCount: 1,
                            processorOptions: { updateIntervalInMS: 25 },
                        });
                        node.disconnect();
                        return [3, 4];
                    case 2:
                        _a.sent();
                        if (!vumeterProcessorModule) {
                            vumeterProcessorModule = URL.createObjectURL(new Blob(["registerProcessor(\"vumeter\",class extends AudioWorkletProcessor{_updateIntervalInMS;_nextUpdateFrame;constructor(e){super(),this._updateIntervalInMS=e.processorOptions.updateIntervalInMS,this._nextUpdateFrame=this.intervalInFrames,this.port.onmessage=e=>{e.data.updateIntervalInMS&&(this._updateIntervalInMS=e.data.updateIntervalInMS)}}get intervalInFrames(){return this._updateIntervalInMS/1e3*sampleRate}process(e,t,a){const r=e[0];if(r.length>0){const e=r[0];if(this._nextUpdateFrame-=e.length,this._nextUpdateFrame<0){let t=0;for(let a=0;a<e.length;++a)t+=e[a]*e[a];this.port.postMessage({volume:Math.sqrt(t/e.length)}),this._nextUpdateFrame+=this.intervalInFrames}}return!0}});"], { type: "text/javascript" }));
                        }
                        return [4, audioContext.audioWorklet.addModule(vumeterProcessorModule)];
                    case 3:
                        _a.sent();
                        return [3, 4];
                    case 4: return [2, audioContext];
                }
            });
        });
    }

    var supportedFeature = {
        setSinkId: null,
        createMediaStreamDestination: null,
    };
    function setSinkOutput(element, deviceId) {
        return __awaiter(this, void 0, void 0, function () {
            var e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(supportedFeature.setSinkId !== false)) return [3, 5];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        if (!((deviceId !== null && deviceId !== void 0 ? deviceId : null) !== null)) return [3, 3];
                        return [4, element.setSinkId(deviceId)];
                    case 2:
                        _a.sent();
                        supportedFeature.setSinkId = true;
                        _a.label = 3;
                    case 3: return [2, true];
                    case 4:
                        e_1 = _a.sent();
                        if (!(e_1 instanceof DOMException)) {
                            supportedFeature.setSinkId = false;
                        }
                        throw e_1;
                    case 5: return [2, !!supportedFeature.setSinkId];
                }
            });
        });
    }
    function audioTrackLevelToObservable(mediaStream, updateIntervalInMS) {
        return new Observable(function (observer) {
            var vuMeterNode = vuMeterOfMediaStream(mediaStream, function (volume) { return observer.next(volume); }, updateIntervalInMS)
                .then(function (vuMeter) {
                vuMeter.onprocessorerror = function (err) { return console.error("vuMeterNode - Error on process", err); };
                vuMeter.start();
                return vuMeter;
            })
                .catch(function (err) {
                console.error("vuMeterNode - Error on initialize", err);
                observer.error(err);
                return null;
            });
            return function () {
                vuMeterNode.then(function (vuMeter) { return vuMeter === null || vuMeter === void 0 ? void 0 : vuMeter.stop(); }).catch(function (err) { return console.error("vuMeterNode - Error on stop", err); });
            };
        });
    }

    var Emitter = (function () {
        function Emitter() {
            this.listeners = {};
        }
        Emitter.prototype.on = function (event, fn, context) {
            return this.addListener(event, fn, context, false);
        };
        Emitter.prototype.once = function (event, fn, context) {
            return this.addListener(event, fn, context, true);
        };
        Emitter.prototype.addListener = function (event, fn, context, once) {
            if (once === void 0) { once = false; }
            var listeners = this.listeners[event];
            if (!listeners) {
                listeners = [];
                this.listeners[event] = listeners;
            }
            var listener = {
                fn: fn,
                once: once,
                context: context || this,
                dispose: function () {
                    var index = listeners.indexOf(listener);
                    if (index > -1)
                        listeners.splice(index, 1);
                },
            };
            listeners.push(listener);
            return listener.dispose;
        };
        Emitter.prototype.emit = function (event) {
            var _a;
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                var _b, _c, listener, e_1_1;
                var e_1, _d;
                return __generator(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            _e.trys.push([0, 5, 6, 7]);
                            _b = __values(__spreadArray$1([], __read(((_a = this.listeners[event]) !== null && _a !== void 0 ? _a : [])), false)), _c = _b.next();
                            _e.label = 1;
                        case 1:
                            if (!!_c.done) return [3, 4];
                            listener = _c.value;
                            if (listener.once)
                                listener.dispose();
                            return [4, listener.fn.apply(listener.context, args)];
                        case 2:
                            _e.sent();
                            _e.label = 3;
                        case 3:
                            _c = _b.next();
                            return [3, 1];
                        case 4: return [3, 7];
                        case 5:
                            e_1_1 = _e.sent();
                            e_1 = { error: e_1_1 };
                            return [3, 7];
                        case 6:
                            try {
                                if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
                            }
                            finally { if (e_1) throw e_1.error; }
                            return [7];
                        case 7: return [2];
                    }
                });
            });
        };
        Emitter.prototype.dispose = function () {
            var e_2, _a;
            for (var event_1 in this.listeners) {
                try {
                    for (var _b = (e_2 = void 0, __values(__spreadArray$1([], __read(this.listeners[event_1]), false))), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var listener = _c.value;
                        listener.dispose();
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                delete this.listeners[event_1];
            }
        };
        return Emitter;
    }());

    var WebRtcMedia = (function (_super) {
        __extends(WebRtcMedia, _super);
        function WebRtcMedia() {
            var _this = _super.call(this) || this;
            _this._audioLevelSubscription = Subscription.EMPTY;
            return _this;
        }
        Object.defineProperty(WebRtcMedia.prototype, "audioLevel", {
            get: function () {
                var _this = this;
                if (!this._audioLevel) {
                    this._audioLevel = new Observable(function (observer) {
                        _this._audioLevelObserver = observer;
                        _this.startAudioLevel();
                        return function () {
                            _this._audioLevelSubscription.unsubscribe();
                            _this._audioLevel = undefined;
                        };
                    }).pipe(share());
                }
                return this._audioLevel;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRtcMedia.prototype, "audioLinkStatus", {
            get: function () {
                return this.audioMuted ? WebRtcMedia.LinkStatus.MUTE : WebRtcMedia.LinkStatus.UNMUTE;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRtcMedia.prototype, "videoLinkStatus", {
            get: function () {
                return this.videoMuted ? WebRtcMedia.LinkStatus.MUTE : WebRtcMedia.LinkStatus.UNMUTE;
            },
            enumerable: false,
            configurable: true
        });
        WebRtcMedia.prototype.dispose = function () {
            var _a;
            this._audioLevelSubscription.unsubscribe();
            (_a = this._audioLevelObserver) === null || _a === void 0 ? void 0 : _a.complete();
        };
        WebRtcMedia.prototype.startAudioLevel = function () {
            var _this = this;
            this._audioLevelSubscription.unsubscribe();
            if (this._stream && this._audioLevelObserver) {
                this._audioLevelSubscription = audioTrackLevelToObservable(this._stream).subscribe(function (value) { var _a; return (_a = _this._audioLevelObserver) === null || _a === void 0 ? void 0 : _a.next(value); });
            }
            else {
                this._audioLevelSubscription = Subscription.EMPTY;
            }
        };
        Object.defineProperty(WebRtcMedia.prototype, "audioMuted", {
            get: function () {
                if (this._stream) {
                    var tracks = this._stream.getAudioTracks();
                    if (tracks && tracks.length) {
                        return !tracks[0].enabled;
                    }
                }
                return false;
            },
            set: function (muted) {
                if (this._stream) {
                    this._stream.getAudioTracks().forEach(function (track) { return (track.enabled = !muted); });
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRtcMedia.prototype, "videoMuted", {
            get: function () {
                if (this._stream) {
                    var tracks = this._stream.getVideoTracks();
                    if (tracks && tracks.length) {
                        return !tracks[0].enabled;
                    }
                }
                return false;
            },
            set: function (muted) {
                if (this._stream) {
                    this._stream.getVideoTracks().forEach(function (track) { return (track.enabled = !muted); });
                }
            },
            enumerable: false,
            configurable: true
        });
        WebRtcMedia.prototype.grabVideoFrame = function (videoSink) {
            return __awaiter(this, void 0, void 0, function () {
                var width, height, canvas, context, image;
                return __generator(this, function (_a) {
                    if (videoSink && videoSink.width && videoSink.height) {
                        width = videoSink.width, height = videoSink.height, canvas = document.createElement("canvas"), context = canvas.getContext("2d");
                        canvas.width = width;
                        canvas.height = height;
                        context === null || context === void 0 ? void 0 : context.drawImage(videoSink.htmlElement, 0, 0, width, height);
                        image = context === null || context === void 0 ? void 0 : context.getImageData(0, 0, width, height);
                        if (image) {
                            return [2, image];
                        }
                    }
                    return [2, null];
                });
            });
        };
        WebRtcMedia.prototype.setStream = function (stream) {
            this._stream = stream;
            this.startAudioLevel();
        };
        return WebRtcMedia;
    }(Emitter));
    (function (WebRtcMedia) {
        (function (LinkStatus) {
            LinkStatus["MUTE"] = "MUTE";
            LinkStatus["UNMUTE"] = "UNMUTE";
        })(WebRtcMedia.LinkStatus || (WebRtcMedia.LinkStatus = {}));
    })(WebRtcMedia || (WebRtcMedia = {}));

    let logDisabled_ = true;
    let deprecationWarnings_ = true;
    function extractVersion(uastring, expr, pos) {
      const match = uastring.match(expr);
      return match && match.length >= pos && parseInt(match[pos], 10);
    }
    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';
    }
    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);
        }
      }
    }
    function deprecated(oldMethod, newMethod) {
      if (!deprecationWarnings_) {
        return;
      }
      console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
          ' instead.');
    }
    function detectBrowser(window) {
      const result = {browser: null, version: null};
      if (typeof window === 'undefined' || !window.navigator ||
          !window.navigator.userAgent) {
        result.browser = 'Not a browser.';
        return result;
      }
      const {navigator} = window;
      if (navigator.mozGetUserMedia) {
        result.browser = 'firefox';
        result.version = extractVersion(navigator.userAgent,
          /Firefox\/(\d+)\./, 1);
      } else if (navigator.webkitGetUserMedia ||
          (window.isSecureContext === false && window.webkitRTCPeerConnection)) {
        result.browser = 'chrome';
        result.version = extractVersion(navigator.userAgent,
          /Chrom(e|ium)\/(\d+)\./, 2);
      } else if (window.RTCPeerConnection &&
          navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
        result.browser = 'safari';
        result.version = extractVersion(navigator.userAgent,
          /AppleWebKit\/(\d+)\./, 1);
        result.supportsUnifiedPlan = window.RTCRtpTransceiver &&
            'currentDirection' in window.RTCRtpTransceiver.prototype;
      } else {
        result.browser = 'Not a supported browser.';
        return result;
      }
      return result;
    }
    function isObject$1(val) {
      return Object.prototype.toString.call(val) === '[object Object]';
    }
    function compactObject(data) {
      if (!isObject$1(data)) {
        return data;
      }
      return Object.keys(data).reduce(function(accumulator, key) {
        const isObj = isObject$1(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});
      }, {});
    }
    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);
          });
        }
      });
    }
    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;
    }

    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') {
          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) {
              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];
                  }
                  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);
      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))));
        };
      }
    }

    function shimGetDisplayMedia$1(window, getSourceId) {
      if (window.navigator.mediaDevices &&
        'getDisplayMedia' in window.navigator.mediaDevices) {
        return;
      }
      if (!(window.navigator.mediaDevices)) {
        return;
      }
      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);
            });
        };
    }

    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) => {
                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 {
        wrapPeerConnectionEvent(window, 'track', e => {
          if (!e.transceiver) {
            Object.defineProperty(e, 'transceiver',
              {value: {receiver: e.receiver}});
          }
          return e;
        });
      }
    }
    function shimGetSendersWithDtmf(window) {
      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
          };
        };
        if (!window.RTCPeerConnection.prototype.getSenders) {
          window.RTCPeerConnection.prototype.getSenders = function getSenders() {
            this._senders = this._senders || [];
            return this._senders.slice();
          };
          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) {
                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 (arguments.length > 0 && typeof selector === 'function') {
          return origGetStats.apply(this, arguments);
        }
        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;
        };
        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]);
        }
        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;
      }
      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 =>
            filterStats(result, sender.track, true));
        };
      }
      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;
      }
      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) {
      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;
      }
      if (window.RTCPeerConnection.prototype.addTrack &&
          browserDetails.version >= 65) {
        return shimAddTrackRemoveTrackWithNative(window);
      }
      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');
          }
        });
        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)) {
            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) {
            oldStream.addTrack(track);
            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);
        };
      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);
        };
      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');
          }
          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');
          }
          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) {
              this.removeStream(this._reverseStreams[stream.id]);
            } else {
              stream.removeTrack(sender.track);
            }
            this.dispatchEvent(new Event('negotiationneeded'));
          }
        };
    }
    function shimPeerConnection$1(window, browserDetails) {
      if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
        window.RTCPeerConnection = window.webkitRTCPeerConnection;
      }
      if (!window.RTCPeerConnection) {
        return;
      }
      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];
          });
      }
    }
    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
    });

    function shimGetUserMedia$1(window, browserDetails) {
      const navigator = window && window.navigator;
      const MediaStreamTrack = window && window.MediaStreamTrack;
      navigator.getUserMedia = function(constraints, onSuccess, onError) {
        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]);
          };
        }
      }
    }

    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';
            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);
        };
    }

    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;
      }
      if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
        window.RTCPeerConnection = window.mozRTCPeerConnection;
      }
      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];
          });
      }
      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) {
              try {
                stats.forEach(stat => {
                  stat.type = modernStatsTypes[stat.type] || stat.type;
                });
              } catch (e) {
                if (e.name !== 'TypeError') {
                  throw e;
                }
                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) {
      if (window.DataChannel && !window.RTCDataChannel) {
        window.RTCDataChannel = window.DataChannel;
      }
    }
    function shimAddTransceiver(window) {
      if (!(typeof window === 'object' && window.RTCPeerConnection)) {
        return;
      }
      const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
      if (origAddTransceiver) {
        window.RTCPeerConnection.prototype.addTransceiver =
          function addTransceiver() {
            this.setParametersPromises = [];
            let sendEncodings = arguments[1] && arguments[1].sendEncodings;
            if (sendEncodings === undefined) {
              sendEncodings = [];
            }
            sendEncodings = [...sendEncodings];
            const shouldPerformCheck = sendEncodings.length > 0;
            if (shouldPerformCheck) {
              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) {
              const {sender} = transceiver;
              const params = sender.getParameters();
              if (!('encodings' in params) ||
                  (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) {
      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) {
      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
    });

    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);
          }
          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) {
        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;
      }
      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;
      if ('generateCertificate' in OrigPeerConnection) {
        Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
          get() {
            return OrigPeerConnection.generateCertificate;
          }
        });
      }
    }
    function shimTrackEventTransceiver(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 shimCreateOfferLegacy(window) {
      const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
      window.RTCPeerConnection.prototype.createOffer =
        function createOffer(offerOptions) {
          if (offerOptions) {
            if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
              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') {
              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 sdpExports = {};
    var sdp$1 = {
      get exports(){ return sdpExports; },
      set exports(v){ sdpExports = v; },
    };

    (function (module) {
    	const SDPUtils = {};
    	SDPUtils.generateIdentifier = function() {
    	  return Math.random().toString(36).substring(2, 12);
    	};
    	SDPUtils.localCName = SDPUtils.generateIdentifier();
    	SDPUtils.splitLines = function(blob) {
    	  return blob.trim().split('\n').map(line => line.trim());
    	};
    	SDPUtils.splitSections = function(blob) {
    	  const parts = blob.split('\nm=');
    	  return parts.map((part, index) => (index > 0 ?
    	    'm=' + part : part).trim() + '\r\n');
    	};
    	SDPUtils.getDescription = function(blob) {
    	  const sections = SDPUtils.splitSections(blob);
    	  return sections && sections[0];
    	};
    	SDPUtils.getMediaSections = function(blob) {
    	  const sections = SDPUtils.splitSections(blob);
    	  sections.shift();
    	  return sections;
    	};
    	SDPUtils.matchPrefix = function(blob, prefix) {
    	  return SDPUtils.splitLines(blob).filter(line => line.indexOf(prefix) === 0);
    	};
    	SDPUtils.parseCandidate = function(line) {
    	  let parts;
    	  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],
    	    port: parseInt(parts[5], 10),
    	    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];
    	        candidate.usernameFragment = parts[i + 1];
    	        break;
    	      default:
    	        if (candidate[parts[i]] === undefined) {
    	          candidate[parts[i]] = parts[i + 1];
    	        }
    	        break;
    	    }
    	  }
    	  return candidate;
    	};
    	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(' ');
    	};
    	SDPUtils.parseIceOptions = function(line) {
    	  return line.substring(14).split(' ');
    	};
    	SDPUtils.parseRtpMap = function(line) {
    	  let parts = line.substring(9).split(' ');
    	  const parsed = {
    	    payloadType: parseInt(parts.shift(), 10),
    	  };
    	  parts = parts[0].split('/');
    	  parsed.name = parts[0];
    	  parsed.clockRate = parseInt(parts[1], 10);
    	  parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
    	  parsed.numChannels = parsed.channels;
    	  return parsed;
    	};
    	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';
    	};
    	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(' '),
    	  };
    	};
    	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';
    	};
    	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;
    	};
    	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;
    	};
    	SDPUtils.parseRtcpFb = function(line) {
    	  const parts = line.substring(line.indexOf(' ') + 1).split(' ');
    	  return {
    	    type: parts.shift(),
    	    parameter: parts.join(' '),
    	  };
    	};
    	SDPUtils.writeRtcpFb = function(codec) {
    	  let lines = '';
    	  let pt = codec.payloadType;
    	  if (codec.preferredPayloadType !== undefined) {
    	    pt = codec.preferredPayloadType;
    	  }
    	  if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
    	    codec.rtcpFeedback.forEach(fb => {
    	      lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
    	      (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
    	          '\r\n';
    	    });
    	  }
    	  return lines;
    	};
    	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;
    	};
    	SDPUtils.parseSsrcGroup = function(line) {
    	  const parts = line.substring(13).split(' ');
    	  return {
    	    semantics: parts.shift(),
    	    ssrcs: parts.map(ssrc => parseInt(ssrc, 10)),
    	  };
    	};
    	SDPUtils.getMid = function(mediaSection) {
    	  const mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
    	  if (mid) {
    	    return mid.substring(6);
    	  }
    	};
    	SDPUtils.parseFingerprint = function(line) {
    	  const parts = line.substring(14).split(' ');
    	  return {
    	    algorithm: parts[0].toLowerCase(),
    	    value: parts[1].toUpperCase(),
    	  };
    	};
    	SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
    	  const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
    	    'a=fingerprint:');
    	  return {
    	    role: 'auto',
    	    fingerprints: lines.map(SDPUtils.parseFingerprint),
    	  };
    	};
    	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;
    	};
    	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';
    	};
    	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
    	      : '');
    	};
    	SDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {
    	  const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
    	    'a=crypto:');
    	  return lines.map(SDPUtils.parseCryptoLine);
    	};
    	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),
    	  };
    	};
    	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;
    	};
    	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++) {
    	    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 + ' ');
    	      codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
    	      codec.rtcpFeedback = SDPUtils.matchPrefix(
    	        mediaSection, 'a=rtcp-fb:' + pt + ' ')
    	        .map(SDPUtils.parseRtcpFb);
    	      description.codecs.push(codec);
    	      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);
    	      }
    	    });
    	  });
    	  return description;
    	};
    	SDPUtils.writeRtpDescription = function(kind, caps) {
    	  let sdp = '';
    	  sdp += 'm=' + kind + ' ';
    	  sdp += caps.codecs.length > 0 ? '9' : '0';
    	  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';
    	  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);
    	    });
    	  }
    	  return sdp;
    	};
    	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;
    	  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,
    	    });
    	  }
    	  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) {
    	      bandwidth = parseInt(bandwidth[0].substring(5), 10) * 1000 * 0.95
    	          - (50 * 40 * 8);
    	    } else {
    	      bandwidth = undefined;
    	    }
    	    encodingParameters.forEach(params => {
    	      params.maxBitrate = bandwidth;
    	    });
    	  }
    	  return encodingParameters;
    	};
    	SDPUtils.parseRtcpParameters = function(mediaSection) {
    	  const rtcpParameters = {};
    	  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;
    	  }
    	  const rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
    	  rtcpParameters.reducedSize = rsize.length > 0;
    	  rtcpParameters.compound = rsize.length === 0;
    	  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;
    	};
    	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]};
    	  }
    	};
    	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,
    	    };
    	  }
    	};
    	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('');
    	};
    	SDPUtils.generateSessionId = function() {
    	  return Math.random().toString().substr(2, 22);
    	};
    	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';
    	  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';
    	};
    	SDPUtils.getDirection = function(mediaSection, sessionpart) {
    	  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);
    	    }
    	  }
    	  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],
    	  };
    	};
    	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;
    	    }
    	  }
    	  return true;
    	};
    	{
    	  module.exports = SDPUtils;
    	}
    } (sdp$1));
    var SDPUtils = sdpExports;

    var sdp = /*#__PURE__*/_mergeNamespaces({
        __proto__: null,
        default: SDPUtils
    }, [sdpExports]);

    function shimRTCIceCandidate(window) {
      if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in
          window.RTCIceCandidate.prototype)) {
        return;
      }
      const NativeRTCIceCandidate = window.RTCIceCandidate;
      window.RTCIceCandidate = function RTCIceCandidate(args) {
        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) {
          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]});
            }
          }
          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;
      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;
      }
      wrapPeerConnectionEvent(window, 'icecandidate', e => {
        if (e.candidate) {
          const parsedCandidate = SDPUtils.parseCandidate(e.candidate.candidate);
          if (parsedCandidate.type === 'relay') {
            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) {
        const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
        if (match === null || match.length < 2) {
          return -1;
        }
        const version = parseInt(match[1], 10);
        return version !== version ? -1 : version;
      };
      const getCanSendMaxMessageSize = function(remoteIsFirefox) {
        let canSendMaxMessageSize = 65536;
        if (browserDetails.browser === 'firefox') {
          if (browserDetails.version < 57) {
            if (remoteIsFirefox === -1) {
              canSendMaxMessageSize = 16384;
            } else {
              canSendMaxMessageSize = 2147483637;
            }
          } else if (browserDetails.version < 60) {
            canSendMaxMessageSize =
              browserDetails.version === 57 ? 65535 : 65536;
          } else {
            canSendMaxMessageSize = 2147483637;
          }
        }
        return canSendMaxMessageSize;
      };
      const getMaxMessageSize = function(description, remoteIsFirefox) {
        let maxMessageSize = 65536;
        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) {
          maxMessageSize = 2147483637;
        }
        return maxMessageSize;
      };
      const origSetRemoteDescription =
          window.RTCPeerConnection.prototype.setRemoteDescription;
      window.RTCPeerConnection.prototype.setRemoteDescription =
        function setRemoteDescription() {
          this._sctp = null;
          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])) {
            const isFirefox = getRemoteFirefoxVersion(arguments[0]);
            const canSendMMS = getCanSendMaxMessageSize(isFirefox);
            const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
            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);
            }
            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;
      }
      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;
      });
    }
    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) {
      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');
          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) {
      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();
          }
          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);
        };
    }
    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);
          }
          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
    });

    function adapterFactory({window} = {}, options = {
      shimChrome: true,
      shimFirefox: true,
      shimSafari: true,
    }) {
      const logging = log;
      const browserDetails = detectBrowser(window);
      const adapter = {
        browserDetails,
        commonShim,
        extractVersion: extractVersion,
        disableLog: disableLog,
        disableWarnings: disableWarnings,
        sdp,
      };
      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.');
          adapter.browserShim = chromeShim;
          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.');
          adapter.browserShim = firefoxShim;
          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.');
          adapter.browserShim = safariShim;
          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;
    }

    const adapter =
      adapterFactory({window: typeof window === 'undefined' ? undefined : window});

    var PlatformData = (function () {
        function PlatformData() {
            this.mobile = false;
            this.supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
            if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(adapter.browserDetails.browser) ||
                /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(adapter.browserDetails.browser.substr(0, 4))) {
                this.mobile = true;
            }
        }
        PlatformData.prototype.isConstraintsSupported = function (constraints) {
            return !!this.supportedConstraints[constraints];
        };
        return PlatformData;
    }());
    var Platform = new PlatformData();

    var LayoutScale;
    (function (LayoutScale) {
        LayoutScale["Contain"] = "Contain";
        LayoutScale["Cover"] = "Cover";
        LayoutScale["Stretch"] = "Stretch";
    })(LayoutScale || (LayoutScale = {}));
    var LayoutMode;
    (function (LayoutMode) {
        LayoutMode["FloatLocal"] = "FloatLocal";
    })(LayoutMode || (LayoutMode = {}));
    var LayoutDirection;
    (function (LayoutDirection) {
        LayoutDirection["Horizontal"] = "Horizontal";
        LayoutDirection["Vertical"] = "Vertical";
    })(LayoutDirection || (LayoutDirection = {}));
    var LayoutAlignment;
    (function (LayoutAlignment) {
        LayoutAlignment["TopLeft"] = "TopLeft";
        LayoutAlignment["Top"] = "Top";
        LayoutAlignment["TopRight"] = "TopRight";
        LayoutAlignment["Left"] = "Left";
        LayoutAlignment["Center"] = "Center";
        LayoutAlignment["Right"] = "Right";
        LayoutAlignment["BottomLeft"] = "BottomLeft";
        LayoutAlignment["Bottom"] = "Bottom";
        LayoutAlignment["BottomRight"] = "BottomRight";
    })(LayoutAlignment || (LayoutAlignment = {}));
    var LayoutOrigin;
    (function (LayoutOrigin) {
        LayoutOrigin["TopLeft"] = "TopLeft";
        LayoutOrigin["TopRight"] = "TopRight";
        LayoutOrigin["BottomRight"] = "BottomRight";
        LayoutOrigin["BottomLeft"] = "BottomLeft";
    })(LayoutOrigin || (LayoutOrigin = {}));

    function uuidv4() {
        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { return (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16); });
    }
    function isDOMAttrModifiedSupported() {
        var p = document.createElement("p");
        var flag = false;
        if (p.addEventListener) {
            p.addEventListener("DOMAttrModified", function () {
                return (flag = true);
            }, false);
        }
        else if (p.attachEvent) {
            p.attachEvent("onDOMAttrModified", function () {
                return (flag = true);
            });
        }
        else {
            return false;
        }
        p.setAttribute("id", "target");
        return flag;
    }
    function observe(element, event) {
        return new Observable(function (subscriber) {
            if (element.addEventListener) {
                element.addEventListener(event, subscriber.next, false);
            }
            else if (element.attachEvent) {
                element.attachEvent("on" + event, subscriber.next);
            }
            else {
                element["on" + event] = subscriber.next;
            }
            return function () {
                if (element.removeEventListener) {
                    element.removeEventListener(event, subscriber.next, false);
                }
                else {
                    element.detachEvent("on" + event, subscriber.next);
                }
            };
        });
    }
    function observeAttr(element) {
        return new Observable(function (subscriber) {
            var mutationObserver;
            var observerSubscription = Subscription.EMPTY;
            if (window.MutationObserver) {
                mutationObserver = new MutationObserver(function (mutations, observer) {
                    for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {
                        var mutation = mutations_1[_i];
                        subscriber.next(mutation.attributeName);
                    }
                });
                mutationObserver.observe(element, {
                    subtree: false,
                    attributes: true,
                });
            }
            else if (isDOMAttrModifiedSupported()) {
                observerSubscription = observe(element, "DOMAttrModified")
                    .pipe(map(function (e) { return e.attrName; }))
                    .subscribe(subscriber);
            }
            else if ("onpropertychange" in document.body) {
                observerSubscription = observe(element, "propertychange")
                    .pipe(map(function () { return (window === null || window === void 0 ? void 0 : window.event).propertyName; }))
                    .subscribe(subscriber);
            }
            return function () {
                observerSubscription.unsubscribe();
                if (mutationObserver) {
                    mutationObserver.disconnect();
                }
            };
        });
    }

    var MediaSink = (function (_super) {
        __extends(MediaSink, _super);
        function MediaSink(local) {
            var _this = _super.call(this) || this;
            _this._videoStarted = false;
            _this._audio = new AudioSink(_this);
            _this._audio.muted = local;
            _this._video = new VideoSink(_this);
            _this._video.muted = local;
            _this._container = document.createElement("div");
            _this._container.style.position = "relative";
            _this._container.style.overflow = "hidden";
            _this._container.className = "tl-video tl-video-".concat(local ? "local" : "remote");
            _this.on("videoStart", function (videoSink) {
                if (!_this._container.contains(videoSink.htmlElement)) {
                    _this._container.append(videoSink.htmlElement);
                }
                _this._videoStarted = true;
            });
            _this.on("videoStop", function (videoSink) {
                if (_this._videoStarted) {
                    _this._videoStarted = false;
                    if (_this._container.contains(videoSink.htmlElement)) {
                        _this._container.removeChild(videoSink.htmlElement);
                    }
                }
            });
            return _this;
        }
        Object.defineProperty(MediaSink.prototype, "view", {
            get: function () {
                return this._container;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MediaSink.prototype, "audioSink", {
            get: function () {
                return this._audio;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MediaSink.prototype, "videoSink", {
            get: function () {
                return this._video;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MediaSink.prototype, "videoStarted", {
            get: function () {
                return this._videoStarted;
            },
            enumerable: false,
            configurable: true
        });
        MediaSink.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this._audio.dispose();
            this._video.dispose();
        };
        MediaSink.prototype.setAudioOutput = function (audioOutput) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(audioOutput && audioOutput.deviceId)) return [3, 3];
                            return [4, this._audio.setSinkId(audioOutput.deviceId)];
                        case 1:
                            _a.sent();
                            return [4, this._video.setSinkId(audioOutput.deviceId)];
                        case 2:
                            _a.sent();
                            return [3, 6];
                        case 3: return [4, this._audio.setSinkId()];
                        case 4:
                            _a.sent();
                            return [4, this._video.setSinkId()];
                        case 5:
                            _a.sent();
                            _a.label = 6;
                        case 6: return [2];
                    }
                });
            });
        };
        MediaSink.prototype.replaceTrack = function (stream) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!stream) return [3, 2];
                            return [4, Promise.all([this.replaceAudioTrack(stream), this.replaceVideoTrack(stream)])];
                        case 1:
                            _a.sent();
                            return [3, 4];
                        case 2: return [4, this.stopTrack()];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [2];
                    }
                });
            });
        };
        MediaSink.prototype.replaceAudioTrack = function (stream) {
            return __awaiter(this, void 0, void 0, function () {
                var audioTracks, previousAudioIsStarted, playRequest;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            audioTracks = stream.getAudioTracks();
                            if (!(audioTracks && audioTracks.length)) return [3, 6];
                            if (!!(this._audio.stream && this._audio.stream === stream)) return [3, 5];
                            return [4, this.stopAudio(false)];
                        case 1:
                            previousAudioIsStarted = _a.sent();
                            return [4, this._audio.setStream(stream)];
                        case 2:
                            _a.sent();
                            if (!!isGestureRequiredForPlay()) return [3, 4];
                            playRequest = this._audio.play();
                            if (!playRequest) return [3, 4];
                            return [4, playRequest];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4:
                            if (!previousAudioIsStarted) {
                                this.emit("audioStart", this._audio);
                            }
                            _a.label = 5;
                        case 5: return [3, 8];
                        case 6: return [4, this.stopAudio(true)];
                        case 7:
                            _a.sent();
                            _a.label = 8;
                        case 8: return [2];
                    }
                });
            });
        };
        MediaSink.prototype.replaceVideoTrack = function (stream) {
            return __awaiter(this, void 0, void 0, function () {
                var videoTracks, previousVideoIsStarted, playRequest;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            videoTracks = stream.getVideoTracks();
                            if (!(videoTracks && videoTracks.length)) return [3, 6];
                            if (!!(this._video.stream && this._video.stream === stream)) return [3, 5];
                            return [4, this.stopVideo(false)];
                        case 1:
                            previousVideoIsStarted = _a.sent();
                            return [4, this._video.setStream(stream)];
                        case 2:
                            _a.sent();
                            if (!!isGestureRequiredForPlay()) return [3, 4];
                            playRequest = this._video.play();
                            if (!playRequest) return [3, 4];
                            return [4, playRequest];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4:
                            if (!previousVideoIsStarted) {
                                this.emit("videoStart", this._video);
                            }
                            _a.label = 5;
                        case 5: return [3, 8];
                        case 6: return [4, this.stopVideo(true)];
                        case 7:
                            _a.sent();
                            _a.label = 8;
                        case 8: return [2];
                    }
                });
            });
        };
        MediaSink.prototype.stopTrack = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, Promise.all([this.stopAudio(true), this.stopVideo(true)])];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        MediaSink.prototype.stopAudio = function (emit) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this._audio && this._audio.stream)) return [3, 5];
                            return [4, this._audio.stop()];
                        case 1:
                            _a.sent();
                            return [4, this._audio.setStream()];
                        case 2:
                            _a.sent();
                            if (!emit) return [3, 4];
                            return [4, this.emit("audioStop", this._audio)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [2, true];
                        case 5: return [2, false];
                    }
                });
            });
        };
        MediaSink.prototype.stopVideo = function (emit) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this._video && this._video.stream)) return [3, 5];
                            return [4, this._video.stop()];
                        case 1:
                            _a.sent();
                            return [4, this._video.setStream()];
                        case 2:
                            _a.sent();
                            if (!emit) return [3, 4];
                            return [4, this.emit("videoStop", this._video)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [2, true];
                        case 5: return [2, false];
                    }
                });
            });
        };
        return MediaSink;
    }(Emitter));
    var LocalMediaSink = (function (_super) {
        __extends(LocalMediaSink, _super);
        function LocalMediaSink(localMedia) {
            var _this = this;
            var _a, _b, _c, _d;
            _this = _super.call(this, true) || this;
            _this._localMedia = localMedia;
            (_a = _this._localMedia) === null || _a === void 0 ? void 0 : _a.on("start", function () {
                return _this.replaceTrack(_this._localMedia.stream);
            });
            (_b = _this._localMedia) === null || _b === void 0 ? void 0 : _b.on("stop", function () {
                return _this.stopTrack();
            });
            (_c = _this._localMedia) === null || _c === void 0 ? void 0 : _c.on("replaceTrack", function (previousTracks, currentTracks, constraints) {
                return _this.replaceTrack(_this._localMedia.stream);
            });
            (_d = _this._localMedia) === null || _d === void 0 ? void 0 : _d.on("changeAudioOutput", function (audioOutput) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, this.setAudioOutput(audioOutput)];
                });
            }); });
            return _this;
        }
        Object.defineProperty(LocalMediaSink.prototype, "localMedia", {
            get: function () {
                return this._localMedia;
            },
            enumerable: false,
            configurable: true
        });
        LocalMediaSink.prototype.replaceTrack = function (stream) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, _super.prototype.replaceTrack.call(this, stream)];
                        case 1:
                            _b.sent();
                            this.setViewMirror();
                            (_a = this._video) === null || _a === void 0 ? void 0 : _a.applyScale();
                            return [2];
                    }
                });
            });
        };
        LocalMediaSink.prototype.setViewMirror = function () {
            var _a, _b, _c, _d;
            if (((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.constraints) && ((_b = this._localMedia) === null || _b === void 0 ? void 0 : _b.constraints.video)) {
                switch (typeof ((_c = this._localMedia) === null || _c === void 0 ? void 0 : _c.constraints.video)) {
                    case "boolean":
                        if (this._video) {
                            this._video.viewMirror = true;
                        }
                        break;
                    case "object":
                        var videoConstraints = (_d = this._localMedia) === null || _d === void 0 ? void 0 : _d.constraints.video;
                        var facingMode = videoConstraints.facingMode;
                        if (facingMode && facingMode.exact) {
                            facingMode = facingMode.exact;
                        }
                        else if (facingMode && facingMode.ideal) {
                            facingMode = facingMode.ideal;
                        }
                        if (this._video) {
                            this._video.viewMirror = facingMode == "user";
                        }
                        break;
                }
            }
        };
        return LocalMediaSink;
    }(MediaSink));
    var RemoteMediaSink = (function (_super) {
        __extends(RemoteMediaSink, _super);
        function RemoteMediaSink(remoteMedia) {
            var _this = this;
            var _a, _b, _c;
            _this = _super.call(this, false) || this;
            _this._remoteMedia = remoteMedia;
            (_a = _this._remoteMedia) === null || _a === void 0 ? void 0 : _a.on("start", function () {
                return _this.replaceTrack(_this._remoteMedia.stream);
            });
            (_b = _this._remoteMedia) === null || _b === void 0 ? void 0 : _b.on("stop", function () {
                return _this.stopTrack();
            });
            (_c = _this._remoteMedia) === null || _c === void 0 ? void 0 : _c.on("changeAudioOutput", function (audioOutput) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, this.setAudioOutput(audioOutput)];
                });
            }); });
            return _this;
        }
        Object.defineProperty(RemoteMediaSink.prototype, "remoteMedia", {
            get: function () {
                return this._remoteMedia;
            },
            enumerable: false,
            configurable: true
        });
        RemoteMediaSink.prototype.replaceTrack = function (stream) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, _super.prototype.replaceTrack.call(this, stream)];
                        case 1:
                            _b.sent();
                            if (this._video) {
                                this._video.viewMirror = false;
                            }
                            (_a = this._video) === null || _a === void 0 ? void 0 : _a.applyScale();
                            return [2];
                    }
                });
            });
        };
        RemoteMediaSink.prototype.addTrack = function (track) {
            return __awaiter(this, void 0, void 0, function () {
                var stream, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            stream = this._remoteMedia.stream;
                            if (!stream) return [3, 13];
                            stream.addTrack(track);
                            _a = track.kind;
                            switch (_a) {
                                case "audio": return [3, 1];
                                case "video": return [3, 7];
                            }
                            return [3, 13];
                        case 1:
                            if (!!(this._audio.stream && this._audio.stream === stream)) return [3, 6];
                            return [4, this._audio.stop()];
                        case 2:
                            _b.sent();
                            return [4, this._audio.setStream(stream)];
                        case 3:
                            _b.sent();
                            if (!!isGestureRequiredForPlay()) return [3, 5];
                            return [4, this._audio.play()];
                        case 4:
                            _b.sent();
                            _b.label = 5;
                        case 5:
                            this.emit("audioStart", this._audio);
                            _b.label = 6;
                        case 6: return [3, 13];
                        case 7:
                            if (!!(this._video.stream && this._video.stream === stream)) return [3, 12];
                            return [4, this._video.stop()];
                        case 8:
                            _b.sent();
                            return [4, this._video.setStream(stream)];
                        case 9:
                            _b.sent();
                            if (!!isGestureRequiredForPlay()) return [3, 11];
                            return [4, this._video.play()];
                        case 10:
                            _b.sent();
                            _b.label = 11;
                        case 11:
                            this.emit("videoStart", this._video);
                            _b.label = 12;
                        case 12: return [3, 13];
                        case 13: return [2];
                    }
                });
            });
        };
        RemoteMediaSink.prototype.removeTrack = function (track) {
            return __awaiter(this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _a = track.kind;
                            switch (_a) {
                                case "audio": return [3, 1];
                                case "video": return [3, 7];
                            }
                            return [3, 13];
                        case 1:
                            if (!(this._audio && this._audio.stream)) return [3, 6];
                            _b.label = 2;
                        case 2:
                            _b.trys.push([2, 4, , 5]);
                            return [4, this._audio.stop()];
                        case 3:
                            _b.sent();
                            return [3, 5];
                        case 4:
                            _b.sent();
                            return [3, 5];
                        case 5:
                            this._audio.setStream();
                            this.emit("audioStop", this._audio);
                            _b.label = 6;
                        case 6: return [3, 13];
                        case 7:
                            if (!(this._video && this._video.stream)) return [3, 12];
                            _b.label = 8;
                        case 8:
                            _b.trys.push([8, 10, , 11]);
                            return [4, this._video.stop()];
                        case 9:
                            _b.sent();
                            return [3, 11];
                        case 10:
                            _b.sent();
                            return [3, 11];
                        case 11:
                            this._video.setStream();
                            this.emit("videoStop", this._video);
                            _b.label = 12;
                        case 12: return [3, 13];
                        case 13: return [2];
                    }
                });
            });
        };
        return RemoteMediaSink;
    }(MediaSink));
    var HTMLMediaElementSink = (function (_super) {
        __extends(HTMLMediaElementSink, _super);
        function HTMLMediaElementSink(_sink, element) {
            var _this = _super.call(this) || this;
            _this._sink = _sink;
            _this._element = element;
            return _this;
        }
        HTMLMediaElementSink.prototype.dispose = function () {
            this.stop();
        };
        HTMLMediaElementSink.prototype.play = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, this.htmlElement.play()];
                });
            });
        };
        HTMLMediaElementSink.prototype.stop = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, this.htmlElement.pause()];
                });
            });
        };
        HTMLMediaElementSink.prototype.setSinkId = function (deviceId) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.htmlElement.setSinkId(deviceId || "")];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        HTMLMediaElementSink.prototype.setStream = function (stream) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    this._stream = stream;
                    this.htmlElement.srcObject = stream !== null && stream !== void 0 ? stream : null;
                    return [2];
                });
            });
        };
        Object.defineProperty(HTMLMediaElementSink.prototype, "stream", {
            get: function () {
                return this._stream;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HTMLMediaElementSink.prototype, "htmlElement", {
            get: function () {
                return this._element;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HTMLMediaElementSink.prototype, "volume", {
            get: function () {
                return this._element.volume;
            },
            set: function (volume) {
                this._element.volume = volume;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HTMLMediaElementSink.prototype, "muted", {
            get: function () {
                return this._element.muted;
            },
            set: function (muted) {
                this._element.muted = muted;
            },
            enumerable: false,
            configurable: true
        });
        return HTMLMediaElementSink;
    }(Emitter));
    var VideoSink = (function (_super) {
        __extends(VideoSink, _super);
        function VideoSink(mediaSink) {
            var _this = _super.call(this, mediaSink, document.createElement("video")) || this;
            _this._viewMirror = false;
            _this._viewScale = LayoutScale.Contain;
            _this._elementLoadedDataSubscription = Subscription.EMPTY;
            _this._viewAttributeChangeSubscription = Subscription.EMPTY;
            _this.htmlElement.style.position = "absolute";
            _this.htmlElement.setAttribute("autoplay", "autoplay");
            _this.htmlElement.setAttribute("playsinline", "playsinline");
            _this.muted = true;
            _this.applyScale();
            return _this;
        }
        Object.defineProperty(VideoSink.prototype, "width", {
            get: function () {
                return this.htmlElement.videoWidth;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(VideoSink.prototype, "height", {
            get: function () {
                return this.htmlElement.videoHeight;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(VideoSink.prototype, "viewMirror", {
            get: function () {
                return this._viewMirror;
            },
            set: function (viewMirror) {
                this._sink.view.style.transform = viewMirror ? "scale(-1,1)" : "";
                this._viewMirror = viewMirror;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(VideoSink.prototype, "scale", {
            get: function () {
                return this._viewScale;
            },
            set: function (scale) {
                this._viewScale = scale;
                this.applyScale();
            },
            enumerable: false,
            configurable: true
        });
        VideoSink.prototype.applyScale = function () {
            var _this = this;
            if (this.htmlElement.style.hasOwnProperty("objectFit")) {
                this.htmlElement.style.width = "100%";
                this.htmlElement.style.height = "100%";
                switch (this._viewScale) {
                    case LayoutScale.Contain: {
                        this.htmlElement.style.objectFit = "contain";
                        break;
                    }
                    case LayoutScale.Cover: {
                        this.htmlElement.style.objectFit = "cover";
                        break;
                    }
                    case LayoutScale.Stretch: {
                        this.htmlElement.style.objectFit = "fill";
                        break;
                    }
                }
            }
            else {
                switch (this._viewScale) {
                    case LayoutScale.Contain: {
                        this.htmlElement.style.width = "100%";
                        this.htmlElement.style.height = "100%";
                        break;
                    }
                    case LayoutScale.Cover: {
                        this._sink.view.style.display = "inline-block";
                        this.htmlElement.style.left = "-100%";
                        this.htmlElement.style.right = "-100%";
                        this.htmlElement.style.top = "-100%";
                        this.htmlElement.style.bottom = "-100%";
                        this.htmlElement.style.margin = "auto";
                        this.htmlElement.style.maxWidth = "none";
                        this.htmlElement.style.maxHeight = "none";
                        var rescale_1 = function () {
                            var containerWidth = _this._sink.view.clientWidth, containerHeight = _this._sink.view.clientHeight, videoWidth = _this.htmlElement.clientWidth, videoHeight = _this.htmlElement.clientHeight;
                            if (!videoHeight || videoWidth / videoHeight > containerWidth / containerHeight) {
                                _this.htmlElement.style.width = "auto";
                                _this.htmlElement.style.height = "100%";
                                _this.htmlElement.style.maxWidth = "none";
                            }
                            else {
                                _this.htmlElement.style.width = "100%";
                                _this.htmlElement.style.height = "auto";
                                _this.htmlElement.style.maxWidth = "none";
                            }
                        };
                        this._elementLoadedDataSubscription = observe(this.htmlElement, "loadeddata").subscribe(function () { return rescale_1(); });
                        this._viewAttributeChangeSubscription = observeAttr(this._sink.view).subscribe(function (attrName) {
                            if (attrName == "width" || attrName == "height" || attrName == "style") {
                                rescale_1();
                            }
                        });
                        rescale_1();
                        break;
                    }
                    case LayoutScale.Stretch: {
                        this.htmlElement.style.transformOrigin = "0px 0px";
                        var lastContainerWidth_1 = 0, lastContainerHeight_1 = 0, lastVideoWidth_1 = 0, lastVideoHeight_1 = 0;
                        var rescale_2 = function () {
                            var containerWidth = _this._sink.view.clientWidth, containerHeight = _this._sink.view.clientHeight, videoWidth = _this.htmlElement.clientWidth, videoHeight = _this.htmlElement.clientHeight;
                            if (containerWidth != lastContainerWidth_1 || containerHeight != lastContainerHeight_1 || videoWidth != lastVideoWidth_1 || videoHeight != lastVideoHeight_1) {
                                if (videoWidth && videoHeight) {
                                    _this.htmlElement.style.transform = "scale(" + containerWidth / videoWidth + ", " + containerHeight / videoHeight + ")";
                                    lastContainerWidth_1 = containerWidth;
                                    lastContainerHeight_1 = containerHeight;
                                    lastVideoWidth_1 = videoWidth;
                                    lastVideoHeight_1 = videoHeight;
                                }
                            }
                        };
                        this._elementLoadedDataSubscription = observe(this.htmlElement, "loadeddata").subscribe(function () { return rescale_2(); });
                        this._viewAttributeChangeSubscription = observeAttr(this._sink.view).subscribe(function (attrName) {
                            if (attrName == "width" || attrName == "height" || attrName == "style") {
                                rescale_2();
                            }
                        });
                        rescale_2();
                        break;
                    }
                }
            }
        };
        return VideoSink;
    }(HTMLMediaElementSink));
    var AudioSink = (function (_super) {
        __extends(AudioSink, _super);
        function AudioSink(sink) {
            var _this = _super.call(this, sink, document.createElement("audio")) || this;
            _this.htmlElement.setAttribute("autoplay", "autoplay");
            return _this;
        }
        return AudioSink;
    }(HTMLMediaElementSink));

    var LocalMedia = (function (_super) {
        __extends(LocalMedia, _super);
        function LocalMedia(constraints) {
            var _this = _super.call(this) || this;
            _this._sink = new LocalMediaSink(_this);
            _this.changeConstraints(constraints !== null && constraints !== void 0 ? constraints : {});
            _this.on("replaceTrack", function () { return _this.startAudioLevel(); });
            return _this;
        }
        Object.defineProperty(LocalMedia.prototype, "sink", {
            get: function () {
                return this._sink;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "audioInput", {
            get: function () {
                return this._audioInput;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "videoInput", {
            get: function () {
                return this._videoInput;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "audioOutput", {
            get: function () {
                return this._audioOutput;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "stream", {
            get: function () {
                return this._stream;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "constraints", {
            get: function () {
                return this._constraints;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LocalMedia.prototype, "started", {
            get: function () {
                return !!this._stream;
            },
            enumerable: false,
            configurable: true
        });
        LocalMedia.prototype.dispose = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.stop()];
                        case 1:
                            _a.sent();
                            _super.prototype.dispose.call(this);
                            return [2];
                    }
                });
            });
        };
        LocalMedia.prototype.start = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _a, e_1;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!!this.started) return [3, 4];
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 3, , 4]);
                            _a = this.setStream;
                            return [4, navigator.mediaDevices.getUserMedia(this._constraints)];
                        case 2:
                            _a.apply(this, [_b.sent()]);
                            this.emit("start");
                            return [3, 4];
                        case 3:
                            e_1 = _b.sent();
                            throw new TLinkError("Error on start local media", e_1);
                        case 4: return [2];
                    }
                });
            });
        };
        LocalMedia.prototype.stop = function () {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4, this._sink.stopTrack()];
                        case 1:
                            _c.sent();
                            (_a = this._stream) === null || _a === void 0 ? void 0 : _a.getTracks().forEach(function (track) { return track.stop(); });
                            (_b = this._audioLevelObserver) === null || _b === void 0 ? void 0 : _b.complete();
                            this._stream = undefined;
                            this.emit("stop");
                            return [2];
                    }
                });
            });
        };
        LocalMedia.prototype.changeAudioVideoInput = function (audioInput, videoInput) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, this.changeConstraints(this.buildConstraints(audioInput, videoInput))];
                });
            });
        };
        LocalMedia.prototype.buildConstraints = function (audioInput, videoInput) {
            var _this = this;
            var constraints = {};
            [
                { inputDevice: audioInput, deviceType: "audio" },
                { inputDevice: videoInput, deviceType: "video" },
            ].forEach(function (_a) {
                var _b;
                var inputDevice = _a.inputDevice, deviceType = _a.deviceType;
                switch (typeof inputDevice) {
                    case "boolean":
                        constraints[deviceType] = inputDevice;
                        break;
                    case "undefined":
                        constraints[deviceType] = false;
                        break;
                    case "object":
                        if (inputDevice === null || inputDevice === undefined) {
                            constraints[deviceType] = true;
                        }
                        else if (inputDevice.kind === "".concat(deviceType, "input")) {
                            if (((_b = _this._constraints) === null || _b === void 0 ? void 0 : _b[deviceType]) && typeof _this.constraints[deviceType] === "object") {
                                constraints[deviceType] = __assign(__assign({}, _this._constraints[deviceType]), { deviceId: { exact: inputDevice.deviceId } });
                            }
                            if (!constraints[deviceType]) {
                                constraints[deviceType] = { deviceId: { exact: inputDevice.deviceId } };
                            }
                        }
                        else {
                            throw new TLinkError("error on LocalMedia.buildConstraints, ".concat(deviceType, "Input.kind is ").concat(inputDevice.kind));
                        }
                        break;
                    default:
                        throw new TLinkError("error on LocalMedia.buildConstraints, ".concat(deviceType, "Input is invalid: ").concat(JSON.stringify(inputDevice)));
                }
            });
            if (constraints.video) {
                if (!(typeof constraints.video === "object")) {
                    constraints.video = {};
                }
                var videoConstraints = constraints.video;
                if (!videoConstraints.facingMode) {
                    videoConstraints.facingMode = "user";
                }
                if (videoConstraints.deviceId && this._videoInput != null) {
                    var videoSourceInputName = this._videoInput.label;
                    if (videoSourceInputName) {
                        if (videoSourceInputName.startsWith("back") || videoSourceInputName.endsWith("back") || videoSourceInputName.startsWith("rear") || videoSourceInputName.endsWith("rear") || videoSourceInputName.startsWith("environment") || videoSourceInputName.endsWith("environment")) {
                            videoConstraints.facingMode = "environment";
                        }
                    }
                }
            }
            return constraints;
        };
        LocalMedia.prototype.changeAudioOutput = function (audioOutput) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (audioOutput) {
                                if (audioOutput.kind === "audiooutput") {
                                    this._audioOutput = audioOutput;
                                }
                                else {
                                    throw new TLinkError("error on LocalMedia.changeAudioOutput, audioOutput.kind is ".concat(audioOutput.kind));
                                }
                            }
                            else {
                                this._audioOutput = undefined;
                            }
                            return [4, this.emit("changeAudioOutput", audioOutput)];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        LocalMedia.prototype.changeConstraints = function (constraints) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function () {
                var constraint, constraint, previousTracks, currentTracks, stream;
                var _this = this;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (constraints && !!constraints.audio && typeof constraints.audio === "object") {
                                for (constraint in constraints.audio) {
                                    if (!Platform.isConstraintsSupported(constraint)) {
                                        delete constraints[constraint];
                                    }
                                }
                            }
                            if (constraints && !!constraints.video && typeof constraints.video === "object") {
                                for (constraint in constraints.video) {
                                    if (!Platform.isConstraintsSupported(constraint)) {
                                        delete constraints[constraint];
                                    }
                                }
                            }
                            previousTracks = __spreadArray$1([], __read(((_b = (_a = this._stream) === null || _a === void 0 ? void 0 : _a.getTracks()) !== null && _b !== void 0 ? _b : [])), false);
                            currentTracks = [];
                            this._constraints = constraints;
                            if (!this.started) return [3, 5];
                            if (!(this._constraints.audio || this._constraints.video)) return [3, 2];
                            return [4, navigator.mediaDevices.getUserMedia(this._constraints)];
                        case 1:
                            stream = _c.sent();
                            previousTracks.forEach(function (track) { return _this._stream.removeTrack(track); });
                            currentTracks = stream.getTracks();
                            currentTracks.forEach(function (track) { return _this._stream.addTrack(track); });
                            return [3, 3];
                        case 2:
                            previousTracks.forEach(function (track) { return _this._stream.removeTrack(track); });
                            _c.label = 3;
                        case 3:
                            previousTracks.forEach(function (track) { return track.stop(); });
                            return [4, this.emit("replaceTrack", previousTracks, currentTracks, constraints)];
                        case 4:
                            _c.sent();
                            _c.label = 5;
                        case 5: return [2];
                    }
                });
            });
        };
        LocalMedia.prototype.grabVideoFrame = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, _super.prototype.grabVideoFrame.call(this, this._sink.videoSink)];
                });
            });
        };
        return LocalMedia;
    }(WebRtcMedia));

    var DeviceInfo = (function () {
        function DeviceInfo(device) {
            this.device = device;
        }
        Object.defineProperty(DeviceInfo.prototype, "deviceId", {
            get: function () {
                return this.device.deviceId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DeviceInfo.prototype, "groupId", {
            get: function () {
                return this.device.groupId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DeviceInfo.prototype, "label", {
            get: function () {
                return this.device.label;
            },
            enumerable: false,
            configurable: true
        });
        return DeviceInfo;
    }());
    var AudioInput = (function (_super) {
        __extends(AudioInput, _super);
        function AudioInput(device) {
            return _super.call(this, device) || this;
        }
        Object.defineProperty(AudioInput.prototype, "kind", {
            get: function () {
                return "audioinput";
            },
            enumerable: false,
            configurable: true
        });
        return AudioInput;
    }(DeviceInfo));
    var VideoInput = (function (_super) {
        __extends(VideoInput, _super);
        function VideoInput(device) {
            return _super.call(this, device) || this;
        }
        Object.defineProperty(VideoInput.prototype, "kind", {
            get: function () {
                return "videoinput";
            },
            enumerable: false,
            configurable: true
        });
        return VideoInput;
    }(DeviceInfo));
    var AudioOutput = (function (_super) {
        __extends(AudioOutput, _super);
        function AudioOutput(device) {
            return _super.call(this, device) || this;
        }
        Object.defineProperty(AudioOutput.prototype, "kind", {
            get: function () {
                return "audiooutput";
            },
            enumerable: false,
            configurable: true
        });
        return AudioOutput;
    }(DeviceInfo));
    var MediaDevice = (function () {
        function MediaDevice() {
            this.audioInput = [];
            this.videoInput = [];
            this.audioOutput = [];
        }
        MediaDevice.prototype.addDevice = function (device) {
            if (device) {
                switch (device.kind) {
                    case "audioinput":
                        this.audioInput.push(device instanceof AudioInput ? device : new AudioInput(device));
                        break;
                    case "videoinput":
                        this.videoInput.push(device instanceof VideoInput ? device : new VideoInput(device));
                        break;
                    case "audiooutput":
                        this.audioOutput.push(device instanceof AudioOutput ? device : new AudioOutput(device));
                        break;
                }
            }
        };
        Object.defineProperty(MediaDevice.prototype, "audioInputEnabled", {
            get: function () {
                return !!this.audioInput.length;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MediaDevice.prototype, "audioOutputEnabled", {
            get: function () {
                return !!this.audioOutput.length;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MediaDevice.prototype, "videoInputEnabled", {
            get: function () {
                return !!this.videoInput.length;
            },
            enumerable: false,
            configurable: true
        });
        MediaDevice.prototype.hasDevice = function (device) {
            return this.hasAudioInput(device) || this.hasAudioOutput(device) || this.hasVideoInput(device);
        };
        MediaDevice.prototype.hasAudioInput = function (device) {
            return !!this.audioInput.find(function (d) { return d.deviceId === device.deviceId; });
        };
        MediaDevice.prototype.hasAudioOutput = function (device) {
            return !!this.audioOutput.find(function (d) { return d.deviceId === device.deviceId; });
        };
        MediaDevice.prototype.hasVideoInput = function (device) {
            return !!this.videoInput.find(function (d) { return d.deviceId === device.deviceId; });
        };
        return MediaDevice;
    }());
    var MediaDeviceRetrieved = (function (_super) {
        __extends(MediaDeviceRetrieved, _super);
        function MediaDeviceRetrieved(retrivedWithUserAuthorization) {
            var _this = _super.call(this) || this;
            _this.retrivedWithUserAuthorization = retrivedWithUserAuthorization;
            return _this;
        }
        return MediaDeviceRetrieved;
    }(MediaDevice));
    var MediaDeviceManager = (function () {
        function MediaDeviceManager() {
            this.mediaAvailableSubject = new BehaviorSubject({ audio: false, video: false });
            this.deviceSubject = new BehaviorSubject(new MediaDeviceRetrieved(false));
            this.deviceChange = this.deviceSubject.pipe(distinctUntilChanged(function (prev, next) { return prev.audioInput.length === next.audioInput.length && prev.audioOutput.length === next.audioOutput.length && prev.videoInput.length === next.videoInput.length; }));
            this.mediaAvailable = this.mediaAvailableSubject.asObservable().pipe(distinctUntilChanged(function (m1, m2) { return m1.audio === m2.audio && m1.video === m2.video; }), share());
            this.deviceIdToIgnore = ["default", "communications"];
            var prevOndevicechange = navigator.mediaDevices.ondevicechange;
            var onDeviceChangeHandler = this.deviceChangeHandler.bind(this);
            navigator.mediaDevices.ondevicechange = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                if (prevOndevicechange)
                    prevOndevicechange.apply(this, args);
                onDeviceChangeHandler.apply(this, args);
            };
        }
        MediaDeviceManager.prototype.deviceChangeHandler = function () {
            this.getMediaDevice(false, true, true);
        };
        MediaDeviceManager.prototype.getMediaDevice = function (startMedia, acquireAudio, acquireVideo) {
            return __awaiter(this, void 0, void 0, function () {
                var localStream, mediaDevice, devices;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            localStream = new LocalMedia({ audio: acquireAudio, video: acquireVideo });
                            if (!startMedia) return [3, 2];
                            return [4, localStream.start()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            mediaDevice = new MediaDeviceRetrieved(startMedia);
                            _a.label = 3;
                        case 3:
                            _a.trys.push([3, , 5, 8]);
                            return [4, navigator.mediaDevices.enumerateDevices()];
                        case 4:
                            devices = _a.sent();
                            devices.filter(function (device) { return (_this.deviceIdToIgnore && _this.deviceIdToIgnore.includes(device.deviceId) ? false : true); }).forEach(function (d) { return mediaDevice.addDevice(d); });
                            return [3, 8];
                        case 5:
                            if (!startMedia) return [3, 7];
                            return [4, localStream.stop()];
                        case 6:
                            _a.sent();
                            _a.label = 7;
                        case 7: return [7];
                        case 8:
                            this.deviceSubject.next(mediaDevice);
                            this.mediaAvailableSubject.next({ audio: !!mediaDevice.audioInput.length, video: !!mediaDevice.videoInput.length });
                            return [2, mediaDevice];
                    }
                });
            });
        };
        return MediaDeviceManager;
    }());
    var DeviceManager = new MediaDeviceManager();

    var RemoteMedia = (function (_super) {
        __extends(RemoteMedia, _super);
        function RemoteMedia() {
            var _this = _super.call(this) || this;
            _this._id = uuidv4();
            _this._started = false;
            _this._sink = new RemoteMediaSink(_this);
            return _this;
        }
        Object.defineProperty(RemoteMedia.prototype, "sink", {
            get: function () {
                return this._sink;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RemoteMedia.prototype, "id", {
            get: function () {
                return this._id;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RemoteMedia.prototype, "started", {
            get: function () {
                return this._started;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RemoteMedia.prototype, "audioOutput", {
            get: function () {
                return this._audioOutput;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RemoteMedia.prototype, "stream", {
            get: function () {
                return this._stream;
            },
            set: function (stream) {
                var _this = this;
                if (stream && this._stream !== stream) {
                    this.setStream(stream);
                    stream.onremovetrack = function (_a) {
                        var track = _a.track;
                        _this.removeTrack(track);
                    };
                    this._started = true;
                    this.emit("start");
                }
            },
            enumerable: false,
            configurable: true
        });
        RemoteMedia.prototype.addTrack = function (track) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.stream) {
                                this.stream = new MediaStream();
                            }
                            return [4, this._sink.addTrack(track)];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        RemoteMedia.prototype.removeTrack = function (track) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this._sink.removeTrack(track)];
                        case 1:
                            _a.sent();
                            return [2];
                    }
                });
            });
        };
        RemoteMedia.prototype.dispose = function () {
            this.emit("stop");
            _super.prototype.dispose.call(this);
        };
        RemoteMedia.prototype.setAudioOutput = function (audioOutput) {
            return __awaiter(this, void 0, void 0, function () {
                var prevAudioOutput, e_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            prevAudioOutput = this._audioOutput;
                            if (audioOutput) {
                                if (audioOutput.kind === "audiooutput") {
                                    this._audioOutput = audioOutput;
                                }
                                else {
                                    throw new TLinkError("error on RemoteMedia.changeAudioOutput, audioOutput.kind is ".concat(audioOutput.kind));
                                }
                            }
                            else {
                                this._audioOutput = undefined;
                            }
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4, this.emit("changeAudioOutput", audioOutput)];
                        case 2:
                            _a.sent();
                            return [3, 4];
                        case 3:
                            e_1 = _a.sent();
                            this._audioOutput = prevAudioOutput;
                            throw new TLinkError("error on RemoteMedia.changeAudioOutput", e_1);
                        case 4: return [2];
                    }
                });
            });
        };
        RemoteMedia.prototype.grabVideoFrame = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2, _super.prototype.grabVideoFrame.call(this, this._sink.videoSink)];
                });
            });
        };
        return RemoteMedia;
    }(WebRtcMedia));

    var StatusWrapper = (function () {
        function StatusWrapper(_value) {
            this._value = _value;
            this._changeTime = new Date();
            this._millisElapsedFromLastChange = 0;
            this.value = _value;
        }
        Object.defineProperty(StatusWrapper.prototype, "value", {
            get: function () {
                return this._value;
            },
            set: function (value) {
                var time = new Date();
                this._millisElapsedFromLastChange = time.getMilliseconds() - this._changeTime.getMilliseconds();
                if (this._millisElapsedFromLastChange < 0) {
                    this._millisElapsedFromLastChange = 0;
                }
                this._changeTime = time;
                this._value = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(StatusWrapper.prototype, "changeTime", {
            get: function () {
                return this._changeTime;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(StatusWrapper.prototype, "millisElapsedFromLastChange", {
            get: function () {
                return this._millisElapsedFromLastChange;
            },
            enumerable: false,
            configurable: true
        });
        return StatusWrapper;
    }());

    var parser$1 = {};

    var grammarExports = {};
    var grammar$2 = {
      get exports(){ return grammarExports; },
      set exports(v){ grammarExports = v; },
    };

    var grammar$1 = grammar$2.exports = {
      v: [{
        name: 'version',
        reg: /^(\d*)$/
      }],
      o: [{
        name: 'origin',
        reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
        names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
        format: '%s %s %d %s IP%d %s'
      }],
      s: [{ name: 'name' }],
      i: [{ name: 'description' }],
      u: [{ name: 'uri' }],
      e: [{ name: 'email' }],
      p: [{ name: 'phone' }],
      z: [{ name: 'timezones' }],
      r: [{ name: 'repeats' }],
      t: [{
        name: 'timing',
        reg: /^(\d*) (\d*)/,
        names: ['start', 'stop'],
        format: '%d %d'
      }],
      c: [{
        name: 'connection',
        reg: /^IN IP(\d) (\S*)/,
        names: ['version', 'ip'],
        format: 'IN IP%d %s'
      }],
      b: [{
        push: 'bandwidth',
        reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
        names: ['type', 'limit'],
        format: '%s:%s'
      }],
      m: [{
        reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/,
        names: ['type', 'port', 'protocol', 'payloads'],
        format: '%s %d %s %s'
      }],
      a: [
        {
          push: 'rtp',
          reg: /^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
          names: ['payload', 'codec', 'rate', 'encoding'],
          format: function (o) {
            return (o.encoding)
              ? 'rtpmap:%d %s/%s/%s'
              : o.rate
                ? 'rtpmap:%d %s/%s'
                : 'rtpmap:%d %s';
          }
        },
        {
          push: 'fmtp',
          reg: /^fmtp:(\d*) ([\S| ]*)/,
          names: ['payload', 'config'],
          format: 'fmtp:%d %s'
        },
        {
          name: 'control',
          reg: /^control:(.*)/,
          format: 'control:%s'
        },
        {
          name: 'rtcp',
          reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
          names: ['port', 'netType', 'ipVer', 'address'],
          format: function (o) {
            return (o.address != null)
              ? 'rtcp:%d %s IP%d %s'
              : 'rtcp:%d';
          }
        },
        {
          push: 'rtcpFbTrrInt',
          reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
          names: ['payload', 'value'],
          format: 'rtcp-fb:%s trr-int %d'
        },
        {
          push: 'rtcpFb',
          reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
          names: ['payload', 'type', 'subtype'],
          format: function (o) {
            return (o.subtype != null)
              ? 'rtcp-fb:%s %s %s'
              : 'rtcp-fb:%s %s';
          }
        },
        {
          push: 'ext',
          reg: /^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,
          names: ['value', 'direction', 'encrypt-uri', 'uri', 'config'],
          format: function (o) {
            return (
              'extmap:%d' +
              (o.direction ? '/%s' : '%v') +
              (o['encrypt-uri'] ? ' %s' : '%v') +
              ' %s' +
              (o.config ? ' %s' : '')
            );
          }
        },
        {
          name: 'extmapAllowMixed',
          reg: /^(extmap-allow-mixed)/
        },
        {
          push: 'crypto',
          reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
          names: ['id', 'suite', 'config', 'sessionConfig'],
          format: function (o) {
            return (o.sessionConfig != null)
              ? 'crypto:%d %s %s %s'
              : 'crypto:%d %s %s';
          }
        },
        {
          name: 'setup',
          reg: /^setup:(\w*)/,
          format: 'setup:%s'
        },
        {
          name: 'connectionType',
          reg: /^connection:(new|existing)/,
          format: 'connection:%s'
        },
        {
          name: 'mid',
          reg: /^mid:([^\s]*)/,
          format: 'mid:%s'
        },
        {
          name: 'msid',
          reg: /^msid:(.*)/,
          format: 'msid:%s'
        },
        {
          name: 'ptime',
          reg: /^ptime:(\d*(?:\.\d*)*)/,
          format: 'ptime:%d'
        },
        {
          name: 'maxptime',
          reg: /^maxptime:(\d*(?:\.\d*)*)/,
          format: 'maxptime:%d'
        },
        {
          name: 'direction',
          reg: /^(sendrecv|recvonly|sendonly|inactive)/
        },
        {
          name: 'icelite',
          reg: /^(ice-lite)/
        },
        {
          name: 'iceUfrag',
          reg: /^ice-ufrag:(\S*)/,
          format: 'ice-ufrag:%s'
        },
        {
          name: 'icePwd',
          reg: /^ice-pwd:(\S*)/,
          format: 'ice-pwd:%s'
        },
        {
          name: 'fingerprint',
          reg: /^fingerprint:(\S*) (\S*)/,
          names: ['type', 'hash'],
          format: 'fingerprint:%s %s'
        },
        {
          push:'candidates',
          reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,
          names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'],
          format: function (o) {
            var str = 'candidate:%s %d %s %d %s %d typ %s';
            str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v';
            str += (o.tcptype != null) ? ' tcptype %s' : '%v';
            if (o.generation != null) {
              str += ' generation %d';
            }
            str += (o['network-id'] != null) ? ' network-id %d' : '%v';
            str += (o['network-cost'] != null) ? ' network-cost %d' : '%v';
            return str;
          }
        },
        {
          name: 'endOfCandidates',
          reg: /^(end-of-candidates)/
        },
        {
          name: 'remoteCandidates',
          reg: /^remote-candidates:(.*)/,
          format: 'remote-candidates:%s'
        },
        {
          name: 'iceOptions',
          reg: /^ice-options:(\S*)/,
          format: 'ice-options:%s'
        },
        {
          push: 'ssrcs',
          reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,
          names: ['id', 'attribute', 'value'],
          format: function (o) {
            var str = 'ssrc:%d';
            if (o.attribute != null) {
              str += ' %s';
              if (o.value != null) {
                str += ':%s';
              }
            }
            return str;
          }
        },
        {
          push: 'ssrcGroups',
          reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,
          names: ['semantics', 'ssrcs'],
          format: 'ssrc-group:%s %s'
        },
        {
          name: 'msidSemantic',
          reg: /^msid-semantic:\s?(\w*) (\S*)/,
          names: ['semantic', 'token'],
          format: 'msid-semantic: %s %s'
        },
        {
          push: 'groups',
          reg: /^group:(\w*) (.*)/,
          names: ['type', 'mids'],
          format: 'group:%s %s'
        },
        {
          name: 'rtcpMux',
          reg: /^(rtcp-mux)/
        },
        {
          name: 'rtcpRsize',
          reg: /^(rtcp-rsize)/
        },
        {
          name: 'sctpmap',
          reg: /^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,
          names: ['sctpmapNumber', 'app', 'maxMessageSize'],
          format: function (o) {
            return (o.maxMessageSize != null)
              ? 'sctpmap:%s %s %s'
              : 'sctpmap:%s %s';
          }
        },
        {
          name: 'xGoogleFlag',
          reg: /^x-google-flag:([^\s]*)/,
          format: 'x-google-flag:%s'
        },
        {
          push: 'rids',
          reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,
          names: ['id', 'direction', 'params'],
          format: function (o) {
            return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s';
          }
        },
        {
          push: 'imageattrs',
          reg: new RegExp(
            '^imageattr:(\\d+|\\*)' +
            '[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)' +
            '(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?'
          ),
          names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'],
          format: function (o) {
            return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : '');
          }
        },
        {
          name: 'simulcast',
          reg: new RegExp(
            '^simulcast:' +
            '(send|recv) ([a-zA-Z0-9\\-_~;,]+)' +
            '(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?' +
            '$'
          ),
          names: ['dir1', 'list1', 'dir2', 'list2'],
          format: function (o) {
            return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : '');
          }
        },
        {
          name: 'simulcast_03',
          reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/,
          names: ['value'],
          format: 'simulcast: %s'
        },
        {
          name: 'framerate',
          reg: /^framerate:(\d+(?:$|\.\d+))/,
          format: 'framerate:%s'
        },
        {
          name: 'sourceFilter',
          reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,
          names: ['filterMode', 'netType', 'addressTypes', 'destAddress', 'srcList'],
          format: 'source-filter: %s %s %s %s %s'
        },
        {
          name: 'bundleOnly',
          reg: /^(bundle-only)/
        },
        {
          name: 'label',
          reg: /^label:(.+)/,
          format: 'label:%s'
        },
        {
          name: 'sctpPort',
          reg: /^sctp-port:(\d+)$/,
          format: 'sctp-port:%s'
        },
        {
          name: 'maxMessageSize',
          reg: /^max-message-size:(\d+)$/,
          format: 'max-message-size:%s'
        },
        {
          push:'tsRefClocks',
          reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/,
          names: ['clksrc', 'clksrcExt'],
          format: function (o) {
            return 'ts-refclk:%s' + (o.clksrcExt != null ? '=%s' : '');
          }
        },
        {
          name:'mediaClk',
          reg: /^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,
          names: ['id', 'mediaClockName', 'mediaClockValue', 'rateNumerator', 'rateDenominator'],
          format: function (o) {
            var str = 'mediaclk:';
            str += (o.id != null ? 'id=%s %s' : '%v%s');
            str += (o.mediaClockValue != null ? '=%s' : '');
            str += (o.rateNumerator != null ? ' rate=%s' : '');
            str += (o.rateDenominator != null ? '/%s' : '');
            return str;
          }
        },
        {
          name: 'keywords',
          reg: /^keywds:(.+)$/,
          format: 'keywds:%s'
        },
        {
          name: 'content',
          reg: /^content:(.+)/,
          format: 'content:%s'
        },
        {
          name: 'bfcpFloorCtrl',
          reg: /^floorctrl:(c-only|s-only|c-s)/,
          format: 'floorctrl:%s'
        },
        {
          name: 'bfcpConfId',
          reg: /^confid:(\d+)/,
          format: 'confid:%s'
        },
        {
          name: 'bfcpUserId',
          reg: /^userid:(\d+)/,
          format: 'userid:%s'
        },
        {
          name: 'bfcpFloorId',
          reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,
          names: ['id', 'mStream'],
          format: 'floorid:%s mstrm:%s'
        },
        {
          push: 'invalid',
          names: ['value']
        }
      ]
    };
    Object.keys(grammar$1).forEach(function (key) {
      var objs = grammar$1[key];
      objs.forEach(function (obj) {
        if (!obj.reg) {
          obj.reg = /(.*)/;
        }
        if (!obj.format) {
          obj.format = '%s';
        }
      });
    });

    (function (exports) {
    	var toIntIfInt = function (v) {
    	  return String(Number(v)) === v ? Number(v) : v;
    	};
    	var attachProperties = function (match, location, names, rawName) {
    	  if (rawName && !names) {
    	    location[rawName] = toIntIfInt(match[1]);
    	  }
    	  else {
    	    for (var i = 0; i < names.length; i += 1) {
    	      if (match[i+1] != null) {
    	        location[names[i]] = toIntIfInt(match[i+1]);
    	      }
    	    }
    	  }
    	};
    	var parseReg = function (obj, location, content) {
    	  var needsBlank = obj.name && obj.names;
    	  if (obj.push && !location[obj.push]) {
    	    location[obj.push] = [];
    	  }
    	  else if (needsBlank && !location[obj.name]) {
    	    location[obj.name] = {};
    	  }
    	  var keyLocation = obj.push ?
    	    {} :
    	    needsBlank ? location[obj.name] : location;
    	  attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
    	  if (obj.push) {
    	    location[obj.push].push(keyLocation);
    	  }
    	};
    	var grammar = grammarExports;
    	var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
    	exports.parse = function (sdp) {
    	  var session = {}
    	    , media = []
    	    , location = session;
    	  sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
    	    var type = l[0];
    	    var content = l.slice(2);
    	    if (type === 'm') {
    	      media.push({rtp: [], fmtp: []});
    	      location = media[media.length-1];
    	    }
    	    for (var j = 0; j < (grammar[type] || []).length; j += 1) {
    	      var obj = grammar[type][j];
    	      if (obj.reg.test(content)) {
    	        return parseReg(obj, location, content);
    	      }
    	    }
    	  });
    	  session.media = media;
    	  return session;
    	};
    	var paramReducer = function (acc, expr) {
    	  var s = expr.split(/=(.+)/, 2);
    	  if (s.length === 2) {
    	    acc[s[0]] = toIntIfInt(s[1]);
    	  } else if (s.length === 1 && expr.length > 1) {
    	    acc[s[0]] = undefined;
    	  }
    	  return acc;
    	};
    	exports.parseParams = function (str) {
    	  return str.split(/;\s?/).reduce(paramReducer, {});
    	};
    	exports.parseFmtpConfig = exports.parseParams;
    	exports.parsePayloads = function (str) {
    	  return str.toString().split(' ').map(Number);
    	};
    	exports.parseRemoteCandidates = function (str) {
    	  var candidates = [];
    	  var parts = str.split(' ').map(toIntIfInt);
    	  for (var i = 0; i < parts.length; i += 3) {
    	    candidates.push({
    	      component: parts[i],
    	      ip: parts[i + 1],
    	      port: parts[i + 2]
    	    });
    	  }
    	  return candidates;
    	};
    	exports.parseImageAttributes = function (str) {
    	  return str.split(' ').map(function (item) {
    	    return item.substring(1, item.length-1).split(',').reduce(paramReducer, {});
    	  });
    	};
    	exports.parseSimulcastStreamList = function (str) {
    	  return str.split(';').map(function (stream) {
    	    return stream.split(',').map(function (format) {
    	      var scid, paused = false;
    	      if (format[0] !== '~') {
    	        scid = toIntIfInt(format);
    	      } else {
    	        scid = toIntIfInt(format.substring(1, format.length));
    	        paused = true;
    	      }
    	      return {
    	        scid: scid,
    	        paused: paused
    	      };
    	    });
    	  });
    	};
    } (parser$1));

    var grammar = grammarExports;
    var formatRegExp = /%[sdv%]/g;
    var format = function (formatStr) {
      var i = 1;
      var args = arguments;
      var len = args.length;
      return formatStr.replace(formatRegExp, function (x) {
        if (i >= len) {
          return x;
        }
        var arg = args[i];
        i += 1;
        switch (x) {
        case '%%':
          return '%';
        case '%s':
          return String(arg);
        case '%d':
          return Number(arg);
        case '%v':
          return '';
        }
      });
    };
    var makeLine = function (type, obj, location) {
      var str = obj.format instanceof Function ?
        (obj.format(obj.push ? location : location[obj.name])) :
        obj.format;
      var args = [type + '=' + str];
      if (obj.names) {
        for (var i = 0; i < obj.names.length; i += 1) {
          var n = obj.names[i];
          if (obj.name) {
            args.push(location[obj.name][n]);
          }
          else {
            args.push(location[obj.names[i]]);
          }
        }
      }
      else {
        args.push(location[obj.name]);
      }
      return format.apply(null, args);
    };
    var defaultOuterOrder = [
      'v', 'o', 's', 'i',
      'u', 'e', 'p', 'c',
      'b', 't', 'r', 'z', 'a'
    ];
    var defaultInnerOrder = ['i', 'c', 'b', 'a'];
    var writer$1 = function (session, opts) {
      opts = opts || {};
      if (session.version == null) {
        session.version = 0;
      }
      if (session.name == null) {
        session.name = ' ';
      }
      session.media.forEach(function (mLine) {
        if (mLine.payloads == null) {
          mLine.payloads = '';
        }
      });
      var outerOrder = opts.outerOrder || defaultOuterOrder;
      var innerOrder = opts.innerOrder || defaultInnerOrder;
      var sdp = [];
      outerOrder.forEach(function (type) {
        grammar[type].forEach(function (obj) {
          if (obj.name in session && session[obj.name] != null) {
            sdp.push(makeLine(type, obj, session));
          }
          else if (obj.push in session && session[obj.push] != null) {
            session[obj.push].forEach(function (el) {
              sdp.push(makeLine(type, obj, el));
            });
          }
        });
      });
      session.media.forEach(function (mLine) {
        sdp.push(makeLine('m', grammar.m[0], mLine));
        innerOrder.forEach(function (type) {
          grammar[type].forEach(function (obj) {
            if (obj.name in mLine && mLine[obj.name] != null) {
              sdp.push(makeLine(type, obj, mLine));
            }
            else if (obj.push in mLine && mLine[obj.push] != null) {
              mLine[obj.push].forEach(function (el) {
                sdp.push(makeLine(type, obj, el));
              });
            }
          });
        });
      });
      return sdp.join('\r\n') + '\r\n';
    };

    var parser = parser$1;
    var writer = writer$1;
    var write = writer;
    var parse$1 = parser.parse;

    var SessionDescription = (function () {
        function SessionDescription(sdp, type) {
            this._sdp = sdp ? parse$1(sdp) : {};
            this._type = type;
        }
        SessionDescription.fromJson = function (sessionDescription) {
            var sdJ = JSON.parse(sessionDescription);
            return new SessionDescription(sdJ.sdpMessage || "", sdJ.isOffer ? SessionDescription.Type.Offer : SessionDescription.Type.Answer);
        };
        Object.defineProperty(SessionDescription.prototype, "sdp", {
            get: function () {
                return this._sdp;
            },
            enumerable: false,
            configurable: true
        });
        SessionDescription.prototype.toJson = function () {
            return JSON.stringify({
                isOffer: SessionDescription.Type.Offer === this._type,
                sdpMessage: this.getSdpMessageAsString(),
            });
        };
        SessionDescription.prototype.getSdpMessageAsString = function () {
            return this._sdp ? write(this._sdp) : "";
        };
        SessionDescription.prototype.getType = function () {
            return this._type;
        };
        SessionDescription.prototype.hasAudio = function () {
            var _a;
            return !!((_a = this._sdp) === null || _a === void 0 ? void 0 : _a.media["audio"]);
        };
        SessionDescription.prototype.hasVideo = function () {
            var _a;
            return !!((_a = this._sdp) === null || _a === void 0 ? void 0 : _a.media["video"]);
        };
        SessionDescription.prototype.hasData = function () {
            var _a;
            return !!((_a = this._sdp) === null || _a === void 0 ? void 0 : _a.media["application"]);
        };
        SessionDescription.prototype.extractMedia = function (mediaType) {
            var _a;
            var media = "".concat(mediaType).toLowerCase();
            return (_a = this._sdp.media) === null || _a === void 0 ? void 0 : _a.filter(function (m) {
                return media === m.type.toLowerCase();
            });
        };
        return SessionDescription;
    }());
    (function (SessionDescription) {
        (function (Type) {
            Type["Offer"] = "offer";
            Type["Answer"] = "answer";
        })(SessionDescription.Type || (SessionDescription.Type = {}));
    })(SessionDescription || (SessionDescription = {}));
    var Candidate = (function () {
        function Candidate(init) {
            this.candidate = init instanceof RTCIceCandidate ? init : new RTCIceCandidate(init);
        }
        Candidate.fromJson = function (candidateJson) {
            var _a, _b, _c;
            var cJ = JSON.parse(candidateJson);
            var sdpCandidateAttribute = cJ.sdpCandidateAttribute;
            var sdpMLineIndex = (_a = cJ.sdpMediaIndex) !== null && _a !== void 0 ? _a : 0;
            var sdpMid = "".concat((_c = (_b = cJ.sdpMid) !== null && _b !== void 0 ? _b : cJ.mid) !== null && _c !== void 0 ? _c : "");
            var usernameFragment = cJ.usernameFragment;
            if (sdpCandidateAttribute.indexOf("a=".concat(Candidate.attributeName, ":")) === 0) {
                sdpCandidateAttribute = sdpCandidateAttribute.substring(12);
            }
            else if (sdpCandidateAttribute.indexOf("".concat(Candidate.attributeName, ":")) === 0) {
                sdpCandidateAttribute = sdpCandidateAttribute.substring(10);
            }
            return new Candidate({
                candidate: "".concat(Candidate.attributeName, ":").concat(sdpCandidateAttribute),
                sdpMLineIndex: sdpMLineIndex,
                sdpMid: sdpMid,
                usernameFragment: usernameFragment ? usernameFragment : Candidate.candidatePartsFromValue(sdpCandidateAttribute).ufrag,
            });
        };
        Candidate.prototype.toJson = function () {
            return JSON.stringify({
                mid: this.candidate.sdpMid,
                sdpMediaIndex: this.candidate.sdpMLineIndex,
                sdpCandidateAttribute: this.candidate.candidate,
            });
        };
        Object.defineProperty(Candidate.prototype, "parts", {
            get: function () {
                return this.candidate;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Candidate.prototype, "type", {
            get: function () {
                return this.candidate.type;
            },
            enumerable: false,
            configurable: true
        });
        Candidate.prototype.toParts = function () {
            return Candidate.candidatePartsFromValue(this.candidate.candidate);
        };
        return Candidate;
    }());
    (function (Candidate) {
        Candidate.attributeName = "candidate";
        (function (Type) {
            Type["Host"] = "host";
            Type["Srflx"] = "srflx";
            Type["Relay"] = "relay";
        })(Candidate.Type || (Candidate.Type = {}));
        function candidatePartsFromValue(value) {
            if (value.indexOf("a=".concat(Candidate.attributeName, ":")) === 0) {
                value = value.substring(12);
            }
            else if (value.indexOf("".concat(Candidate.attributeName, ":")) === 0) {
                value = value.substring(10);
            }
            var parts = value.split(" ");
            var result = {
                foundation: parts[0],
                component: parseInt(parts[1], 10),
                transport: "".concat(parts[2]).trim().toLowerCase(),
                priority: parseInt(parts[3], 10),
                ip: "".concat(parts[4]).trim(),
                port: parseInt(parts[5], 10),
                type: "".concat(parts[7]).trim().toLowerCase(),
            };
            for (var i = 8; i < parts.length; i += 2) {
                switch (parts[i]) {
                    case "rport":
                        result.rport = parseInt(parts[i + 1], 10);
                        break;
                    default:
                        result[parts[i]] = parts[i + 1];
                        break;
                }
            }
            return result;
        }
        Candidate.candidatePartsFromValue = candidatePartsFromValue;
    })(Candidate || (Candidate = {}));

    var StatsGatherer = (function (_super) {
        __extends(StatsGatherer, _super);
        function StatsGatherer(id, peerConnection) {
            var _this = _super.call(this) || this;
            _this.id = id;
            _this.peerConnection = peerConnection;
            return _this;
        }
        StatsGatherer.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.lastStatsItems = [];
            this.localCandidate = undefined;
            this.remoteCandidate = undefined;
        };
        StatsGatherer.prototype.getStats = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _a = this.createStatsEvent;
                            return [4, this.peerConnection.getStats(null).then(this.polyFillStats.bind(this))];
                        case 1: return [2, _a.apply(this, [_b.sent()])];
                    }
                });
            });
        };
        StatsGatherer.prototype.polyFillStats = function (results) {
            if (!results) {
                return [];
            }
            if (Array.isArray(results)) {
                return results;
            }
            var betterResults = [];
            if (typeof window.RTCStatsReport !== "undefined" && results instanceof window.RTCStatsReport) {
                results.forEach(function (value, key) {
                    betterResults.push({ key: key, value: value });
                });
            }
            else if (Object.keys(results).length > 0) {
                Object.keys(results).forEach(function (key) {
                    betterResults.push({
                        key: key,
                        value: results[key],
                    });
                });
            }
            return betterResults;
        };
        StatsGatherer.prototype.createStatsEvent = function (statsItems) {
            var _this = this;
            var _a;
            var statsEvent = {
                id: this.id,
                localTracks: [],
                remoteTracks: [],
            };
            statsItems
                .filter(function (r) { return ["inbound-rtp", "outbound-rtp"].indexOf(r.value.type) > -1; })
                .map(function (source) { return source.value; })
                .forEach(function (source) {
                _this.processRtpStreamStats(source, statsItems, statsEvent);
            });
            var candidatePair = (_a = statsItems.find(function (r) { return r.value.type === "candidate-pair" && r.value.state === "succeeded" && r.value.nominated === true; })) === null || _a === void 0 ? void 0 : _a.value;
            if (candidatePair) {
                this.processSelectedCandidatePair(candidatePair, statsItems, statsEvent);
            }
            this.lastStatsItems = statsItems;
            return statsEvent;
        };
        StatsGatherer.prototype.processRtpStreamStats = function (stats, statsItems, statsEvent) {
            var _a, _b, _c, _d, _e, _f;
            var now = new Date(stats.timestamp);
            var lastStats = (_b = (_a = this.lastStatsItems) === null || _a === void 0 ? void 0 : _a.find(function (r) { return r.key === stats.id; })) === null || _b === void 0 ? void 0 : _b.value;
            var lastResultRemoteSource;
            if (lastStats) {
                lastResultRemoteSource = (_d = (_c = this.lastStatsItems) === null || _c === void 0 ? void 0 : _c.find(function (r) { return r.value.localId === lastStats.id; })) === null || _d === void 0 ? void 0 : _d.value;
            }
            var trackId = stats.trackId || stats.id;
            var correspondingRemoteSource;
            var transport;
            var candidatePair;
            var track;
            var mediaSource;
            var codec;
            statsItems.forEach(function (r) {
                if (r.value.localId === stats.id) {
                    correspondingRemoteSource = r.value;
                }
                else if (r.key === stats.transportId) {
                    transport = r.value;
                }
                else if (r.key === trackId) {
                    track = r.value;
                }
                else if (r.key === stats.mediaSourceId) {
                    mediaSource = r.value;
                }
                else if (r.key === stats.codecId) {
                    codec = r.value;
                }
            });
            if (transport) {
                candidatePair = (_e = statsItems.find(function (r) { return r.key === transport.selectedCandidatePairId; })) === null || _e === void 0 ? void 0 : _e.value;
            }
            if (candidatePair) {
                statsEvent.candidatePairHadActiveSource = true;
            }
            var kind = (stats.kind || stats.mediaType);
            var isOutbound = stats.type === "outbound-rtp";
            var trackInfo = {
                track: (_f = track === null || track === void 0 ? void 0 : track.trackIdentifier) !== null && _f !== void 0 ? _f : "",
                kind: kind,
                jitter: getDefinedValue("jitter", stats, correspondingRemoteSource),
                roundTripTime: getDefinedValue("roundTripTime", stats, correspondingRemoteSource),
                packetsLost: getDefinedValue("packetsLost", stats, correspondingRemoteSource) || 0,
                packetLoss: 0,
                bytes: (isOutbound ? stats.bytesSent : stats.bytesReceived) || 0,
                codec: codec,
            };
            if (lastStats) {
                var previousBytesTotal = (isOutbound ? lastStats.bytesSent : lastStats.bytesReceived) || 0;
                var deltaTime = now.getTime() - new Date(lastStats.timestamp).getTime();
                trackInfo.bitrate = Math.floor((8 * (trackInfo.bytes - previousBytesTotal)) / deltaTime);
            }
            var lastPacketsLost = getDefinedValue("packetsLost", lastStats, lastResultRemoteSource);
            if (isOutbound) {
                trackInfo.packetsSent = stats.packetsSent;
                trackInfo.packetLoss = trackInfo.packetsLost ? (trackInfo.packetsLost / (trackInfo.packetsSent || 1)) * 100 : 0;
                if (lastStats) {
                    trackInfo.intervalPacketsSent = trackInfo.packetsSent - (lastStats.packetsSent || 0);
                    trackInfo.intervalPacketsLost = trackInfo.packetsLost - (lastPacketsLost || 0);
                    trackInfo.intervalPacketLoss = (trackInfo.intervalPacketsLost / (trackInfo.intervalPacketsSent || 1)) * 100;
                }
                trackInfo.retransmittedBytesSent = stats.retransmittedBytesSent;
                trackInfo.retransmittedPacketsSent = stats.retransmittedPacketsSent;
            }
            else {
                trackInfo.packetsReceived = stats.packetsReceived;
                trackInfo.packetLoss = trackInfo.packetsLost ? (trackInfo.packetsLost / (trackInfo.packetsReceived || 1)) * 100 : 0;
                if (lastStats) {
                    trackInfo.intervalPacketsReceived = trackInfo.packetsReceived - (lastStats.packetsReceived || 0);
                    trackInfo.intervalPacketsLost = trackInfo.packetsLost - lastPacketsLost;
                    trackInfo.intervalPacketLoss = (trackInfo.intervalPacketsLost / (trackInfo.intervalPacketsReceived || 1)) * 100;
                }
            }
            if (track) {
                if (kind === "audio") {
                    var audioTrack = track;
                    var audioTrackInfo = trackInfo;
                    if (audioTrack.remoteSource) {
                        audioTrackInfo.level = audioTrack.audioLevel;
                        audioTrackInfo.totalEnergy = audioTrack.totalAudioEnergy;
                    }
                    else {
                        audioTrackInfo.level = audioTrack.audioLevel;
                        audioTrackInfo.totalEnergy = audioTrack.totalAudioEnergy;
                        audioTrackInfo.totalSamplesDuration = audioTrack.totalSamplesDuration;
                        audioTrackInfo.echoReturnLoss = audioTrack.echoReturnLoss;
                        audioTrackInfo.echoReturnLossEnhancement = audioTrack.echoReturnLossEnhancement;
                    }
                }
                else if (kind === "video") {
                    var videoTrack = track;
                    var videoTrackInfo = trackInfo;
                    videoTrackInfo.frameWidth = videoTrack.frameWidth;
                    videoTrackInfo.frameHeight = videoTrack.frameHeight;
                    videoTrackInfo.framesReceived = videoTrack.framesReceived;
                    videoTrackInfo.framesSent = videoTrack.framesSent;
                    videoTrackInfo.framesDecoded = videoTrack.framesDecoded;
                    videoTrackInfo.framesDropped = videoTrack.framesDropped;
                    videoTrackInfo.framesReceived = videoTrack.framesReceived;
                }
            }
            if (mediaSource && (!track || !track.remoteSource)) {
                if (kind === "audio") {
                    var audioTrack = mediaSource;
                    var audioTrackInfo = trackInfo;
                    audioTrackInfo.level = audioTrack.audioLevel;
                    audioTrackInfo.totalEnergy = audioTrack.totalAudioEnergy;
                    audioTrackInfo.echoReturnLoss = audioTrack.echoReturnLoss;
                    audioTrackInfo.echoReturnLossEnhancement = audioTrack.echoReturnLossEnhancement;
                }
                else if (kind === "video") {
                    var videoTrack = mediaSource;
                    var videoTrackInfo = trackInfo;
                    videoTrackInfo.width = videoTrack.width;
                    videoTrackInfo.height = videoTrack.height;
                    videoTrackInfo.frames = videoTrack.frames;
                    videoTrackInfo.framesPerSecond = videoTrack.framesPerSecond;
                }
            }
            Object.keys(trackInfo).forEach(function (key) { return trackInfo[key] === undefined && delete trackInfo[key]; });
            if (isOutbound) {
                statsEvent.localTracks.push(trackInfo);
            }
            else {
                statsEvent.remoteTracks.push(trackInfo);
            }
        };
        StatsGatherer.prototype.processSelectedCandidatePair = function (candidatePairStats, statsItems, statsEvent) {
            var _this = this;
            var localId = candidatePairStats.localCandidateId;
            var remoteId = candidatePairStats.remoteCandidateId;
            var transporEvent = statsEvent.transport
                ? statsEvent.transport
                : {
                    timestamp: candidatePairStats.timestamp,
                };
            statsEvent.transport = transporEvent;
            statsEvent.localCandidateChanged = !!this.localCandidate && localId !== this.localCandidate.id;
            statsEvent.remoteCandidateChanged = !!this.remoteCandidate && remoteId !== this.remoteCandidate.id;
            if (!this.localCandidate || statsEvent.localCandidateChanged || statsEvent.remoteCandidateChanged) {
                statsItems.forEach(function (result) {
                    if (localId && result.value.type === "local-candidate" && result.value.id === localId) {
                        _this.localCandidate = result.value;
                    }
                    if (remoteId && result.value.type === "remote-candidate" && result.value.id === remoteId) {
                        _this.remoteCandidate = result.value;
                    }
                });
            }
            statsEvent.candidatePair = {
                local: this.localCandidate,
                remote: this.remoteCandidate,
            };
            transporEvent.bytesSent = candidatePairStats.bytesSent;
            transporEvent.bytesReceived = candidatePairStats.bytesReceived;
            transporEvent.requestsReceived = candidatePairStats.requestsReceived;
            transporEvent.requestsSent = candidatePairStats.requestsSent;
            transporEvent.responsesReceived = candidatePairStats.responsesReceived;
            transporEvent.responsesSent = candidatePairStats.responsesSent;
            transporEvent.consentRequestsSent = candidatePairStats.consentRequestsSent;
            transporEvent.totalRoundTripTime = candidatePairStats.totalRoundTripTime;
        };
        return StatsGatherer;
    }(Emitter));
    function getDefinedValue(propertyName) {
        var objects = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            objects[_i - 1] = arguments[_i];
        }
        var item = objects.find(function (obj) { return obj && (obj[propertyName] || obj[propertyName] === 0); });
        return item && item[propertyName];
    }

    var Connection = (function (_super) {
        __extends(Connection, _super);
        function Connection(rtcConfiguration, localMedia, remoteMedia) {
            if (rtcConfiguration === void 0) { rtcConfiguration = {}; }
            var _this = _super.call(this) || this;
            _this.rtcConfiguration = rtcConfiguration;
            _this.localMedia = localMedia;
            _this.remoteMedia = remoteMedia;
            _this._id = uuidv4();
            _this._trickleIcePolicy = Connection.TrickleIcePolicy.FullTrickle;
            _this._state = new StatusWrapper(Connection.State.New);
            _this._iceConnectionState = new StatusWrapper(Connection.IceConnectionState.New);
            _this._gatheringState = new StatusWrapper(Connection.IceGatheringState.New);
            _this._signallingState = new StatusWrapper(Connection.SignallingState.New);
            _this._discoveredCandidates = [];
            _this._iceGatherType = [Candidate.Type.Host, Candidate.Type.Srflx, Candidate.Type.Relay];
            _this._isRenegotiation = false;
            _this._localDescription = null;
            _this._remoteDescription = null;
            _this._timeout = 30000;
            _this._deadStreamTimeout = 30000;
            _this._iceCandidateProcessingTimeout = 2000;
            _this.localMedia.on("replaceTrack", function () {
                return _this.alingnPcSenderToLocalMediaTracks();
            });
            _this.localMedia.on("start", function () {
                return _this.alingnPcSenderToLocalMediaTracks();
            });
            _this.localMedia.on("stop", function () {
                return _this.alingnPcSenderToLocalMediaTracks();
            });
            return _this;
        }
        Object.defineProperty(Connection.prototype, "id", {
            get: function () {
                return this._id;
            },
            set: function (id) {
                this._id = id;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "error", {
            get: function () {
                return this._error;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "trickleIceSupported", {
            get: function () {
                return this._trickleIcePolicy !== Connection.TrickleIcePolicy.NotSupported;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "signallingState", {
            get: function () {
                return this._signallingState;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "audioSender", {
            get: function () {
                return this.getSender("audio");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "videoSender", {
            get: function () {
                return this.getSender("video");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "dtmfSender", {
            get: function () {
                var _this = this;
                var _a;
                if (!this._dtmfSender) {
                    this._dtmfSender = (_a = this.audioSender) === null || _a === void 0 ? void 0 : _a.dtmf;
                    if (this._dtmfSender) {
                        this._dtmfSender.ontonechange = function (_a) {
                            var tone = _a.tone;
                            _this.emit("sendDtmfToneChange", tone);
                        };
                    }
                }
                return this._dtmfSender;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "iceGatheringState", {
            get: function () {
                return this._gatheringState.value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "state", {
            get: function () {
                return this._state.value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "iceConnectionState", {
            get: function () {
                return this._iceConnectionState.value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "localDescription", {
            get: function () {
                return this._localDescription;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "remoteDescription", {
            get: function () {
                return this._remoteDescription;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "timeout", {
            get: function () {
                return this._timeout;
            },
            set: function (timeout) {
                this._timeout = timeout;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "deadStreamTimeout", {
            get: function () {
                return this.deadStreamTimeout;
            },
            set: function (deadStreamTimeout) {
                this._deadStreamTimeout = deadStreamTimeout;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "trickleIcePolicy", {
            set: function (trickleIcePolicy) {
                this._trickleIcePolicy = trickleIcePolicy;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "iceGatherType", {
            get: function () {
                return this._iceGatherType;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Connection.prototype, "iceServers", {
            get: function () {
                return this.rtcConfiguration.iceServers;
            },
            enumerable: false,
            configurable: true
        });
        Connection.prototype.start = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.initPeerConnection();
                            if (!this.localMedia.started) return [3, 2];
                            return [4, Promise.all([new Promise(function (resolve) { return (_this._pc.onnegotiationneeded = function () { return resolve(); }); }), this.alingnPcSenderToLocalMediaTracks()])];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2];
                    }
                });
            });
        };
        Connection.prototype.dispose = function () {
            var _a, _b;
            (_a = this._pc) === null || _a === void 0 ? void 0 : _a.close();
            this._pc = undefined;
            (_b = this._statsGatherer) === null || _b === void 0 ? void 0 : _b.dispose();
            this.remoteMedia.dispose();
            _super.prototype.dispose.call(this);
        };
        Connection.prototype.createOffer = function (options) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var _b, _c, e_1;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            _d.trys.push([0, 2, , 3]);
                            _b = this.rtcLocalSessionDescriptionToSessionDescription;
                            _c = [SessionDescription.Type.Offer];
                            return [4, ((_a = this._pc) === null || _a === void 0 ? void 0 : _a.createOffer(options))];
                        case 1: return [2, _b.apply(this, _c.concat([_d.sent()]))];
                        case 2:
                            e_1 = _d.sent();
                            throw new TLinkError("Error on createOffer", e_1);
                        case 3: return [2];
                    }
                });
            });
        };
        Connection.prototype.createAnswer = function (options) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var _b, _c, e_2;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            _d.trys.push([0, 2, , 3]);
                            _b = this.rtcLocalSessionDescriptionToSessionDescription;
                            _c = [SessionDescription.Type.Answer];
                            return [4, ((_a = this._pc) === null || _a === void 0 ? void 0 : _a.createAnswer(options))];
                        case 1: return [2, _b.apply(this, _c.concat([_d.sent()]))];
                        case 2:
                            e_2 = _d.sent();
                            throw new TLinkError("Error on createAnswer", e_2);
                        case 3: return [2];
                    }
                });
            });
        };
        Connection.prototype.rtcLocalSessionDescriptionToSessionDescription = function (type, sessionDescription) {
            var result = new SessionDescription(sessionDescription === null || sessionDescription === void 0 ? void 0 : sessionDescription.sdp, type);
            info("Local session description (".concat(type, ") for connection ").concat(this._id, ":\n").concat(result.getSdpMessageAsString()));
            return result;
        };
        Connection.prototype.setLocalDescription = function (sessionDescription) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var prevSignallingState, newSignallingState, e_3;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            prevSignallingState = this._signallingState;
                            switch (this._signallingState.value) {
                                case Connection.SignallingState.New:
                                case Connection.SignallingState.Stable:
                                    newSignallingState = Connection.SignallingState.HaveLocalOffer;
                                    break;
                                case Connection.SignallingState.HaveRemoteOffer:
                                    newSignallingState = Connection.SignallingState.Stable;
                                    break;
                            }
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 5, , 6]);
                            return [4, ((_a = this._pc) === null || _a === void 0 ? void 0 : _a.setLocalDescription({ sdp: sessionDescription.getSdpMessageAsString(), type: sessionDescription.getType() === SessionDescription.Type.Answer ? "answer" : "offer" }))];
                        case 2:
                            _b.sent();
                            this._localDescription = sessionDescription;
                            this.setSignallingState(newSignallingState);
                            if (this._remoteDescription && this._state.value !== Connection.State.Connected) {
                                this.setState(Connection.State.Connecting);
                            }
                            if (!!this.trickleIceSupported) return [3, 4];
                            return [4, new Promise(function (resolve, reject) {
                                    if (_this._gatheringState.value === Connection.IceGatheringState.Complete) {
                                        _this.injectDiscoveredCandidatesIntoSdp();
                                        resolve();
                                    }
                                    else {
                                        var dispose_1 = _this.on("gatheringStateChange", function (state) {
                                            if (state === Connection.IceGatheringState.Failed) {
                                                clearTimeout(timeout_1);
                                                dispose_1();
                                                reject("gatheringState error");
                                            }
                                            else if (state === Connection.IceGatheringState.Complete) {
                                                clearTimeout(timeout_1);
                                                dispose_1();
                                                resolve();
                                            }
                                        });
                                        var timeout_1 = setTimeout(function () {
                                            _this.injectDiscoveredCandidatesIntoSdp();
                                            dispose_1();
                                            resolve();
                                        }, _this._iceCandidateProcessingTimeout);
                                    }
                                })];
                        case 3:
                            _b.sent();
                            _b.label = 4;
                        case 4:
                            this.emit("localDescription", this._localDescription);
                            return [3, 6];
                        case 5:
                            e_3 = _b.sent();
                            this._signallingState = prevSignallingState;
                            throw new TLinkError("Error on setLocalDescription", e_3);
                        case 6: return [2, sessionDescription];
                    }
                });
            });
        };
        Connection.prototype.setRemoteDescription = function (sessionDescription) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var prevSignallingState, newSignallingState, e_4;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            prevSignallingState = this._signallingState;
                            switch (this._signallingState.value) {
                                case Connection.SignallingState.New:
                                case Connection.SignallingState.Stable:
                                    newSignallingState = Connection.SignallingState.HaveRemoteOffer;
                                    break;
                                case Connection.SignallingState.HaveRemoteOffer:
                                    newSignallingState = Connection.SignallingState.Stable;
                                    break;
                            }
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 3, , 4]);
                            return [4, ((_a = this._pc) === null || _a === void 0 ? void 0 : _a.setRemoteDescription({ sdp: sessionDescription.getSdpMessageAsString(), type: sessionDescription.getType() === SessionDescription.Type.Answer ? "answer" : "offer" }))];
                        case 2:
                            _b.sent();
                            info("Remote session description (".concat(sessionDescription.getType(), ") for connection ").concat(this._id, ":\n").concat(sessionDescription.getSdpMessageAsString()));
                            this._remoteDescription = sessionDescription;
                            this.setSignallingState(newSignallingState);
                            if (this.localDescription) {
                                if (this._state.value !== Connection.State.Connected) {
                                    this.setState(Connection.State.Connecting);
                                }
                            }
                            this.emit("remoteDescription", sessionDescription);
                            return [3, 4];
                        case 3:
                            e_4 = _b.sent();
                            this._signallingState = prevSignallingState;
                            throw new TLinkError("Error on setLocalDescription", e_4);
                        case 4: return [2, sessionDescription];
                    }
                });
            });
        };
        Connection.prototype.addRemoteCandidates = function (candidates) {
            return __awaiter(this, void 0, void 0, function () {
                var candidateByType, candidate;
                var _this = this;
                return __generator(this, function (_a) {
                    candidateByType = __spreadArray$1([], __read(candidates.filter(function (c) { return !!c; })), false).reduce(function (result, candidate) {
                        var candidateByType = result.get(candidate.type);
                        if (!candidateByType) {
                            candidateByType = [];
                            result.set(candidate.type, candidateByType);
                        }
                        candidateByType.push(candidate);
                        return result;
                    }, new Map());
                    candidate = __spreadArray$1(__spreadArray$1(__spreadArray$1([], __read((candidateByType.get(Candidate.Type.Host) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    })), false), __read((candidateByType.get(Candidate.Type.Srflx) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    })), false), __read((candidateByType.get(Candidate.Type.Relay) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    })), false);
                    return [2, Promise.all(candidate.map(function (candidate) { return _this.addRemoteCandidate(candidate); }))];
                });
            });
        };
        Connection.prototype.addRemoteCandidate = function (candidate) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var e_5;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 2, , 3]);
                            return [4, ((_a = this._pc) === null || _a === void 0 ? void 0 : _a.addIceCandidate(candidate.parts))];
                        case 1:
                            _b.sent();
                            info("Remote candidate for stream ".concat(candidate.parts.sdpMLineIndex, " for connection ").concat(this._id, ": ").concat(candidate.parts.candidate));
                            this.emit("remoteCandidate", candidate);
                            return [2, candidate];
                        case 2:
                            e_5 = _b.sent();
                            throw new TLinkError("error on addRemoteCandidate", e_5);
                        case 3: return [2];
                    }
                });
            });
        };
        Connection.prototype.setState = function (state) {
            this._state.value = state;
            info("Setting connection ".concat(this._id, " state to ").concat(state));
            switch (state) {
                case Connection.State.Connecting:
                    info("Connection ".concat(this.id, " took ").concat(this._state.millisElapsedFromLastChange, "ms to initialize (offer/answer signalling)."));
                    break;
                case Connection.State.Connected:
                    info("Connection ".concat(this.id, " took ").concat(this._state.millisElapsedFromLastChange, "ms to connect (connectivity checks and secure key exchange)."));
                    break;
            }
            this.emit("stateChange", state);
        };
        Connection.prototype.setSignallingState = function (state) {
            this._signallingState.value = state;
            this.emit("signallingStateChange", state);
        };
        Connection.prototype.getSender = function (kind) {
            var _a;
            return (_a = this._pc) === null || _a === void 0 ? void 0 : _a.getSenders().find(function (sender) { return sender.track && sender.track.kind === kind; });
        };
        Connection.prototype.alingnPcSenderToLocalMediaTracks = function () {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function () {
                var senderKind, tracksKind, _c, _d, _i, kind, tracks, sender, tracks_1, tracks_1_1, track, e_6_1;
                var e_6, _e;
                var _this = this;
                return __generator(this, function (_f) {
                    switch (_f.label) {
                        case 0:
                            if (!this._pc) {
                                return [2];
                            }
                            senderKind = {};
                            tracksKind = {};
                            (_b = (_a = this.localMedia.stream) === null || _a === void 0 ? void 0 : _a.getTracks()) === null || _b === void 0 ? void 0 : _b.forEach(function (track) {
                                if (!senderKind[track.kind]) {
                                    var sender = _this.getSender(track.kind);
                                    if (sender) {
                                        senderKind[track.kind] = sender;
                                    }
                                }
                                if (!tracksKind[track.kind]) {
                                    tracksKind[track.kind] = [];
                                }
                                tracksKind[track.kind].push(track);
                            });
                            _c = [];
                            for (_d in tracksKind)
                                _c.push(_d);
                            _i = 0;
                            _f.label = 1;
                        case 1:
                            if (!(_i < _c.length)) return [3, 13];
                            kind = _c[_i];
                            tracks = tracksKind[kind];
                            sender = senderKind[kind];
                            if (!(tracks && tracks.length)) return [3, 11];
                            _f.label = 2;
                        case 2:
                            _f.trys.push([2, 8, 9, 10]);
                            tracks_1 = (e_6 = void 0, __values(tracks)), tracks_1_1 = tracks_1.next();
                            _f.label = 3;
                        case 3:
                            if (!!tracks_1_1.done) return [3, 7];
                            track = tracks_1_1.value;
                            if (!sender) return [3, 5];
                            return [4, sender.replaceTrack(track)];
                        case 4:
                            _f.sent();
                            return [3, 6];
                        case 5:
                            this._pc.addTrack(track, this.localMedia.stream);
                            _f.label = 6;
                        case 6:
                            tracks_1_1 = tracks_1.next();
                            return [3, 3];
                        case 7: return [3, 10];
                        case 8:
                            e_6_1 = _f.sent();
                            e_6 = { error: e_6_1 };
                            return [3, 10];
                        case 9:
                            try {
                                if (tracks_1_1 && !tracks_1_1.done && (_e = tracks_1.return)) _e.call(tracks_1);
                            }
                            finally { if (e_6) throw e_6.error; }
                            return [7];
                        case 10: return [3, 12];
                        case 11:
                            if (sender) {
                                this._pc.removeTrack(sender);
                            }
                            _f.label = 12;
                        case 12:
                            _i++;
                            return [3, 1];
                        case 13: return [2];
                    }
                });
            });
        };
        Connection.prototype.initPeerConnection = function () {
            var _this = this;
            var pc = new RTCPeerConnection(this.rtcConfiguration);
            pc.ontrack = function (_a) {
                var track = _a.track, streams = _a.streams;
                if (streams && streams.length) {
                    _this.remoteMedia.stream = streams[0];
                }
                else {
                    _this.remoteMedia.addTrack(track);
                }
                if (_this._state.value == Connection.State.Connecting) {
                    _this.setState(Connection.State.Connected);
                }
            };
            pc.onicecandidate = function (_a) {
                var candidate = _a.candidate;
                if (candidate) {
                    var c = new Candidate(candidate);
                    if (c.parts.type && _this._iceGatherType.indexOf(c.type) > -1) {
                        if (_this.trickleIceSupported) {
                            _this.emit("localCandidate", c);
                        }
                        else {
                            _this._discoveredCandidates.push(c);
                        }
                    }
                }
            };
            pc.onicegatheringstatechange = function () {
                _this.setGatheringState(rtcIceGatheringStateToGatheringState(pc.iceGatheringState));
            };
            var deadStreamTimer;
            pc.oniceconnectionstatechange = function () {
                var state = rtcIceConnectionStateToConnectionState(pc.iceConnectionState);
                if (state) {
                    _this._iceConnectionState.value = state;
                    if (state === Connection.IceConnectionState.Connected || state === Connection.IceConnectionState.Completed) {
                        if (deadStreamTimer) {
                            debug("Connectivity checks have restored.");
                            clearTimeout(deadStreamTimer);
                            deadStreamTimer = null;
                        }
                        if (_this._state.value === Connection.State.Initializing) {
                            debug("Transitioning Connection from Initializing to Connecting state because inner iceConnectionState state is Connected.");
                            _this.setState(Connection.State.Connecting);
                        }
                        if (_this.remoteMedia.started && _this._state.value === Connection.State.Connecting) {
                            _this.setState(Connection.State.Connected);
                        }
                    }
                    if (state === Connection.IceConnectionState.Disconnected && _this._state.value === Connection.State.Connected) {
                        debug("Some connectivity checks have failed. Monitoring for dead stream.");
                        if (!deadStreamTimer) {
                            deadStreamTimer = setTimeout(function () {
                                info("Dead stream detected.");
                                deadStreamTimer = null;
                                _this.setState(Connection.State.Failed);
                            }, _this._deadStreamTimeout);
                        }
                    }
                    _this.emit("iceConnectionStateChange", _this._iceConnectionState.value);
                }
            };
            this._statsGatherer = new StatsGatherer(this._id, pc);
            this._pc = pc;
        };
        Connection.prototype.setGatheringState = function (state) {
            if (state && this._gatheringState.value != state) {
                this._gatheringState.value = state;
                if (state == Connection.IceGatheringState.Complete) {
                    if (!this.trickleIceSupported && !this._isRenegotiation && this._localDescription) {
                        this.injectDiscoveredCandidatesIntoSdp();
                    }
                }
                this.emit("gatheringStateChange", this._gatheringState.value);
            }
        };
        Connection.prototype.injectDiscoveredCandidatesIntoSdp = function () {
            var e_7, _a;
            if (this.localDescription) {
                var medias = this.localDescription.sdp.media;
                try {
                    for (var _b = __values(this._discoveredCandidates), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var candidate = _c.value;
                        var media = medias[candidate.parts.sdpMLineIndex];
                        if (!media.candidates) {
                            media.candidates = [];
                        }
                        media.candidates.push(candidate.toParts());
                    }
                }
                catch (e_7_1) { e_7 = { error: e_7_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_7) throw e_7.error; }
                }
            }
        };
        Connection.prototype.insertDTMF = function (tones, dtmfDuration, dtmfInterToneGap) {
            var _a;
            (_a = this.dtmfSender) === null || _a === void 0 ? void 0 : _a.insertDTMF(tones, dtmfDuration, dtmfInterToneGap);
        };
        Connection.prototype.getStats = function () {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_b) {
                    return [2, (_a = this._statsGatherer) === null || _a === void 0 ? void 0 : _a.getStats()];
                });
            });
        };
        return Connection;
    }(Emitter));
    (function (Connection) {
        (function (State) {
            State["New"] = "new";
            State["Initializing"] = "initializing";
            State["Connecting"] = "connecting";
            State["Connected"] = "connected";
            State["Failing"] = "failing";
            State["Failed"] = "failed";
            State["Closing"] = "closing";
            State["Closed"] = "closed";
        })(Connection.State || (Connection.State = {}));
        (function (IceConnectionState) {
            IceConnectionState["New"] = "new";
            IceConnectionState["Checking"] = "checking";
            IceConnectionState["Connected"] = "connected";
            IceConnectionState["Completed"] = "completed";
            IceConnectionState["Failed"] = "failed";
            IceConnectionState["Disconnected"] = "disconnected";
            IceConnectionState["Closed"] = "closed";
        })(Connection.IceConnectionState || (Connection.IceConnectionState = {}));
        (function (TrickleIcePolicy) {
            TrickleIcePolicy["NotSupported"] = "NotSupported";
            TrickleIcePolicy["FullTrickle"] = "FullTrickle";
            TrickleIcePolicy["HalfTrickle"] = "HalfTrickle";
        })(Connection.TrickleIcePolicy || (Connection.TrickleIcePolicy = {}));
        (function (IceGatheringState) {
            IceGatheringState["New"] = "new";
            IceGatheringState["Gathering"] = "gathering";
            IceGatheringState["Complete"] = "complete";
            IceGatheringState["Closing"] = "closing";
            IceGatheringState["Closed"] = "closed";
            IceGatheringState["Failed"] = "failed";
        })(Connection.IceGatheringState || (Connection.IceGatheringState = {}));
        (function (SignallingState) {
            SignallingState["New"] = "new";
            SignallingState["HaveLocalOffer"] = "haveLocalOffer";
            SignallingState["HaveRemoteOffer"] = "haveRemoteOffer";
            SignallingState["Stable"] = "stable";
        })(Connection.SignallingState || (Connection.SignallingState = {}));
    })(Connection || (Connection = {}));
    function rtcIceConnectionStateToConnectionState(state) {
        switch (state) {
            case "checking":
                return Connection.IceConnectionState.Checking;
            case "closed":
                return Connection.IceConnectionState.Closed;
            case "completed":
                return Connection.IceConnectionState.Completed;
            case "connected":
                return Connection.IceConnectionState.Connected;
            case "disconnected":
                return Connection.IceConnectionState.Disconnected;
            case "failed":
                return Connection.IceConnectionState.Failed;
            case "new":
                return Connection.IceConnectionState.New;
        }
    }
    function rtcIceGatheringStateToGatheringState(state) {
        switch (state) {
            case "new":
                return Connection.IceGatheringState.New;
            case "complete":
                return Connection.IceGatheringState.Complete;
            case "gathering":
                return Connection.IceGatheringState.Gathering;
        }
    }

    var LayoutFrame = (function () {
        function LayoutFrame(_x, _y, _width, _height) {
            if (_x === void 0) { _x = 0; }
            if (_y === void 0) { _y = 0; }
            if (_width === void 0) { _width = 0; }
            if (_height === void 0) { _height = 0; }
            this._x = _x;
            this._y = _y;
            this._width = _width;
            this._height = _height;
            this._orientation = 0;
        }
        Object.defineProperty(LayoutFrame.prototype, "height", {
            get: function () {
                return this._height;
            },
            set: function (value) {
                this._height = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutFrame.prototype, "orientation", {
            get: function () {
                return this._orientation;
            },
            set: function (value) {
                this._orientation = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutFrame.prototype, "width", {
            get: function () {
                return this._width;
            },
            set: function (value) {
                this._width = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutFrame.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (value) {
                this._x = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutFrame.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (value) {
                this._y = value;
            },
            enumerable: false,
            configurable: true
        });
        LayoutFrame.prototype.getScaledFrame = function (scale, outerWidth, outerHeight, innerWidth, innerHeight) {
            if (outerWidth === void 0) { outerWidth = 0; }
            if (outerHeight === void 0) { outerHeight = 0; }
            if (innerWidth === void 0) { innerWidth = 0; }
            if (innerHeight === void 0) { innerHeight = 0; }
            var x = 0, y = 0, width = outerWidth, height = outerHeight;
            if (outerWidth === 0 || outerHeight === 0 || innerWidth === 0 || innerHeight === 0) {
                if (outerWidth === 0 || innerWidth === 0) {
                    width = 0;
                    x = Math.floor(outerWidth / 2);
                }
                if (outerHeight === 0 || innerHeight === 0) {
                    height = 0;
                    y = Math.floor(outerHeight / 2);
                }
            }
            else {
                var num5, num6;
                if (scale === LayoutScale.Contain) {
                    num5 = outerWidth / outerHeight;
                    num6 = innerWidth / innerHeight;
                    if (num5 > num6) {
                        width = outerHeight * num6;
                        x = Math.floor((outerWidth - width) / 2);
                    }
                    else {
                        if (num5 < num6) {
                            height = outerWidth / num6;
                            y = Math.floor((outerHeight - height) / 2);
                        }
                    }
                }
                else {
                    if (scale === LayoutScale.Cover) {
                        num5 = outerWidth / outerHeight;
                        num6 = innerWidth / innerHeight;
                        if (num5 < num6) {
                            width = outerHeight * num6;
                            x = Math.floor((outerWidth - width) / 2);
                        }
                        else {
                            if (num5 > num6) {
                                height = outerWidth / num6;
                                y = Math.floor((outerHeight - height) / 2);
                            }
                        }
                    }
                }
            }
            return new LayoutFrame(x, y, width, height);
        };
        LayoutFrame.prototype.isEquivalent = function (layoutFrame) {
            return layoutFrame.x === this.x && layoutFrame.y === this.y && layoutFrame.width === this.width && layoutFrame.height === this.height;
        };
        return LayoutFrame;
    }());

    var Layout = (function () {
        function Layout(_width, _height, _localFrame, _remoteFrame) {
            if (_width === void 0) { _width = 0; }
            if (_height === void 0) { _height = 0; }
            if (_localFrame === void 0) { _localFrame = new LayoutFrame(0, 0, 0, 0); }
            if (_remoteFrame === void 0) { _remoteFrame = new LayoutFrame(0, 0, 0, 0); }
            this._width = _width;
            this._height = _height;
            this._localFrame = _localFrame;
            this._remoteFrame = _remoteFrame;
        }
        Object.defineProperty(Layout.prototype, "localFrame", {
            get: function () {
                return this._localFrame;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layout.prototype, "remoteFrame", {
            get: function () {
                return this._remoteFrame;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layout.prototype, "width", {
            get: function () {
                return this._width;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layout.prototype, "height", {
            get: function () {
                return this._height;
            },
            enumerable: false,
            configurable: true
        });
        Layout.prototype.swapFrames = function (frame1, frame2) {
            var x = frame1.x, y = frame1.y, width = frame1.width, height = frame1.height;
            frame1.x = frame2.x;
            frame1.y = frame2.y;
            frame1.width = frame2.width;
            frame1.height = frame2.height;
            frame2.x = x;
            frame2.y = y;
            frame2.width = width;
            frame2.height = height;
        };
        Layout.prototype.swapLocalFrame = function () {
            this.swapFrames(this._localFrame, this._remoteFrame);
        };
        return Layout;
    }());

    var LayoutTable = (function () {
        function LayoutTable(_columnCount, _rowCount, _cellWidth, _cellHeight) {
            if (_columnCount === void 0) { _columnCount = 0; }
            if (_rowCount === void 0) { _rowCount = 0; }
            if (_cellWidth === void 0) { _cellWidth = 0; }
            if (_cellHeight === void 0) { _cellHeight = 0; }
            this._columnCount = _columnCount;
            this._rowCount = _rowCount;
            this._cellWidth = _cellWidth;
            this._cellHeight = _cellHeight;
        }
        Object.defineProperty(LayoutTable.prototype, "cellHeight", {
            get: function () {
                return this._cellHeight;
            },
            set: function (value) {
                this._cellHeight = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutTable.prototype, "cellWidth", {
            get: function () {
                return this._cellWidth;
            },
            set: function (value) {
                this._cellWidth = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutTable.prototype, "columnCount", {
            get: function () {
                return this._columnCount;
            },
            set: function (value) {
                this._columnCount = value;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutTable.prototype, "rowCount", {
            get: function () {
                return this._rowCount;
            },
            set: function (value) {
                this._rowCount = value;
            },
            enumerable: false,
            configurable: true
        });
        return LayoutTable;
    }());

    var Size = (function () {
        function Size(width, height) {
            this.width = width;
            this.height = height;
        }
        return Size;
    }());

    var LayoutPreset = (function () {
        function LayoutPreset() {
            this._floatWidthPercent = 0;
            this._floatHeightPercent = 0;
            this._floatMarginXPercent = 0;
            this._floatMarginYPercent = 0;
            this._floatWidth = 0;
            this._floatHeight = 0;
            this._floatMarginX = 0;
            this._floatMarginY = 0;
            this._blockWidthPercent = 0;
            this._blockHeightPercent = 0;
            this._blockMarginXPercent = 0;
            this._blockMarginYPercent = 0;
            this._blockWidth = 0;
            this._blockHeight = 0;
            this._blockMarginX = 0;
            this._blockMarginY = 0;
            this._inlineMargin = 0;
            this._mode = LayoutMode.FloatLocal;
            this._direction = LayoutDirection.Horizontal;
            this._alignment = LayoutAlignment.BottomRight;
            this.calculateFillFrame = function (layoutWidth, layoutHeight) {
                return new LayoutFrame(0, 0, layoutWidth, layoutHeight);
            };
        }
        Object.defineProperty(LayoutPreset.prototype, "mode", {
            get: function () {
                return this._mode;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutPreset.prototype, "direction", {
            get: function () {
                return this._direction;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutPreset.prototype, "alignment", {
            get: function () {
                return this._alignment;
            },
            enumerable: false,
            configurable: true
        });
        LayoutPreset.calculateTable = function (tableWidth, tableHeight, count) {
            var num = 0, columnCount = 1, rowCount = 1;
            for (var i = count; i >= 1; i--) {
                var num5 = Math.ceil(count / i);
                var num6 = tableWidth / i;
                var num7 = tableHeight / num5;
                var num8 = num6 < num7 ? num6 : num7;
                if (num8 >= num) {
                    num = num8;
                    columnCount = i;
                    rowCount = num5;
                }
            }
            return new LayoutTable(columnCount, rowCount, Math.floor(tableWidth / columnCount), Math.floor(tableHeight / rowCount));
        };
        LayoutPreset.Facetime = function () {
            var preset = new LayoutPreset();
            preset._mode = LayoutMode.FloatLocal;
            preset._alignment = LayoutAlignment.BottomRight;
            preset._floatMarginX = 10;
            preset._floatMarginY = 10;
            preset._floatWidthPercent = 0.25;
            preset._floatHeightPercent = 0.25;
            preset._inlineMargin = 0;
            return preset;
        };
        LayoutPreset.prototype.applyPreset = function (preset) {
            this._mode = preset._mode;
            this._direction = preset._direction;
            this._alignment = preset._alignment;
            this._floatWidth = preset._floatWidth;
            this._floatHeight = preset._floatHeight;
            this._floatMarginX = preset._floatMarginX;
            this._floatMarginY = preset._floatMarginY;
            this._floatWidthPercent = preset._floatWidthPercent;
            this._floatHeightPercent = preset._floatHeightPercent;
            this._floatMarginXPercent = preset._floatMarginXPercent;
            this._floatMarginYPercent = preset._floatMarginYPercent;
            this._blockWidth = preset._blockWidth;
            this._blockHeight = preset._blockHeight;
            this._blockMarginX = preset._blockMarginX;
            this._blockMarginY = preset._blockMarginY;
            this._blockWidthPercent = preset._blockWidthPercent;
            this._blockHeightPercent = preset._blockHeightPercent;
            this._blockMarginXPercent = preset._blockMarginXPercent;
            this._blockMarginYPercent = preset._blockMarginYPercent;
            this._inlineMargin = preset._inlineMargin;
        };
        LayoutPreset.prototype.copyToPreset = function (preset) {
            preset._mode = this._mode;
            preset._direction = this._direction;
            preset._alignment = this._alignment;
            preset._floatWidth = this._floatWidth;
            preset._floatHeight = this._floatHeight;
            preset._floatMarginX = this._floatMarginX;
            preset._floatMarginY = this._floatMarginY;
            preset._floatWidthPercent = this._floatWidthPercent;
            preset._floatHeightPercent = this._floatHeightPercent;
            preset._floatMarginXPercent = this._floatMarginXPercent;
            preset._floatMarginYPercent = this._floatMarginYPercent;
            preset._blockWidth = this._blockWidth;
            preset._blockHeight = this._blockHeight;
            preset._blockMarginX = this._blockMarginX;
            preset._blockMarginY = this._blockMarginY;
            preset._blockWidthPercent = this._blockWidthPercent;
            preset._blockHeightPercent = this._blockHeightPercent;
            preset._blockMarginXPercent = this._blockMarginXPercent;
            preset._blockMarginYPercent = this._blockMarginYPercent;
            preset._inlineMargin = this._inlineMargin;
        };
        LayoutPreset.prototype.calculateLayout = function (layoutWidth, layoutHeight, local, remoteCount, origin, localVideoSize, remoteVideoSize) {
            if (layoutWidth < 0) {
                layoutWidth = 0;
            }
            if (layoutHeight < 0) {
                layoutHeight = 0;
            }
            var layout;
            switch (this._mode) {
                case LayoutMode.FloatLocal:
                    layout = this.FloatLocalLayout(layoutWidth, layoutHeight, local, remoteCount);
                    break;
                default:
                    throw new TLinkError("Unrecognized layout mode.");
            }
            LayoutPreset.transformFrame(layout.localFrame, origin, layoutWidth, layoutHeight);
            if (layout.remoteFrame) {
                LayoutPreset.transformFrame(layout.remoteFrame, origin, layoutWidth, layoutHeight);
            }
            return layout;
        };
        LayoutPreset.transformFrame = function (frame, origin, layoutWidth, layoutHeight) {
            var flag = false, flag2 = false;
            switch (origin) {
                case LayoutOrigin.TopRight:
                    flag = true;
                    break;
                case LayoutOrigin.BottomRight:
                    flag = true;
                    flag2 = true;
                    break;
                case LayoutOrigin.BottomLeft:
                    flag2 = true;
                    break;
            }
            if (flag) {
                frame.x = layoutWidth - frame.x - frame.width;
            }
            if (flag2) {
                frame.y = layoutHeight - frame.y - frame.height;
            }
        };
        LayoutPreset.prototype.calculateBlockFrame = function (layoutWidth, layoutHeight, marginX, marginY) {
            if (this._blockWidth === 0 && this._blockWidthPercent === 0) {
                this._blockWidthPercent = 0.25;
            }
            if (this._blockHeight === 0 && this._blockHeightPercent === 0) {
                this._blockHeightPercent = 0.25;
            }
            var width = this._blockWidth > 0 ? this._blockWidth : layoutWidth * this._blockWidthPercent, height = this._blockHeight > 0 ? this._blockHeight : layoutHeight * this._blockHeightPercent;
            this._blockMarginX > 0 ? this._blockMarginX : layoutWidth * this._blockMarginXPercent;
            this._blockMarginY > 0 ? this._blockMarginY : layoutHeight * this._blockMarginYPercent;
            var x = 0;
            if (this._alignment == LayoutAlignment.Top || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Bottom) {
                x = (layoutWidth - width) / 2;
            }
            else if (this._alignment == LayoutAlignment.TopRight || this._alignment == LayoutAlignment.Right || this._alignment == LayoutAlignment.BottomRight) {
                x = layoutWidth - width;
            }
            else {
                x = 0;
            }
            var y = 0;
            if (this._alignment == LayoutAlignment.Left || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Right) {
                y = (layoutHeight - height) / 2;
            }
            else if (this._alignment == LayoutAlignment.BottomLeft || this._alignment == LayoutAlignment.Bottom || this._alignment == LayoutAlignment.BottomRight) {
                y = layoutHeight - height;
            }
            else {
                y = 0;
            }
            return new LayoutFrame(x, y, width, height);
        };
        LayoutPreset.prototype.calculateFloatFrames = function (layoutWidth, layoutHeight, count) {
            if (this._floatWidth === 0 && this._floatWidthPercent === 0) {
                this._floatWidthPercent = 0.25;
            }
            if (this._floatHeight === 0 && this._floatHeightPercent === 0) {
                this._floatHeightPercent = 0.25;
            }
            var num = this._floatWidth > 0 ? this._floatWidth : layoutWidth * this._floatWidthPercent, num2 = this._floatHeight > 0 ? this._floatHeight : layoutHeight * this._floatHeightPercent, num3 = this._floatMarginX > 0 ? this._floatMarginX : layoutWidth * this._floatMarginXPercent, num4 = this._floatMarginY > 0 ? this._floatMarginY : layoutHeight * this._floatMarginYPercent;
            if (this._direction === LayoutDirection.Horizontal) {
                num = Math.min(layoutWidth, num * count);
            }
            else {
                num2 = Math.min(layoutHeight, num2 * count);
            }
            var frameArray = this.calculateInlineFrames(num, num2, count, 0, 0);
            do {
                if (this._alignment == LayoutAlignment.TopLeft || this._alignment == LayoutAlignment.Top || this._alignment == LayoutAlignment.TopRight) {
                    for (var _i = 0, frameArray_1 = frameArray; _i < frameArray_1.length; _i++) {
                        var frame = frameArray_1[_i];
                        frame.y += num4;
                    }
                    break;
                }
                else if (this._alignment == LayoutAlignment.Left || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Right) {
                    for (var _a = 0, frameArray_2 = frameArray; _a < frameArray_2.length; _a++) {
                        var frame = frameArray_2[_a];
                        frame.y += (layoutHeight - num2) / 2;
                    }
                    break;
                }
                else if (this._alignment == LayoutAlignment.BottomLeft || this._alignment == LayoutAlignment.Bottom || this._alignment == LayoutAlignment.BottomRight) {
                    for (var _b = 0, frameArray_3 = frameArray; _b < frameArray_3.length; _b++) {
                        var frame = frameArray_3[_b];
                        frame.y += layoutHeight - num2 - num4;
                    }
                    break;
                }
            } while (false);
            do {
                if (this._alignment == LayoutAlignment.TopLeft || this._alignment == LayoutAlignment.Left || this._alignment == LayoutAlignment.BottomLeft) {
                    for (var _c = 0, frameArray_4 = frameArray; _c < frameArray_4.length; _c++) {
                        var frame = frameArray_4[_c];
                        frame.x += num3;
                    }
                    return frameArray;
                }
                else if (this._alignment == LayoutAlignment.Top || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Bottom) {
                    for (var _d = 0, frameArray_5 = frameArray; _d < frameArray_5.length; _d++) {
                        var frame = frameArray_5[_d];
                        frame.x += (layoutWidth - num) / 2;
                    }
                    return frameArray;
                }
                else if (this._alignment == LayoutAlignment.TopRight || this._alignment == LayoutAlignment.Right || this._alignment == LayoutAlignment.BottomRight) {
                    for (var _e = 0, frameArray_6 = frameArray; _e < frameArray_6.length; _e++) {
                        var frame = frameArray_6[_e];
                        frame.x += layoutWidth - num - num3;
                    }
                    return frameArray;
                }
            } while (false);
            return frameArray;
        };
        LayoutPreset.SingleLayout = function (layoutWidth, layoutHeight, local) {
            return new Layout(0, 0, local ? new LayoutFrame(0, 0, layoutWidth, layoutHeight) : null);
        };
        LayoutPreset.prototype.FloatLocalLayout = function (layoutWidth, layoutHeight, local, remoteCount) {
            var _f, _g;
            if (remoteCount === 0) {
                return LayoutPreset.SingleLayout(layoutWidth, layoutHeight, local);
            }
            return new Layout(layoutWidth, layoutHeight, local ? (_f = this.calculateFloatFrames(layoutWidth, layoutHeight, 1)) === null || _f === void 0 ? void 0 : _f[0] : null, (_g = this.calculateInlineFrames(layoutWidth, layoutHeight, remoteCount, 0, 0)) === null || _g === void 0 ? void 0 : _g[0]);
        };
        LayoutPreset.prototype.calculateFloatFrame = function (layoutWidth, layoutHeight) {
            var count = 1;
            if (this._floatWidth === 0 && this._floatWidthPercent === 0) {
                this._floatWidthPercent = 0.25;
            }
            if (this._floatHeight === 0 && this._floatHeightPercent === 0) {
                this._floatHeightPercent = 0.25;
            }
            var num = this._floatWidth > 0 ? this._floatWidth : layoutWidth * this._floatWidthPercent;
            var num2 = this._floatHeight > 0 ? this._floatHeight : layoutHeight * this._floatHeightPercent;
            var num3 = this._floatMarginX > 0 ? this._floatMarginX : layoutWidth * this._floatMarginXPercent;
            var num4 = this._floatMarginY > 0 ? this._floatMarginY : layoutHeight * this._floatMarginYPercent;
            if (this._direction === LayoutDirection.Horizontal) {
                num = Math.min(layoutWidth, num * count);
            }
            else {
                num2 = Math.min(layoutHeight, num2 * count);
            }
            var frameArray = this.calculateInlineFrames(num, num2, count, 0, 0);
            do {
                if (this._alignment == LayoutAlignment.TopLeft || this._alignment == LayoutAlignment.Top || this._alignment == LayoutAlignment.TopRight) {
                    for (var _i = 0, frameArray_1 = frameArray; _i < frameArray_1.length; _i++) {
                        var frame = frameArray_1[_i];
                        frame.y += num4;
                    }
                    break;
                }
                else if (this._alignment == LayoutAlignment.Left || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Right) {
                    for (var _a = 0, frameArray_2 = frameArray; _a < frameArray_2.length; _a++) {
                        var frame = frameArray_2[_a];
                        frame.y += (layoutHeight - num2) / 2;
                    }
                    break;
                }
                else if (this._alignment == LayoutAlignment.BottomLeft || this._alignment == LayoutAlignment.Bottom || this._alignment == LayoutAlignment.BottomRight) {
                    for (var _b = 0, frameArray_3 = frameArray; _b < frameArray_3.length; _b++) {
                        var frame = frameArray_3[_b];
                        frame.y += layoutHeight - num2 - num4;
                    }
                    break;
                }
            } while (false);
            do {
                if (this._alignment == LayoutAlignment.TopLeft || this._alignment == LayoutAlignment.Left || this._alignment == LayoutAlignment.BottomLeft) {
                    for (var _c = 0, frameArray_4 = frameArray; _c < frameArray_4.length; _c++) {
                        var frame = frameArray_4[_c];
                        frame.x += num3;
                    }
                    return frameArray;
                }
                else if (this._alignment == LayoutAlignment.Top || this._alignment == LayoutAlignment.Center || this._alignment == LayoutAlignment.Bottom) {
                    for (var _d = 0, frameArray_5 = frameArray; _d < frameArray_5.length; _d++) {
                        var frame = frameArray_5[_d];
                        frame.x += (layoutWidth - num) / 2;
                    }
                    return frameArray;
                }
                else if (this._alignment == LayoutAlignment.TopRight || this._alignment == LayoutAlignment.Right || this._alignment == LayoutAlignment.BottomRight) {
                    for (var _e = 0, frameArray_6 = frameArray; _e < frameArray_6.length; _e++) {
                        var frame = frameArray_6[_e];
                        frame.x += layoutWidth - num - num3;
                    }
                    return frameArray;
                }
            } while (false);
            return frameArray;
        };
        LayoutPreset.prototype.calculateInlineFrame = function (cellX, cellY, cellWidth, cellHeight) {
            var num = this._inlineMargin / 2, x = cellX - num, y = cellY - num, width = cellWidth - this._inlineMargin;
            return new LayoutFrame(x, y, width, cellHeight - this._inlineMargin);
        };
        LayoutPreset.prototype.calculateInlineFrames = function (layoutWidth, layoutHeight, count, baseX, baseY) {
            var num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0, num12 = 0, num13 = 0, num14 = 0, num15 = 0, num16 = 0, num17 = 0, frame, list = [], table = LayoutPreset.calculateTable(layoutWidth + this._inlineMargin, layoutHeight + this._inlineMargin, count), columnCount = table.columnCount, rowCount = table.rowCount, cellWidth = table.cellWidth, cellHeight = table.cellHeight, num5 = this._inlineMargin / 2;
            if (this._direction === LayoutDirection.Horizontal) {
                num6 = 0;
                num7 = baseY + num5;
                num8 = layoutHeight - rowCount * cellHeight + this._inlineMargin;
                num9 = 0;
                while (num9 < rowCount) {
                    num10 = num9 < num8 ? 1 : 0;
                    var num11 = columnCount;
                    if (num9 === rowCount - 1) {
                        num11 = count - num6;
                    }
                    num12 = baseX + num5;
                    if (num9 === rowCount - 1 && rowCount > 1) {
                        num13 = num12 - num5;
                        num14 = num7 - num5;
                        list.push.apply(list, this.calculateInlineFrames(baseX + layoutWidth, baseY + layoutHeight - num14, num11, num13, num14));
                    }
                    else {
                        num15 = layoutWidth - num11 * cellWidth + this._inlineMargin;
                        num16 = 0;
                        while (num16 < num11) {
                            num17 = num16 < num15 ? 1 : 0;
                            frame = this.calculateInlineFrame(num12, num7, cellWidth + num17, cellHeight + num10);
                            list.push(frame);
                            num12 = num12 + (cellWidth + num17);
                            num16++;
                            num6++;
                        }
                    }
                    num7 = num7 + (cellHeight + num10);
                    num9++;
                }
            }
            else {
                num6 = 0;
                num12 = baseX + num5;
                num15 = layoutWidth - columnCount * cellWidth + this._inlineMargin;
                for (num16 = 0; num16 < columnCount; num16++) {
                    num17 = num16 < num15 ? 1 : 0;
                    var num18 = rowCount;
                    if (num16 === columnCount - 1) {
                        num18 = count - num6;
                    }
                    num7 = baseY + num5;
                    if (num16 === columnCount - 1 && columnCount > 1) {
                        num13 = num12 - num5;
                        num14 = num7 - num5;
                        list.push.apply(list, this.calculateInlineFrames(baseX + layoutWidth - num13, baseY + layoutHeight, num18, num13, num14));
                    }
                    else {
                        num8 = layoutHeight - num18 * cellHeight + this._inlineMargin;
                        num9 = 0;
                        while (num9 < num18) {
                            num10 = num9 < num8 ? 1 : 0;
                            frame = this.calculateInlineFrame(num12, num7, cellWidth + num17, cellHeight + num10);
                            list.push(frame);
                            num7 = num7 + (cellHeight + num10);
                            num9++;
                            num6++;
                        }
                    }
                    num12 = num12 + (cellWidth + num17);
                }
            }
            return list;
        };
        return LayoutPreset;
    }());
    var innerContainerClass = "data-tl-webrtc-inner-container";
    var LayoutManager = (function (_super) {
        __extends(LayoutManager, _super);
        function LayoutManager(container, _preset) {
            if (_preset === void 0) { _preset = LayoutPreset.Facetime(); }
            var _this = _super.call(this) || this;
            _this._preset = _preset;
            _this._id = uuidv4();
            _this._verticalScrollBarWidth = -1;
            _this._horizontalScrollBarHeight = -1;
            _this._layoutOrigin = LayoutOrigin.TopLeft;
            _this._parentMissing = 0;
            _this._parentMissingMax = 16;
            _this._lastWidth = 0;
            _this._lastHeight = 0;
            _this._container = container;
            return _this;
        }
        Object.defineProperty(LayoutManager.prototype, "id", {
            get: function () {
                return this._id;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "container", {
            get: function () {
                return this._container;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "innerContainer", {
            get: function () {
                return this._innerContainer;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "localMedia", {
            set: function (localMedia) {
                this._localMediaSink = localMedia === null || localMedia === void 0 ? void 0 : localMedia.sink;
                this.initializeInnerContainer();
                if (this._localMediaSink) {
                    this._innerContainer.append(this._localMediaSink.view);
                }
                this.layout();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "remoteMedia", {
            set: function (remoteMedia) {
                this._remoteMediaSink = remoteMedia === null || remoteMedia === void 0 ? void 0 : remoteMedia.sink;
                this.initializeInnerContainer();
                if (this._remoteMediaSink) {
                    this._innerContainer.append(this._remoteMediaSink.view);
                }
                this.layout();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "verticalScrollbarWidth", {
            get: function () {
                var _f;
                if (this._verticalScrollBarWidth == -1) {
                    var outer = document.createElement("div");
                    outer.style.visibility = "hidden";
                    outer.style.overflow = "scroll";
                    outer.style.msOverflowStyle = "scrollbar";
                    document.body.appendChild(outer);
                    var inner = document.createElement("div");
                    outer.appendChild(inner);
                    this._verticalScrollBarWidth = outer.offsetWidth - outer.clientWidth;
                    (_f = outer.parentNode) === null || _f === void 0 ? void 0 : _f.removeChild(outer);
                }
                return this._verticalScrollBarWidth;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutManager.prototype, "horizontalScrollbarHeight", {
            get: function () {
                var _f;
                if (this._horizontalScrollBarHeight == -1) {
                    var outer = document.createElement("div");
                    outer.style.visibility = "hidden";
                    outer.style.overflow = "scroll";
                    outer.style.msOverflowStyle = "scrollbar";
                    document.body.appendChild(outer);
                    var inner = document.createElement("div");
                    outer.appendChild(inner);
                    this._horizontalScrollBarHeight = outer.offsetHeight - outer.clientHeight;
                    (_f = outer.parentNode) === null || _f === void 0 ? void 0 : _f.removeChild(outer);
                }
                return this._horizontalScrollBarHeight;
            },
            enumerable: false,
            configurable: true
        });
        LayoutManager.prototype.dispose = function () {
            clearInterval(this._resizeInterval);
            this.destroyInnerContainer();
        };
        LayoutManager.prototype.initializeInnerContainer = function () {
            var _this = this;
            if (this._innerContainer) {
                return;
            }
            this.destroyInnerContainer();
            this._innerContainer = document.createElement("div");
            this._innerContainer.style.position = "relative";
            this._innerContainer.style.width = "100%";
            this._innerContainer.style.height = "100%";
            this._innerContainer.setAttribute(innerContainerClass, "true");
            this._container.appendChild(this._innerContainer);
            this._resizeInterval = window.setInterval(function () {
                if (!_this._container.parentNode) {
                    _this._parentMissing = _this._parentMissing + 1;
                    if (_this._parentMissing > _this._parentMissingMax) {
                        window.clearInterval(_this._resizeInterval);
                    }
                }
                else {
                    _this._parentMissing = 0;
                    var width = _this._innerContainer.offsetWidth;
                    var height = _this._innerContainer.offsetHeight;
                    if (width != _this._lastWidth || height != _this._lastHeight) {
                        _this.layout();
                        _this._lastWidth = width;
                        _this._lastHeight = height;
                    }
                }
            }, 250);
        };
        LayoutManager.prototype.destroyInnerContainer = function () {
            var collection = this._container.getElementsByTagName("div");
            for (var i = 0; i < collection.length; i++) {
                var child = collection[i];
                if (child.getAttribute(innerContainerClass) == "true") {
                    this._container.removeChild(child);
                }
            }
        };
        LayoutManager.prototype.getLayout = function (layoutWidth, layoutHeight, local, remoteCount, localVideoSize, remoteVideoSizes) {
            var p = this._preset.calculateLayout(layoutWidth, layoutHeight, local, remoteCount, this._layoutOrigin, localVideoSize, remoteVideoSizes);
            this.emit("layout", p);
            return p;
        };
        LayoutManager.prototype.layout = function (remoteViews, useMediaSink) {
            var _this = this;
            var _f, _g, _h;
            if (remoteViews === void 0) { remoteViews = []; }
            if (useMediaSink === void 0) { useMediaSink = true; }
            if (this._retryTimeout) {
                clearTimeout(this._retryTimeout);
            }
            var localView = (_f = this._localMediaSink) === null || _f === void 0 ? void 0 : _f.view;
            var remoteView = (_g = this._remoteMediaSink) === null || _g === void 0 ? void 0 : _g.view;
            var localVideoSize;
            var remoteVideoSizes = [];
            if (remoteView) {
                this._remoteMediaSink.once("videoStart", function () {
                    setTimeout(function () { return _this.layout([remoteView]); }, 100);
                });
                this._remoteMediaSink.on("videoStop", function () {
                    setTimeout(function () { return _this.layout([], false); }, 100);
                });
                if (!remoteViews.length && ((_h = this._remoteMediaSink) === null || _h === void 0 ? void 0 : _h.videoStarted) && useMediaSink) {
                    remoteViews.push(remoteView);
                }
            }
            var container = this._innerContainer || this._container;
            var containerWidth = container.offsetWidth;
            var containerHeight = container.offsetHeight;
            var layout = this.getLayout(containerWidth, containerHeight, (localView !== null && localView !== void 0 ? localView : null) != null, remoteViews.length, localVideoSize, remoteVideoSizes);
            var localFrame = layout.localFrame;
            if (localView && localFrame) {
                localView.style.position = "absolute";
                localView.style.left = localFrame.x + "px";
                localView.style.top = localFrame.y + "px";
                localView.style.width = localFrame.width + "px";
                localView.style.height = localFrame.height + "px";
                if (this._preset.mode === LayoutMode.FloatLocal) {
                    localView.style.zIndex = "1";
                }
            }
            var remoteFrame = layout.remoteFrame;
            if (remoteView && remoteFrame) {
                remoteView.style.position = "absolute";
                remoteView.style.left = remoteFrame.x + "px";
                remoteView.style.top = remoteFrame.y + "px";
                remoteView.style.width = remoteFrame.width + "px";
                remoteView.style.height = remoteFrame.height + "px";
                if (this._preset.mode == LayoutMode.FloatLocal) {
                    remoteView.style.zIndex = "0";
                }
            }
        };
        LayoutManager.prototype.getVideoSize = function (view) {
            if (view == null) {
                return null;
            }
            if (view.nodeName.toLowerCase() == "video") {
                var video = view, videoWidth = video.videoWidth, videoHeight = video.videoHeight;
                if (videoWidth && videoHeight) {
                    return new Size(videoWidth, videoHeight);
                }
            }
            var children = view.children;
            if (children) {
                for (var i = 0; i < children.length; i++) {
                    var videoSize = this.getVideoSize(children[i]);
                    if (videoSize != null) {
                        return videoSize;
                    }
                }
            }
            return null;
        };
        return LayoutManager;
    }(Emitter));

    const browser = detect();
    const isChomeMajorThan72 = browser && browser.name === "chrome" && parseInt((browser.version || "72.0").split(".")[0]) > 72;
    function phoneCallCanSwitchToVideoCall() {
        return (browser && browser.name !== "chrome") || !isChomeMajorThan72;
    }
    class ChannelEvent {
        constructor(channel, callInfo, generatedBy) {
            this.channel = channel;
            this.callInfo = callInfo;
            this.generatedBy = generatedBy;
        }
        isGeneratedByServer() {
            return this.generatedBy === "server";
        }
        isGeneratedByClient() {
            return this.generatedBy === "client";
        }
    }
    function buildWebrtcControlMessageFromChannelEvent(channelEvent, override) {
        return Object.assign(Object.assign({ _isFromServer: channelEvent.isGeneratedByServer(), _channelType: channelEvent.channel, _realChannelType: channelEvent.channel }, (override !== null && override !== void 0 ? override : {})), channelEvent.callInfo);
    }
    function buildCallInfoFromWebrtcControlMessage(webrtcControlMessage) {
        var _a;
        const result = Object.assign({}, webrtcControlMessage);
        if (webrtcControlMessage._realChannelType) {
            result.channelid = (_a = channelTypeToId(webrtcControlMessage._realChannelType)) !== null && _a !== void 0 ? _a : undefined;
        }
        result.deviceType = ExtenType.WEBRTC;
        delete result._isFromServer;
        delete result._channelType;
        delete result._realChannelType;
        return result;
    }
    function adjustCallInfoWithMediaInfo(data, webrtcManager) {
        var _a, _b, _c, _d;
        const callInfo = data.callInfo;
        if (callInfo && callInfo.deviceType === ExtenType.WEBRTC && webrtcManager) {
            if (!callInfo.remote_media_status) {
                callInfo.remote_media_status = callInfo.media || null;
            }
            if (!callInfo.media_feature) {
                callInfo.media_feature = {};
                if (callInfo.local_media_features) {
                    if (!phoneCallCanSwitchToVideoCall() && callInfo.local_media_features.video && callInfo.state !== CallState.NEW_INBOUND && callInfo.state !== CallState.NEW_OUTBOUND) {
                        let indexOfVideoStartStop = callInfo.local_media_features.video.indexOf(CallMediaFeature.START);
                        if (indexOfVideoStartStop === -1) {
                            indexOfVideoStartStop = callInfo.local_media_features.video.indexOf(CallMediaFeature.STOP);
                        }
                        if (indexOfVideoStartStop > -1) {
                            callInfo.local_media_features.video.splice(indexOfVideoStartStop, 1);
                            if (callInfo.local_media_features.video.length === 0) {
                                delete callInfo.local_media_features.video;
                            }
                        }
                    }
                    callInfo.media_feature.local = callInfo.local_media_features;
                }
                else if (data.channel === ChannelType.Video && webrtcManager) {
                    callInfo.media_feature.local = null;
                    switch (callInfo.state) {
                        case CallState.NEW_INBOUND:
                            if (!callInfo.remote_media_status) {
                                callInfo.remote_media_status = { audio: [CallMediaLinkStatus.UNMUTE], video: [CallMediaLinkStatus.UNMUTE] };
                            }
                            callInfo.media_feature.local = {};
                            if (webrtcManager.device.callMediaNotified.audio) {
                                callInfo.media_feature.local.audio = [CallMediaFeature.START];
                            }
                            if (webrtcManager.device.callMediaNotified.video) {
                                callInfo.media_feature.local.video = [CallMediaFeature.START];
                            }
                            break;
                        case CallState.CONNECTED:
                            const call = webrtcManager.retriveCall((_a = callInfo.callId) !== null && _a !== void 0 ? _a : "");
                            if (call) {
                                if (!callInfo.remote_media_status) {
                                    callInfo.remote_media_status = {};
                                    const remoteAudioStatus = call.remoteMedia.audioLinkStatus;
                                    if (remoteAudioStatus) {
                                        callInfo.remote_media_status.audio = [remoteAudioStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE];
                                    }
                                    const remoteVideoStatus = call.remoteMedia.videoLinkStatus;
                                    if (remoteVideoStatus) {
                                        callInfo.remote_media_status.video = [remoteVideoStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE];
                                    }
                                }
                                callInfo.media_feature.local = {};
                                if (webrtcManager.device.callMediaNotified.audio) {
                                    callInfo.media_feature.local.audio = [];
                                    const status = (_b = call.localMedia) === null || _b === void 0 ? void 0 : _b.audioLinkStatus;
                                    if (status) {
                                        callInfo.media_feature.local.audio.push(status === WebRtcMedia.LinkStatus.MUTE ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE);
                                    }
                                    else {
                                        callInfo.media_feature.local.audio.push(CallMediaFeature.START);
                                    }
                                }
                                if (webrtcManager.device.callMediaNotified.video) {
                                    callInfo.media_feature.local.video = [];
                                    const status = (_c = call.localMedia) === null || _c === void 0 ? void 0 : _c.videoLinkStatus;
                                    if (status) {
                                        callInfo.media_feature.local.video.push(status === WebRtcMedia.LinkStatus.MUTE ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE);
                                    }
                                    else {
                                        callInfo.media_feature.local.video.push(CallMediaFeature.START);
                                    }
                                }
                            }
                            break;
                    }
                    if (callInfo.media_feature.local) {
                        callInfo.local_media_features = callInfo.media_feature.local;
                    }
                    if (!callInfo.media && callInfo.remote_media_status) {
                        callInfo.media = callInfo.remote_media_status;
                    }
                }
            }
            if (!callInfo.media_feature.remote) {
                callInfo.media_feature.remote = {};
                if (callInfo.remote_media_status && (callInfo.remote_media_status.audio || callInfo.remote_media_status.video) && webrtcManager) {
                    const call = webrtcManager.retriveCall((_d = callInfo.callId) !== null && _d !== void 0 ? _d : "");
                    if (callInfo.remote_media_status.audio) {
                        callInfo.media_feature.remote.audio = [call ? (call.remoteMedia.audioLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE) : callInfo.remote_media_status.audio.indexOf(CallMediaLinkStatus.MUTE) > -1 ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE];
                    }
                    if (callInfo.remote_media_status.video) {
                        callInfo.media_feature.remote.video = [call ? (call.remoteMedia.videoLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE) : callInfo.remote_media_status.video.indexOf(CallMediaLinkStatus.MUTE) > -1 ? CallMediaFeature.UNMUTE : CallMediaFeature.MUTE];
                    }
                }
            }
        }
        return data;
    }
    var LoginType;
    (function (LoginType) {
        LoginType[LoginType["Credential"] = 0] = "Credential";
        LoginType[LoginType["AccessToken"] = 1] = "AccessToken";
        LoginType[LoginType["Custom"] = 2] = "Custom";
        LoginType[LoginType["JwtToken"] = 3] = "JwtToken";
    })(LoginType || (LoginType = {}));

    const { version } = { "version": "26.0.0" };
    const LIB_VERSION$1 = version;

    var parse_1 = parse;
    var serialize_1 = serialize;
    var __toString = Object.prototype.toString;
    var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
    function parse(str, options) {
      if (typeof str !== 'string') {
        throw new TypeError('argument str must be a string');
      }
      var obj = {};
      var opt = options || {};
      var dec = opt.decode || decode;
      var index = 0;
      while (index < str.length) {
        var eqIdx = str.indexOf('=', index);
        if (eqIdx === -1) {
          break
        }
        var endIdx = str.indexOf(';', index);
        if (endIdx === -1) {
          endIdx = str.length;
        } else if (endIdx < eqIdx) {
          index = str.lastIndexOf(';', eqIdx - 1) + 1;
          continue
        }
        var key = str.slice(index, eqIdx).trim();
        if (undefined === obj[key]) {
          var val = str.slice(eqIdx + 1, endIdx).trim();
          if (val.charCodeAt(0) === 0x22) {
            val = val.slice(1, -1);
          }
          obj[key] = tryDecode(val, dec);
        }
        index = endIdx + 1;
      }
      return obj;
    }
    function serialize(name, val, options) {
      var opt = options || {};
      var enc = opt.encode || encode$1;
      if (typeof enc !== 'function') {
        throw new TypeError('option encode is invalid');
      }
      if (!fieldContentRegExp.test(name)) {
        throw new TypeError('argument name is invalid');
      }
      var value = enc(val);
      if (value && !fieldContentRegExp.test(value)) {
        throw new TypeError('argument val is invalid');
      }
      var str = name + '=' + value;
      if (null != opt.maxAge) {
        var maxAge = opt.maxAge - 0;
        if (isNaN(maxAge) || !isFinite(maxAge)) {
          throw new TypeError('option maxAge is invalid')
        }
        str += '; Max-Age=' + Math.floor(maxAge);
      }
      if (opt.domain) {
        if (!fieldContentRegExp.test(opt.domain)) {
          throw new TypeError('option domain is invalid');
        }
        str += '; Domain=' + opt.domain;
      }
      if (opt.path) {
        if (!fieldContentRegExp.test(opt.path)) {
          throw new TypeError('option path is invalid');
        }
        str += '; Path=' + opt.path;
      }
      if (opt.expires) {
        var expires = opt.expires;
        if (!isDate(expires) || isNaN(expires.valueOf())) {
          throw new TypeError('option expires is invalid');
        }
        str += '; Expires=' + expires.toUTCString();
      }
      if (opt.httpOnly) {
        str += '; HttpOnly';
      }
      if (opt.secure) {
        str += '; Secure';
      }
      if (opt.priority) {
        var priority = typeof opt.priority === 'string'
          ? opt.priority.toLowerCase()
          : opt.priority;
        switch (priority) {
          case 'low':
            str += '; Priority=Low';
            break
          case 'medium':
            str += '; Priority=Medium';
            break
          case 'high':
            str += '; Priority=High';
            break
          default:
            throw new TypeError('option priority is invalid')
        }
      }
      if (opt.sameSite) {
        var sameSite = typeof opt.sameSite === 'string'
          ? opt.sameSite.toLowerCase() : opt.sameSite;
        switch (sameSite) {
          case true:
            str += '; SameSite=Strict';
            break;
          case 'lax':
            str += '; SameSite=Lax';
            break;
          case 'strict':
            str += '; SameSite=Strict';
            break;
          case 'none':
            str += '; SameSite=None';
            break;
          default:
            throw new TypeError('option sameSite is invalid');
        }
      }
      return str;
    }
    function decode (str) {
      return str.indexOf('%') !== -1
        ? decodeURIComponent(str)
        : str
    }
    function encode$1 (val) {
      return encodeURIComponent(val)
    }
    function isDate (val) {
      return __toString.call(val) === '[object Date]' ||
        val instanceof Date
    }
    function tryDecode(str, decode) {
      try {
        return decode(str);
      } catch (e) {
        return str;
      }
    }

    function exceptionInitializer$1(exception, availableError) {
        return exceptionInstantiator(exception && exception.exceptionName ? exception.exceptionName.replace("com.telenia.webapi.tvox.webclient.exception.", "").replace("com.telenia.webapi.exception.", "").replace("telenia.tvox.webapi.services.exceptions.", "").replace("Exception", "") : null, exception, availableError);
    }
    function exceptionInstantiator(exceptionName, exception, availableError) {
        if (exception instanceof Error) {
            return exception;
        }
        else if (exceptionName && availableError && availableError[exceptionName]) {
            if (exception && exception instanceof availableError[exceptionName]) {
                return exception;
            }
            else {
                return new availableError[exceptionName](exception);
            }
        }
        else {
            if (exception && exception instanceof WebAPI) {
                return exception;
            }
            else {
                return new WebAPI(exception);
            }
        }
    }

    class RequestOptions {
        constructor() {
            this._blockRequestOnReconnect = null;
        }
        _extend(options) {
            var _a, _b;
            if (options) {
                this._timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this._timeout;
                this._blockRequestOnReconnect = (_b = options.blockRequestOnReconnect) !== null && _b !== void 0 ? _b : this._blockRequestOnReconnect;
            }
        }
        get timeout() {
            var _a;
            return (_a = this._timeout) !== null && _a !== void 0 ? _a : undefined;
        }
        set timeout(timeout) {
            if ((timeout !== null && timeout !== void 0 ? timeout : null) !== null && timeout > 0) {
                this._timeout = timeout;
            }
            else {
                throw new Error("requestTimeout must be greater than 0");
            }
        }
        get blockRequestOnReconnect() {
            var _a;
            return (_a = this._blockRequestOnReconnect) !== null && _a !== void 0 ? _a : null;
        }
        set blockRequestOnReconnect(blockRequestOnReconnect) {
            this._blockRequestOnReconnect = !!(blockRequestOnReconnect !== null && blockRequestOnReconnect !== void 0 ? blockRequestOnReconnect : false);
        }
        get priorityOnRestart() {
            var _a;
            return (_a = this._priorityOnRestart) !== null && _a !== void 0 ? _a : 0;
        }
        set priorityOnRestart(priorityOnRestart) {
            this._priorityOnRestart = priorityOnRestart;
        }
    }
    class ResponseWrap {
        constructor(request) {
            this.request = request;
        }
        observable(client) {
            return this.executeRequest(client).response;
        }
        observableUpdate(client) {
            return this.executeRequest(client);
        }
        promiseUpdate(client) {
            const request = this.observableUpdate(client);
            return {
                response: request.response,
                toLiveResult: () => new LiveResultPromiseWrapper(request.toLiveResult()),
            };
        }
        executeRequest(client) {
            if (client) {
                return client.methods._buildResponse(this.request);
            }
            else {
                throw new Error("Unable to execute request, client is required");
            }
        }
    }
    function entityErrorResolver(err) {
        return err;
    }
    class Request {
        constructor(_method, _parameters, errorResolver) {
            this._method = _method;
            this._parameters = _parameters;
            this.errorResolver = errorResolver;
            this._options = new RequestOptions();
            this._response = new ResponseWrap(this);
        }
        get response() {
            return this._response;
        }
        get method() {
            return this._method;
        }
        get parameters() {
            return this._parameters;
        }
        get options() {
            return this._options;
        }
        withParameters(...parameters) {
            this._parameters.length = 0;
            if (parameters && parameters.length) {
                this._parameters.push.apply(this._parameters, parameters);
            }
            return this;
        }
        withOptions(options) {
            this._options._extend(options);
            return this;
        }
        withOptionsFromRequest(request) {
            if (request) {
                this._options = request.options;
            }
            return this;
        }
        withTimeout(timeout) {
            const timeoutValue = timeout !== null && timeout !== void 0 ? timeout : null;
            if (timeoutValue !== null) {
                this._options.timeout = timeoutValue;
            }
            return this;
        }
        withBlockRequestOnReconnect(blockRequestOnReconnect) {
            this._options.blockRequestOnReconnect = blockRequestOnReconnect !== null && blockRequestOnReconnect !== void 0 ? blockRequestOnReconnect : null;
            return this;
        }
        withPriorityOnRestart(priorityOnRestart) {
            this._options.priorityOnRestart = priorityOnRestart !== null && priorityOnRestart !== void 0 ? priorityOnRestart : null;
            return this;
        }
    }
    class RequestPromise extends Request {
        execute(client, requestTimeout) {
            return this.doExecute(client, requestTimeout);
        }
        doExecute(client, requestTimeout) {
            return this.withTimeout(requestTimeout).response.observable(client);
        }
    }
    class RequestChunked extends Request {
        execute(client, requestTimeout) {
            return this.doExecute(client, requestTimeout);
        }
        doExecute(client, requestTimeout) {
            return this.withTimeout(requestTimeout).response.observable(client);
        }
    }
    class RequestPromiseUpdate extends Request {
        execute(client, requestTimeout) {
            return this.doExecute(client, requestTimeout);
        }
        doExecute(client, requestTimeout) {
            return this.withTimeout(requestTimeout).response.promiseUpdate(client);
        }
    }
    class RequestChunkedUpdate extends Request {
        execute(client, requestTimeout) {
            return this.doExecute(client, requestTimeout);
        }
        doExecute(client, requestTimeout) {
            return this.withTimeout(requestTimeout).response.observableUpdate(client);
        }
    }

    class WebRTCFieldSession {
        constructor(answer, session) {
            this.answer = answer;
            this.session = session;
        }
        static fromObject(data) {
            if (data) {
                let sessionDescription = null, answer = false;
                if (data.session) {
                    try {
                        sessionDescription = SessionDescription.fromJson(data.session);
                        answer = sessionDescription.getType() === SessionDescription.Type.Answer;
                    }
                    catch (e) { }
                }
                return new WebRTCFieldSession(answer, sessionDescription);
            }
            else {
                return null;
            }
        }
        toObject() {
            return this.session ? { session: this.session.toJson() } : null;
        }
        isAnswer() {
            return this.answer;
        }
    }
    class WebRTCFieldCandidate {
        constructor(candidate, last) {
            this.candidate = candidate;
            this.last = last;
        }
        static fromObject(data) {
            var _a;
            if (data) {
                let candidate = null;
                if (data.candidate && data.candidate.length > 0) {
                    candidate = [];
                    for (let i = 0; i < data.candidate.length; i++) {
                        if (data.candidate[i]) {
                            try {
                                candidate.push(Candidate.fromJson(data.candidate[i]));
                            }
                            catch (e) { }
                        }
                    }
                }
                return new WebRTCFieldCandidate(candidate, (_a = data.last) !== null && _a !== void 0 ? _a : false);
            }
            else {
                return null;
            }
        }
        toObject() {
            var _a;
            const result = { last: (_a = this.last) !== null && _a !== void 0 ? _a : false };
            if (this.candidate && this.candidate.length) {
                result.candidate = this.candidate.map((candidate) => candidate.toJson());
            }
            return result;
        }
    }
    class WebRTCFieldAutoanswer {
        constructor(after, media) {
            this.after = after;
            this.media = media;
            if (isNaN(after)) {
                this.after = null;
            }
            if (!media || Object.keys(media).length == 0) {
                this.media = null;
            }
        }
        static fromObject(data) {
            var _a;
            if (data) {
                let media = null;
                if (data.media && data.media.length) {
                    media = new MediaParamImpl();
                    data.media.forEach((e) => (media[e] = true));
                }
                let result = new WebRTCFieldAutoanswer((_a = data.after) !== null && _a !== void 0 ? _a : null, media);
                if (result.after == null && result.media == null) {
                    return null;
                }
                else {
                    return result;
                }
            }
            else {
                return null;
            }
        }
        toObject() {
            if (this.after == null && this.media == null) {
                return null;
            }
            else {
                let result = {};
                if (this.after !== null) {
                    result.after = this.after;
                }
                if (this.media) {
                    result.media = MediaParam.toCallMedia(this.media);
                }
                return result;
            }
        }
    }
    class WebRTCField {
        constructor(clientid, sessionDescription, candidate, autoanswer, ring) {
            this.clientid = clientid;
            this.sessionDescription = sessionDescription;
            this.candidate = candidate;
            this.autoanswer = autoanswer;
            this.ring = ring;
        }
        static fromObject(data) {
            if (data) {
                let result = new WebRTCField(data.clientId ? data.clientId : null, data.sessionDescription ? WebRTCFieldSession.fromObject(data.sessionDescription) : null, data.candidate ? WebRTCFieldCandidate.fromObject(data.candidate) : null, data.autoanswer ? WebRTCFieldAutoanswer.fromObject(data.autoanswer) : null, data.ring === true || data.ring === false ? data.ring : null);
                return result;
            }
            else {
                return null;
            }
        }
        toObject() {
            var _a, _b;
            let webrtcFields = {};
            if (this.clientid) {
                webrtcFields.clientId = this.clientid;
            }
            if (this.sessionDescription) {
                webrtcFields.sessionDescription = (_a = this.sessionDescription.toObject()) !== null && _a !== void 0 ? _a : undefined;
            }
            if (this.candidate) {
                webrtcFields.candidate = this.candidate.toObject();
            }
            if (this.autoanswer) {
                webrtcFields.autoanswer = (_b = this.autoanswer.toObject()) !== null && _b !== void 0 ? _b : undefined;
            }
            if (this.ring !== null) {
                webrtcFields.ring = this.ring;
            }
            return webrtcFields;
        }
    }

    class WebRTCMediaField {
        constructor(config, prefix) {
            this.loop = false;
            this.volume = 100;
            if (!config)
                return;
            loadConfig(prefix, WebRTCMediaField.CHECK_OPTIONS, this, config);
        }
        static newInstance(config, prefix) {
            const value = objectCheck(config);
            return value ? new WebRTCMediaField(value, prefix) : value;
        }
    }
    WebRTCMediaField.CHECK_OPTIONS = {
        mandatory: {
            src: stringCheck,
        },
        optional: {
            loop: booleanCheck,
            volume: (volume) => {
                const value = numberCheck(volume);
                if (value == undefined)
                    return value;
                if (value < 0 || value > 100) {
                    throw new Error("Value is outside range 0÷100");
                }
                else {
                    return value;
                }
            },
            maxlength: numberCheck,
            interval: numberCheck,
            startDelay: numberCheck,
        },
    };

    const defaultPhoneSignal = {
        ring: {
            src: "data:video/webm;base64, ",
            loop: true,
            interval: 500,
        },
        ringback: {
            src: "data:video/webm;base64, ",
            loop: true,
            interval: 3700,
        },
        ringAdvertising: {
            src: "data:video/webm;base64, ",
            volume: 15,
            loop: true,
            interval: 3000,
        },
        busy: {
            src: "data:video/webm;base64, ",
            loop: true,
            maxlength: 3000,
        },
        congestion: {
            src: "data:video/webm;base64, ",
            loop: true,
            maxlength: 3000,
        },
    };

    class WebRTCMediaAudioSignal {
        constructor(config, prefix) {
            this.ring = new WebRTCMediaField(defaultPhoneSignal.ring);
            this.ringback = new WebRTCMediaField(defaultPhoneSignal.ringback);
            this.ringAdvertising = new WebRTCMediaField(defaultPhoneSignal.ringAdvertising);
            this.busy = new WebRTCMediaField(defaultPhoneSignal.busy);
            this.congestion = new WebRTCMediaField(defaultPhoneSignal.congestion);
            if (!config)
                return;
            for (let tone in config) {
                if (!this.hasOwnProperty(tone)) {
                    throw ConfigurationError.newInstance(arrayConcat(prefix).join("."), config[tone], new Error(`${tone} is not valid media audio signal`));
                }
            }
            loadConfig(prefix, WebRTCMediaAudioSignal.CHECK_OPTIONS, this, config);
        }
    }
    WebRTCMediaAudioSignal.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            ring: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["ring"])),
            ringback: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["ringback"])),
            ringAdvertising: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["ringAdvertising"])),
            dialtone: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["dialtone"])),
            busy: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["busy"])),
            congestion: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["congestion"])),
            hold: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["hold"])),
            dtmf: (source, prefix) => {
                const value = objectCheck(source);
                return value ? new WebRTCDtmfMediaField(value, arrayConcat(prefix, ["dtmf"])) : value;
            },
        },
    };
    class WebRTCDtmfMediaField {
        constructor(config, prefix) {
            if (!config)
                return;
            for (let dtmf in config) {
                if (!this.hasOwnProperty(dtmf)) {
                    throw ConfigurationError.newInstance(arrayConcat(prefix).join("."), config[dtmf], new Error(`${dtmf} is not valid dtmf`));
                }
            }
            loadConfig(prefix, WebRTCDtmfMediaField.CHECK_OPTIONS, this, config);
        }
    }
    WebRTCDtmfMediaField.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            "0": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["0"])),
            "1": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["1"])),
            "2": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["2"])),
            "3": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["3"])),
            "4": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["4"])),
            "5": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["5"])),
            "6": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["6"])),
            "7": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["7"])),
            "8": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["8"])),
            "9": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["9"])),
            "*": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["*"])),
            "#": (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["#"])),
            A: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["A"])),
            B: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["B"])),
            C: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["C"])),
            D: (source, prefix) => WebRTCMediaField.newInstance(source, arrayConcat(prefix, ["D"])),
        },
    };
    var MediaSignal;
    (function (MediaSignal) {
        MediaSignal["ring"] = "ring";
        MediaSignal["ringback"] = "ringback";
        MediaSignal["ringAdvertising"] = "ringAdvertising";
        MediaSignal["dialtone"] = "dialtone";
        MediaSignal["busy"] = "busy";
        MediaSignal["congestion"] = "congestion";
        MediaSignal["hold"] = "hold";
    })(MediaSignal || (MediaSignal = {}));

    class WebRTCMediaSignal {
        constructor(options, prefix) {
            this.audioenabled = true;
            this.volume = 100;
            this.audio = new WebRTCMediaAudioSignal();
            this.dtmfDuration = 120;
            this.dtmfInterToneGap = 120;
            if (!options)
                return;
            loadConfig(prefix, WebRTCMediaSignal.CHECK_OPTIONS, this, options);
        }
    }
    WebRTCMediaSignal.CHECK_OPTIONS = {
        mandatory: {
            audioenabled: booleanCheck,
        },
        optional: {
            volume: (volume) => {
                let value = numberCheck(volume);
                if (value == undefined)
                    return value;
                if (value < 0 || value > 100) {
                    throw new Error("Value is outside range 0÷100");
                }
                else {
                    return value;
                }
            },
            dtmfDuration: (volume) => {
                let value = numberCheck(volume);
                if (value == undefined)
                    return value;
                if (value < 40 || value > 2000) {
                    throw new Error("Value is outside range 0÷2000");
                }
                else {
                    return value;
                }
            },
            dtmfInterToneGap: (volume) => {
                let value = numberCheck(volume);
                if (value == undefined)
                    return value;
                if (value < 40 || value > 2000) {
                    throw new Error("Value is outside range 0÷2000");
                }
                else {
                    return value;
                }
            },
            audio: (audio, prefix) => {
                const value = objectCheck(audio);
                return value ? new WebRTCMediaAudioSignal(value, arrayConcat(prefix, ["audio"])) : value;
            },
        },
    };

    var featurelog = Log$1.of("webrtc:phonesignal:feature");
    var audioContextInstance = null;
    const dtmfValidator = /^[0-9#\*abcdABCD]+$/;
    const dtmfFrequency = new Map([
        ["1", [697, 1209]],
        ["2", [697, 1336]],
        ["3", [697, 1477]],
        ["A", [697, 1633]],
        ["4", [770, 1209]],
        ["5", [770, 1336]],
        ["6", [770, 1477]],
        ["B", [770, 1633]],
        ["7", [852, 1209]],
        ["8", [852, 1336]],
        ["9", [852, 1477]],
        ["C", [852, 1633]],
        ["*", [941, 1209]],
        ["0", [941, 1336]],
        ["#", [941, 1477]],
        ["D", [941, 1633]],
    ]);
    const DefaultOptions = new WebRTCMediaSignal();
    const SIGNAL_TEST_CALLID = "";
    class PhoneSignalManager {
        constructor(
        webrtcManager) {
            this.webrtcManager = webrtcManager;
            this.testerMediaSignal = null;
            this.log = Log$1.of("webrtc:phonesignal", webrtcManager.client);
            this.callMediaSignal = new CallMediaSignalPlayerStore(this);
            if (webrtcManager.options.mediaSignal) {
                this.setConfig(webrtcManager.options.mediaSignal, false);
            }
        }
        get webrtc() {
            return this.webrtcManager;
        }
        get audioContext() {
            if (audioContextInstance == null) {
                audioContextInstance = newAudioContext();
            }
            return audioContextInstance;
        }
        get config() {
            return this.signalOptions;
        }
        setConfig(options, resetDefault) {
            if (objectCheck(options)) {
                const mediaSignal = Object.assign({}, options);
                if (!mediaSignal.hasOwnProperty("audioenabled")) {
                    mediaSignal.audioenabled = resetDefault ? DefaultOptions.audioenabled : this.signalOptions.audioenabled;
                }
                if (!mediaSignal.hasOwnProperty("volume")) {
                    mediaSignal.volume = resetDefault ? DefaultOptions.volume : this.signalOptions.volume;
                }
                this.signalOptions = mediaSignal;
                if (mediaSignal.hasOwnProperty("audio")) {
                    this.setAudioSignalConfig(options.audio, resetDefault);
                }
                else {
                    if (resetDefault) {
                        mediaSignal.audio = Object.assign({}, DefaultOptions.audio);
                        this.callMediaSignal.reloadConfig();
                    }
                }
            }
        }
        setAudioSignalConfig(options, resetDefault) {
            const configOptions = loadConfig(undefined, WebRTCMediaAudioSignal.CHECK_OPTIONS, {}, options);
            for (var key in configOptions) {
                if (resetDefault) {
                    this.signalOptions.audio[key] = Object.assign({}, DefaultOptions.audio[key]);
                }
                else {
                    this.signalOptions.audio[key] = WebRTCMediaField.newInstance(configOptions[key], [key]);
                }
                if (this.signalOptions.audio[key] && this.signalOptions.audio[key].hasOwnProperty("volume")) {
                    this.changeVolume(this.signalOptions.audio[key].volume, MediaSignal[key]);
                }
            }
            this.callMediaSignal.reloadConfig();
            if (this.testerMediaSignal) {
                this.testerMediaSignal.stop(true);
                this.testerMediaSignal = null;
            }
        }
        getCurrentPlay(callId) {
            return this.callMediaSignal.getCurrentPlay(callId);
        }
        playDTMF(callId, dtmf, duration, interToneGap) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.webrtcManager.retriveCall(callId);
                if (call && call.toneSignalEnabled) {
                    yield this.callMediaSignal.playDTMF(callId, dtmf, duration || this.signalOptions.dtmfDuration, interToneGap || this.signalOptions.dtmfInterToneGap);
                }
            });
        }
        play(callId, mediaSignal) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.callMediaSignal.getCurrentPlay(callId) != mediaSignal) {
                    const call = this.webrtcManager.retriveCall(callId);
                    if (call && call.toneSignalEnabled) {
                        return this.callMediaSignal.play(callId, mediaSignal);
                    }
                    else {
                        return;
                    }
                }
                else {
                    return;
                }
            });
        }
        stop(callId, force) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.callMediaSignal.getCurrentPlay(callId)) {
                    this.callMediaSignal.stop(callId, force);
                    this.callMediaSignal.delete(callId);
                    const call = this.webrtcManager.retriveCall(callId);
                    if (call && call.toneSignalEnabled) {
                        if (call.signalingState == CallState.NEW_OUTBOUND || call.signalingState == CallState.CONNECTED) {
                            this.log.debug(`stopSingleInstancePlayerIfNeedle - ${MediaSignal.dialtone} - ${callId}`);
                            this.callMediaSignal.stopSingleInstancePlayerIfNeedle(MediaSignal.dialtone);
                        }
                        if (call.signalingState == CallState.NEW_INBOUND || call.signalingState == CallState.CONNECTED) {
                            this.log.debug(`stopSingleInstancePlayerIfNeedle - ${MediaSignal.ring} - ${callId}`);
                            this.callMediaSignal.stopSingleInstancePlayerIfNeedle(MediaSignal.ring);
                            this.log.debug(`stopSingleInstancePlayerIfNeedle - ${MediaSignal.ringAdvertising} - ${callId}`);
                            this.callMediaSignal.stopSingleInstancePlayerIfNeedle(MediaSignal.ringAdvertising);
                        }
                        if (this.callMediaSignal.size() === 0) {
                            this.callMediaSignal.stopSingleInstancePlayerIfNeedle();
                            if (audioContextInstance) {
                                try {
                                    yield audioContextInstance.close();
                                    audioContextInstance = null;
                                }
                                catch (ex) {
                                    this.log.error("Could not destroy AudioContext.", ex);
                                }
                            }
                        }
                    }
                }
            });
        }
        setSinkOutput(element, deviceId) {
            return __awaiter(this, void 0, void 0, function* () {
                try {
                    return yield setSinkOutput(element, deviceId);
                }
                catch (e) {
                    if (e instanceof DOMException) {
                        featurelog.error(`setSinkOutput - no permission to use output device ${deviceId}`, e);
                    }
                    else {
                        featurelog.debug("setSinkId is not supported, play to default output device");
                    }
                    return false;
                }
            });
        }
        changeVolume(volume, mediaSignal, callId) {
            const conf = this.config;
            const newVolume = (volume !== null && volume !== void 0 ? volume : null !== null) ? (volume >= 0 && volume <= 100 ? volume : 100) : 100;
            if (!mediaSignal) {
                conf.volume = newVolume;
                if (conf.audio) {
                    for (var signal in conf.audio) {
                        conf.audio[signal].volume = newVolume;
                    }
                }
            }
            else {
                if (conf && conf.audio && conf.audio[mediaSignal]) {
                    conf.audio[mediaSignal].volume = newVolume;
                }
            }
            this.callMediaSignal.changeVolume(newVolume, mediaSignal, callId);
            if (this.testerMediaSignal) {
                this.testerMediaSignal.changeVolume(newVolume, mediaSignal);
            }
        }
        getVolume(mediaSignal, configuration) {
            let volume = 100;
            const conf = this.config;
            if (configuration && configuration.volume >= 0 && configuration.volume <= 100) {
                volume = configuration.volume;
            }
            else if (conf && conf.audio && conf.audio[mediaSignal] && conf.audio[mediaSignal].volume >= 0 && conf.audio[mediaSignal].volume <= 100) {
                volume = conf.audio[mediaSignal].volume;
            }
            else if (conf && conf.volume >= 0 && conf.volume <= 100) {
                volume = conf.volume;
            }
            return volume;
        }
        playSignalTest(mediaSignal, conf, ignoreLoop, device) {
            if (this.testerMediaSignal == null) {
                this.testerMediaSignal = new CallMediaSignalPlayer(this.log, SIGNAL_TEST_CALLID, this, new Map());
            }
            return this.testerMediaSignal.play(mediaSignal, conf, ignoreLoop, device, true);
        }
        stopSignalTest(mediaSignal) {
            if (this.testerMediaSignal) {
                if (mediaSignal) {
                    const player = this.testerMediaSignal.getMediaSignalPlayerTest(mediaSignal);
                    if (player) {
                        player.stop(true);
                    }
                }
                else {
                    this.testerMediaSignal.stop(true);
                }
            }
        }
        convertRingAdvertisingToRingIfNeedle() {
            this.callMediaSignal.convertRingAdvertisingToRingIfNeedle();
        }
    }
    class DtmfPlayer {
        constructor(
        instance,
        duration,
        interToneGap) {
            this.instance = instance;
            this.duration = duration;
            this.interToneGap = interToneGap;
            this.dtmfPlayerElement = null;
            this.audioElement = new Audio();
            this.audioElementPlay = null;
            this.mediaStreamDestination = null;
            this.playerNotifier = new Subject();
            this.log = Log$1.of("webrtc:phonesignal:dtmf", instance.webrtc.client);
        }
        initDestination() {
            return __awaiter(this, void 0, void 0, function* () {
                let outputDevice;
                try {
                    outputDevice = this.instance.webrtc.device.audioOutput;
                }
                catch (e) { }
                if (outputDevice && outputDevice.deviceId) {
                    if (supportedFeature.createMediaStreamDestination !== false && supportedFeature.setSinkId !== false && !this.mediaStreamDestination && !this.audioElement.srcObject) {
                        try {
                            const audioContext = this.instance.audioContext;
                            try {
                                this.mediaStreamDestination = audioContext.createMediaStreamDestination();
                                this.audioElement.srcObject = this.mediaStreamDestination.stream;
                                supportedFeature.createMediaStreamDestination = true;
                            }
                            catch (e) {
                                supportedFeature.createMediaStreamDestination = false;
                                featurelog.debug("createMediaStreamDestination is not supported, play to default output device");
                                this.mediaStreamDestination = null;
                                this.audioElement.srcObject = null;
                            }
                        }
                        catch (e) {
                            featurelog.debug("error on create AudioContext, play to default output device", e);
                        }
                        if (this.mediaStreamDestination) {
                            if (yield this.instance.setSinkOutput(this.audioElement, outputDevice.deviceId)) {
                                return true;
                            }
                            else {
                                this.mediaStreamDestination = null;
                                this.audioElement.srcObject = null;
                                return false;
                            }
                        }
                    }
                }
                else {
                    this.mediaStreamDestination = null;
                    this.audioElement.srcObject = null;
                }
                return true;
            });
        }
        _createOscillator() {
            const audioContext = this.instance.audioContext;
            if (audioContext) {
                const gainNode = audioContext.createGain();
                const oscillator = audioContext.createOscillator();
                oscillator.type = "sine";
                oscillator.connect(gainNode, 0, 0);
                if (this.mediaStreamDestination && this.mediaStreamDestination) {
                    gainNode.connect(this.mediaStreamDestination);
                }
                else {
                    gainNode.connect(audioContext.destination);
                }
                try {
                    gainNode.gain.setValueAtTime(0.1, 0);
                }
                catch (e) {
                    console.error(e);
                }
                return oscillator;
            }
            else {
                return undefined;
            }
        }
        spoolDTMF() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.dtmfPlayerElement) {
                    const dtmfElement = this.dtmfPlayerElement;
                    const dtmfTone = dtmfElement.dtmf.charAt(0).toUpperCase();
                    dtmfElement.stats = true;
                    dtmfElement.dtmf = dtmfElement.dtmf.substring(1);
                    if (dtmfValidator.test(dtmfTone)) {
                        const dtmfSignalOptions = this.instance.config.audio.dtmf;
                        if (dtmfElement && dtmfSignalOptions && dtmfSignalOptions[dtmfTone] && dtmfSignalOptions[dtmfTone].src && !dtmfElement.audioElement) {
                            dtmfElement.audioElement = new Audio();
                        }
                        try {
                            yield this.playDtmfTone(dtmfElement, dtmfTone);
                        }
                        catch (err) { }
                        setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                            this.spoolDTMF();
                        }), this.interToneGap);
                    }
                    else if (dtmfElement.dtmf.length) {
                        this.spoolDTMF();
                    }
                    else {
                        this.dtmfPlayerElement = null;
                        this.playerNotifier.complete();
                    }
                }
            });
        }
        playDtmfTone(dtmfElement, dtmfTone) {
            return new Promise((resolve, reject) => {
                try {
                    this.playerNotifier.next(dtmfTone);
                    const dtmfSignalOptions = this.instance.config.audio.dtmf;
                    if (dtmfElement.audioElement && dtmfSignalOptions && dtmfSignalOptions[dtmfTone] && dtmfSignalOptions[dtmfTone].src) {
                        fromEvent(dtmfElement.audioElement, "ended")
                            .pipe(timeout(this.duration), take(1), catchError((err) => of(true)),
                        switchMap(() => (dtmfElement.audioElementPlay ? dtmfElement.audioElementPlay : Promise.resolve())), catchError((e) => {
                            this.log.error("Error on play dtmf from src", e);
                            return of(false);
                        }))
                            .subscribe(() => {
                            if (dtmfElement.audioElement) {
                                dtmfElement.audioElement.pause();
                                dtmfElement.audioElement.currentTime = 0;
                            }
                        });
                        dtmfElement.audioElement.src = dtmfSignalOptions[dtmfTone].src;
                        dtmfElement.audioElement.loop = true;
                        dtmfElement.audioElementPlay = dtmfElement.audioElement.play();
                    }
                    else {
                        const frequency = dtmfFrequency.get(dtmfTone);
                        if (frequency && frequency.length === 2) {
                            if (!dtmfElement.oscillator1 && !dtmfElement.oscillator2) {
                                dtmfElement.oscillator1 = this._createOscillator();
                                dtmfElement.oscillator2 = this._createOscillator();
                                if (dtmfElement.oscillator1) {
                                    dtmfElement.oscillator1.start(0);
                                }
                                if (dtmfElement.oscillator2) {
                                    dtmfElement.oscillator2.start(0);
                                }
                                if (this.audioElement.srcObject) {
                                    this.audioElementPlay = this.audioElement.play();
                                }
                            }
                            try {
                                if (dtmfElement.oscillator1) {
                                    dtmfElement.oscillator1.frequency.setValueAtTime(frequency[0], 0);
                                }
                                if (dtmfElement.oscillator2) {
                                    dtmfElement.oscillator2.frequency.setValueAtTime(frequency[1], 0);
                                }
                            }
                            catch (e) {
                                console.error(e);
                            }
                            setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                                try {
                                    yield this.audioElementPlay;
                                    if (dtmfElement.oscillator1) {
                                        dtmfElement.oscillator1.stop();
                                        dtmfElement.oscillator1.disconnect();
                                    }
                                    if (dtmfElement.oscillator2) {
                                        dtmfElement.oscillator2.stop();
                                        dtmfElement.oscillator2.disconnect();
                                    }
                                    dtmfElement.oscillator1 = undefined;
                                    dtmfElement.oscillator2 = undefined;
                                    this.audioElement.pause();
                                    this.audioElement.currentTime = 0;
                                    resolve(true);
                                }
                                catch (e) {
                                    this.log.error("Error on play dtmf", e);
                                }
                            }), this.duration);
                        }
                        else {
                            reject(`Invalid DTMF "${dtmfTone}"`);
                        }
                    }
                }
                catch (e) {
                    reject(e);
                }
            });
        }
        destroy() {
            this.mediaStreamDestination = null;
            this.audioElement.srcObject = null;
        }
        playDTMF(dtmf) {
            if (typeof dtmf === "string" && this.instance.config.audioenabled && dtmf) {
                let dtmfElement = this.dtmfPlayerElement;
                if (dtmfElement) {
                    dtmfElement.dtmf += dtmf;
                }
                else {
                    dtmfElement = {
                        stats: false,
                        dtmf,
                    };
                    this.dtmfPlayerElement = dtmfElement;
                }
                if (!dtmfElement.stats) {
                    this.spoolDTMF();
                }
            }
            else {
                this.playerNotifier.complete();
            }
            return this.playerNotifier.asObservable();
        }
    }
    class MediaSignalPlayer {
        constructor(signal,
        phoneSignalManager) {
            this.signal = signal;
            this.phoneSignalManager = phoneSignalManager;
            this.playInProgress = false;
            this.phoneSignalAudioElementPlay = Promise.resolve();
            this.phoneSignalAudioElement = new Audio();
            this.phoneSignalEndedSubscription = new Subscription();
            this.phoneSignalEndedObservable = fromEvent(this.phoneSignalAudioElement, "ended").pipe(tap(() => this.stopAudioElement()));
            this.log = Log$1.of("webrtc:phonesignal", phoneSignalManager.webrtc.client);
            const signalOptions = phoneSignalManager.config;
            this.conf = signalOptions.audio && signalOptions.audio[signal] ? signalOptions.audio[signal] : undefined;
            this.phoneSignalAudioElement.autoplay = false;
            this.phoneSignalAudioElement.loop = true;
            this.volume = phoneSignalManager.getVolume(signal, this.conf);
        }
        stopAudioElement() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.phoneSignalAudioElementPlay) {
                    try {
                        yield this.phoneSignalAudioElementPlay;
                    }
                    catch (e) {
                        this.log.error("Error on play", e);
                    }
                    this.phoneSignalAudioElement.pause();
                    this.phoneSignalAudioElement.currentTime = 0;
                }
            });
        }
        setOutputDevice(outputDevice) {
            return this.phoneSignalManager.setSinkOutput(this.phoneSignalAudioElement, outputDevice && outputDevice.deviceId ? outputDevice.deviceId : undefined);
        }
        set configuration(conf) {
            this.conf = conf;
        }
        set volume(volume) {
            this.phoneSignalAudioElement.volume = volume >= 0 && volume <= 100 ? volume / 100 : 1;
        }
        get volume() {
            return this.phoneSignalAudioElement.volume * 100;
        }
        stop(immediate) {
            if (this.playInProgress) {
                this.log.debug(`MediaSignalPlayer - stop - ${this.signal}`);
                if (this.startPlayTimeout) {
                    clearTimeout(this.startPlayTimeout);
                    this.startPlayTimeout = undefined;
                }
                this.playInProgress = false;
                if (immediate) {
                    this.stopAudioElement();
                }
            }
            this.phoneSignalEndedSubscription.unsubscribe();
        }
        playInternal() {
            try {
                if (isGestureRequiredForPlay()) {
                    this.log.warn(`maybe signal ${this.signal} cannot be play, user gesture is required`);
                }
                this.phoneSignalAudioElementPlay = this.phoneSignalAudioElement.play();
            }
            catch (e) {
                this.log.error("Error on playInternal", e);
            }
        }
        play(ignoreLoop, resolveOnSignalEnd) {
            var _a;
            this.log.debug(`MediaSignalPlayer - play - ${this.signal}`);
            if (!this.playInProgress) {
                const audio = this.conf;
                if (audio && audio.src) {
                    const loop = !!audio.loop;
                    this.phoneSignalAudioElement.src = audio.src;
                    this.phoneSignalAudioElement.loop = loop;
                    if (loop && audio.interval) {
                        this.phoneSignalAudioElement.loop = false;
                        this.phoneSignalEndedSubscription = this.phoneSignalEndedObservable
                            .pipe(delay(audio.interval), filter(() => this.playInProgress))
                            .subscribe(() => {
                            this.playInternal();
                        });
                    }
                    else {
                        this.phoneSignalEndedSubscription = new Subscription(() => {
                            if (loop) {
                                this.phoneSignalAudioElement.loop = false;
                                switch (this.signal) {
                                    case MediaSignal.dialtone:
                                    case MediaSignal.ringback:
                                    case MediaSignal.ring:
                                        this.stopAudioElement();
                                        break;
                                    default:
                                        this.phoneSignalEndedObservable.pipe(first()).subscribe(() => this.stopAudioElement());
                                        break;
                                }
                            }
                            else {
                                this.stopAudioElement();
                            }
                        });
                    }
                    if (audio.maxlength) {
                        let phoneSignalTimer = setTimeout(() => {
                            phoneSignalTimer = null;
                            this.stop(true);
                        }, audio.maxlength);
                        this.phoneSignalEndedSubscription.add(() => {
                            if (phoneSignalTimer) {
                                clearTimeout(phoneSignalTimer);
                                phoneSignalTimer = null;
                            }
                        });
                    }
                    if (ignoreLoop) {
                        this.phoneSignalEndedObservable.pipe(first()).subscribe(() => this.stop(true));
                    }
                    if (((_a = audio.startDelay) !== null && _a !== void 0 ? _a : 0) <= 0) {
                        this.playInternal();
                    }
                    else {
                        if (this.startPlayTimeout) {
                            clearTimeout(this.startPlayTimeout);
                        }
                        this.startPlayTimeout = setTimeout(() => {
                            if (this.startPlayTimeout) {
                                clearTimeout(this.startPlayTimeout);
                                this.startPlayTimeout = undefined;
                            }
                            this.playInternal();
                        }, audio.startDelay);
                    }
                }
                this.playInProgress = true;
            }
            return resolveOnSignalEnd
                ? new Promise((resolve) => {
                    this.phoneSignalEndedSubscription.add(resolve);
                })
                : Promise.resolve();
        }
    }
    class CallMediaSignalPlayer {
        constructor(
        log,
        callId,
        phoneSignal,
        singleInstancePlayer) {
            this.log = log;
            this.callId = callId;
            this.phoneSignal = phoneSignal;
            this.singleInstancePlayer = singleInstancePlayer;
            this.dtmfPlayer = [];
            this.signalPlayed = new Map();
            this.isTestPlayer = callId === SIGNAL_TEST_CALLID;
        }
        get canPlay() {
            var _a;
            return this.isTestPlayer || !!((_a = this.phoneSignal.webrtc.retriveCall(this.callId)) === null || _a === void 0 ? void 0 : _a.mediaOwnedByCurrentInstance);
        }
        getOutputDeviceBySignal(signal) {
            return signal === MediaSignal.ring ? this.phoneSignal.webrtc.device.audioSignalOutput : this.phoneSignal.webrtc.device.audioOutput;
        }
        buildPhoneSignal(signal, conf, device) {
            return __awaiter(this, void 0, void 0, function* () {
                let signalPlayer = this.singleInstancePlayer.get(signal);
                if (!signalPlayer) {
                    signalPlayer = this.signalPlayed.get(signal);
                    if (!signalPlayer) {
                        signalPlayer = new MediaSignalPlayer(signal, this.phoneSignal);
                        this.signalPlayed.set(signal, signalPlayer);
                    }
                }
                if (conf && signalPlayer) {
                    signalPlayer.configuration = conf;
                    signalPlayer.volume = this.phoneSignal.getVolume(signal, conf);
                }
                yield signalPlayer.setOutputDevice(device ? device : this.getOutputDeviceBySignal(signal));
                return signalPlayer;
            });
        }
        changeVolume(volume, mediaSignal) {
            this.signalPlayed.forEach((signalPlayer) => {
                if (!mediaSignal || signalPlayer.signal == mediaSignal) {
                    signalPlayer.volume = volume;
                }
            });
        }
        get currentPlay() {
            return this._currentPlay;
        }
        getMediaSignalPlayer(type) {
            const player = this.singleInstancePlayer.get(type);
            return player ? player : this.signalPlayed.get(type);
        }
        getMediaSignalPlayerTest(type) {
            return this.signalPlayed.get(type);
        }
        stop(immediate) {
            this.log.debug(`CallMediaSignalPlayer - request stop - immediate: ${immediate}`);
            this._currentPlay = undefined;
            if (this.signalPlayed.size) {
                this.signalPlayed.forEach((signalPlayer) => {
                    signalPlayer.stop(immediate);
                });
                this.signalPlayed.clear();
            }
            if (this.dtmfPlayer && this.dtmfPlayer.length) {
                this.dtmfPlayer.forEach((dtmfPlayer) => {
                    dtmfPlayer.destroy();
                });
                this.dtmfPlayer = [];
            }
        }
        playDTMF(dtmf, duration, interToneGap) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canPlay) {
                    const dtmfPlayer = new DtmfPlayer(this.phoneSignal, duration, interToneGap);
                    this.dtmfPlayer.push(dtmfPlayer);
                    yield dtmfPlayer.initDestination();
                    dtmfPlayer
                        .playDTMF(dtmf)
                        .pipe(finalize(() => {
                        dtmfPlayer.destroy();
                        const indexOfPlayer = this.dtmfPlayer.indexOf(dtmfPlayer);
                        if (indexOfPlayer > -1) {
                            this.dtmfPlayer.splice(indexOfPlayer, 1);
                        }
                    }))
                        .subscribe();
                }
                return true;
            });
        }
        play(type, conf, ignoreLoop, device, resolveOnSignalEnd) {
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug(`CallMediaSignalPlayer - request play - ${type}`);
                this._currentPlay = type;
                const phoneSignalPlayer = yield this.buildPhoneSignal(type, conf, device);
                if (this._currentPlay === type) {
                    if (type === MediaSignal.ring || this.canPlay) {
                        return phoneSignalPlayer.play(ignoreLoop, !!resolveOnSignalEnd);
                    }
                    else {
                        return;
                    }
                }
                else {
                    this.log.debug(`CallMediaSignalPlayer - block play ${type} - current play '${this._currentPlay}' is different from '${type}'`);
                }
            });
        }
    }
    class CallMediaSignalPlayerStore {
        constructor(
        instance) {
            this.instance = instance;
            this.log = Log$1.of("webrtc:phonesignal", instance.webrtc.client);
            this.currentPhoneSignal = new Map();
            this.singleInstancePlayer = new Map();
        }
        reloadConfig() {
            if (this.instance.config) {
                this.stopSingleInstancePlayerIfNeedle();
                this.singleInstancePlayer.set(MediaSignal.dialtone, new MediaSignalPlayer(MediaSignal.dialtone, this.instance));
                this.singleInstancePlayer.set(MediaSignal.ring, new MediaSignalPlayer(MediaSignal.ring, this.instance));
                this.singleInstancePlayer.set(MediaSignal.ringAdvertising, new MediaSignalPlayer(MediaSignal.ringAdvertising, this.instance));
            }
        }
        createNewIfNotSet(callId) {
            let phoneSignalPlayer = this.currentPhoneSignal.get(callId);
            if (!phoneSignalPlayer) {
                phoneSignalPlayer = new CallMediaSignalPlayer(this.log, callId, this.instance, this.singleInstancePlayer);
                this.currentPhoneSignal.set(callId, phoneSignalPlayer);
            }
            return phoneSignalPlayer;
        }
        get(callId) {
            return this.createNewIfNotSet(callId);
        }
        getCurrentPlay(callId) {
            const phoneSignalPlayer = this.currentPhoneSignal.get(callId);
            return phoneSignalPlayer ? phoneSignalPlayer.currentPlay : undefined;
        }
        playDTMF(callId, dtmf, duration, interToneGap) {
            this.log.info(`callid: ${callId} - playDTMF: ${dtmf}`);
            return this.get(callId).playDTMF(dtmf, duration, interToneGap);
        }
        play(callId, type) {
            this.log.info(`callid: ${callId} - play: ${type}`);
            return this.get(callId).play(type, null, false, null, false);
        }
        stop(callId, immediate) {
            this.log.info(`callid: ${callId} - stop all`);
            this.get(callId).stop(immediate);
        }
        delete(callId) {
            this.get(callId).stop(true);
            this.currentPhoneSignal.delete(callId);
        }
        keys() {
            return this.currentPhoneSignal.keys();
        }
        size() {
            return this.currentPhoneSignal.size;
        }
        changeVolume(volume, mediaSignal, callId) {
            this.currentPhoneSignal.forEach((signalPlayed, idcall) => {
                if (!callId || idcall === callId) {
                    signalPlayed.changeVolume(volume, mediaSignal);
                }
            });
            this.singleInstancePlayer.forEach((signalPlayer) => {
                if (!mediaSignal || signalPlayer.signal == mediaSignal) {
                    signalPlayer.volume = volume;
                }
            });
        }
        stopSingleInstancePlayerIfNeedle(signal) {
            var _a;
            if (signal) {
                if (this.singleInstancePlayer.has(signal)) {
                    let otherCallSameSignal = 0;
                    this.currentPhoneSignal.forEach((callPhoneSignalPlayer) => {
                        const currentPlay = callPhoneSignalPlayer.currentPlay;
                        if (currentPlay && currentPlay == signal) {
                            otherCallSameSignal++;
                        }
                    });
                    if (otherCallSameSignal === 0) {
                        this.log.debug(`stopSingleInstancePlayerIfNeedle - no other call is play ${signal}, stop now`);
                        (_a = this.singleInstancePlayer.get(signal)) === null || _a === void 0 ? void 0 : _a.stop(true);
                    }
                    else {
                        this.log.debug(`stopSingleInstancePlayerIfNeedle - other call is play ${signal}, so can't stop now`);
                    }
                }
            }
            else {
                this.singleInstancePlayer.forEach((player) => {
                    player.stop(true);
                });
            }
        }
        convertRingAdvertisingToRingIfNeedle() {
            if (this.currentPhoneSignal.size) {
                const ringadv = [];
                this.currentPhoneSignal.forEach((phoneSignal, callId) => {
                    if (phoneSignal.currentPlay === "ringAdvertising") {
                        ringadv.push({ callId });
                    }
                });
                const doConvert = ringadv.length === this.currentPhoneSignal.size;
                this.log.debug(`convertRingAdvertisingToRingIfNeedle - ${doConvert ? `${ringadv[0]} convert to ring` : "No need to convert"} - PhoneSignal: ${this.currentPhoneSignal.size}, ringAdvertising: ${ringadv.length}`);
                if (doConvert) {
                    this.stop(ringadv[0].callId, true);
                    this.play(ringadv[0].callId, MediaSignal.ring);
                }
            }
            else {
                this.log.debug(`convertRingAdvertisingToRingIfNeedle - PhoneSignal: 0`);
            }
        }
    }

    class WebrtcDialParams extends DialParams {
        constructor(params) {
            super(params);
        }
        toRequestParams(phoneManagerActive) {
            const result = super.toRequestParams(phoneManagerActive);
            result[8] = this.params.webrtcFields ? this.params.webrtcFields.toObject() : null;
            return result;
        }
    }
    class WebrtcNotEnableError {
        constructor(message) {
            this.message = message;
        }
    }
    class NoCallError {
        constructor(message) {
            this.message = message;
        }
    }
    class WebrtcRequestPromise extends RequestPromise {
        constructor() {
            super("", []);
        }
        checkWebrtcEnabled(client, { skipChannelCheck, channel, callId } = {}) {
            if (client.webrtc) {
                if (client.webrtc.enable) {
                    let call = null;
                    if (!channel || skipChannelCheck || client.webrtc.isEnabledForChannel(channel)) {
                        if (null !== (callId !== null && callId !== void 0 ? callId : null)) {
                            call = client.webrtc.retriveCall(callId);
                            if (!client.phoneManagerActive || !!(call === null || call === void 0 ? void 0 : call.deviceIsApp)) {
                                return of({ webrtc: client.webrtc });
                            }
                        }
                        return of({ webrtc: client.webrtc, call: call });
                    }
                    else {
                        return throwError(() => new WebrtcNotEnableError(`Webrtc is not enable for channel ${channel}`));
                    }
                }
                else {
                    return throwError(() => new WebrtcNotEnableError(`Webrtc is not enable, call webrtc.start() before ${this.method}`));
                }
            }
            else {
                return throwError(() => new WebrtcNotEnableError(`WebRTC is not attached to client`));
            }
        }
        execute(client, requestTimeout) {
            const result = new Observable((result) => {
                var _a;
                const resultSubscription = (_a = this.buildResponse(client, requestTimeout)) === null || _a === void 0 ? void 0 : _a.subscribe(result);
                if (!resultSubscription) {
                    result.complete();
                }
                return () => resultSubscription === null || resultSubscription === void 0 ? void 0 : resultSubscription.unsubscribe;
            });
            const responsePromise = {
                result,
                resultSync: of(result),
                errorResolver: client.methodsErrorResolver,
            };
            return responsePromise;
        }
    }
    class WebrtcRequestExecutor extends WebrtcRequestPromise {
        constructor(doRequest) {
            super();
            this.doRequest = doRequest;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client).pipe(switchMap(({ webrtc }) => this.doRequest(webrtc, { timeout: requestTimeout })));
        }
    }
    class EchoTestConnectivityCheck extends WebrtcRequestPromise {
        constructor(media, mediaConfiguration, videoContainer) {
            super();
            this.media = media;
            this.mediaConfiguration = mediaConfiguration;
            this.videoContainer = videoContainer;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client).pipe(switchMap(({ webrtc }) => webrtc.generateWebrtcFieldsForConnectivityCheck(ChannelType.PhoneCall, this.media, this.mediaConfiguration, this.videoContainer)));
        }
    }
    let StartVideoEchoTestRequest$1 = class StartVideoEchoTestRequest extends WebrtcRequestPromise  {
        constructor(audio, video, videoContainer, mediaConfiguration) {
            super();
            this.audio = audio;
            this.video = video;
            this.videoContainer = videoContainer;
            this.mediaConfiguration = mediaConfiguration;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client).pipe(switchMap(({ webrtc }) => {
                const webrtcDialParams = new WebrtcDialParams({
                    fromDeviceType: ExtenType.WEBRTC,
                    media: new MediaParamImpl({ audio: this.audio, video: this.video }),
                    privateCall: false,
                    channelId: ChannelType.Video,
                    serviceCode: "dummy",
                });
                return from(webrtc.generateWebrtcFieldsForDial(webrtcDialParams, this.mediaConfiguration, this.videoContainer, undefined, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)).pipe(tap((webrtcFields) => (webrtcDialParams.params.webrtcFields = webrtcFields)), switchMap((webrtcFields) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        return yield client.webrtc.methodExecutor.startVideoEchoTest({
                            callId: webrtcDialParams.params.webrtcFields.clientid,
                            media: webrtcDialParams.params.media,
                            webrtcField: webrtcDialParams.params.webrtcFields.toObject(),
                        }, { timeout: requestTimeout });
                    }
                    catch (err) {
                        const webrtcFields = webrtcDialParams.params.webrtcFields;
                        if (webrtcFields && webrtcFields.clientid) {
                            yield webrtc.destroyCall(webrtcFields.clientid);
                        }
                        throw err;
                    }
                })));
            }));
        }
    };
    let DialRequest$1 = class DialRequest extends WebrtcRequestPromise {
        constructor(dialParam, videoContainer, mediaConstraints, userInteractionAction) {
            super();
            this.videoContainer = videoContainer;
            this.mediaConstraints = mediaConstraints;
            this.userInteractionAction = userInteractionAction;
            this.dialParam = new WebrtcDialParams(dialParam);
        }
        buildResponse(client, requestTimeout) {
            if (client.phoneManagerActive && ExtenType.WEBRTC === this.dialParam.params.fromDeviceType && ChannelType.PhoneCall === this.dialParam.params.channelId ) {
                return this.checkWebrtcEnabled(client, { skipChannelCheck: this.dialParam.isForApp(), channel: this.dialParam.params.channelId }).pipe(switchMap(({ webrtc }) => {
                    const callMedia = this.dialParam.params.media;
                    webrtc.methods.log.debug(`Webrtc dial is requested - contact: ${this.dialParam.params.contact.value} - audio: ${!!callMedia.audio} - video: ${!!callMedia.video} - desktop: ${!!callMedia.desktop} - data: ${!!callMedia.data}`);
                    return from(webrtc.generateWebrtcFieldsForDial(this.dialParam, this.mediaConstraints, this.videoContainer, this.userInteractionAction, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)).pipe(tap((webrtcFields) => (this.dialParam.params.webrtcFields = webrtcFields)), switchMap((webrtcFields) => __awaiter(this, void 0, void 0, function* () {
                        try {
                            return yield client.webrtc.methodExecutor.dial({ dialParam: this.dialParam.params }, { timeout: requestTimeout });
                        }
                        catch (err) {
                            if (this.dialParam.params.webrtcFields && this.dialParam.params.webrtcFields.clientid) {
                                yield webrtc.destroyCall(this.dialParam.params.webrtcFields.clientid, this.dialParam, err);
                            }
                            throw err;
                        }
                    })));
                }));
            }
            else {
                return null;
            }
        }
    };
    class AnswerRequest extends WebrtcRequestPromise {
        constructor(channelId = ChannelType.PhoneCall, callId, media, customFields, videoContainer, mediaConfiguration) {
            super();
            this.channelId = channelId;
            this.callId = callId;
            this.customFields = customFields;
            this.videoContainer = videoContainer;
            this.mediaConfiguration = mediaConfiguration;
            this.media = MediaParam.of(media);
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { channel: this.channelId, callId: this.callId }).pipe(switchMap(({ webrtc, call }) => {
                const log = webrtc.methods.log;
                log.debug(`Webrtc answer is requested - callId: ${this.callId} - audio: ${!!this.media.audio} - video: ${!!this.media.video} - desktop: ${!!this.media.desktop} - data: ${!!this.media.data}`);
                if (!call || (call.signalingState === CallState.NEW_INBOUND && call.waitForAnswer)) {
                    return from(webrtc.generateWebrtcFieldsForAnswer(this.channelId, this.callId, this.media, this.mediaConfiguration, this.videoContainer)).pipe(switchMap((webrtcFields) => __awaiter(this, void 0, void 0, function* () {
                        try {
                            return yield client.webrtc.methodExecutor.answer({
                                callId: this.callId,
                                media: this.media,
                                webrtcField: webrtcFields.toObject(),
                                customFields: this.customFields,
                            }, { timeout: requestTimeout });
                        }
                        catch (err) {
                            yield webrtc.destroyCall(this.callId);
                            throw err;
                        }
                    })));
                }
                else {
                    const msg = "Answer was previous requested, wait or cancel call";
                    log.error(msg);
                    return throwError(() => new Error(msg));
                }
            }));
        }
    }
    class CancelRequest extends WebrtcRequestPromise {
        constructor(callId, storeAction, execWebapiRequest) {
            super();
            this.callId = callId;
            this.storeAction = storeAction;
            this.execWebapiRequest = execWebapiRequest;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ webrtc }) => __awaiter(this, void 0, void 0, function* () {
                webrtc.methods.log.debug(`Webrtc cancel is requested - callId: ${this.callId}`);
                if (this.storeAction) {
                    webrtc.cancelCallRequest(this.callId);
                }
                if (this.execWebapiRequest) {
                    return client.webrtc.methodExecutor.cancel({ callId: this.callId }, { timeout: requestTimeout });
                }
                else {
                    return true;
                }
            })));
        }
    }
    class HoldRequest extends WebrtcRequestPromise {
        constructor(callId) {
            super();
            this.callId = callId;
            this.doHold = true;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ webrtc }) => from(webrtc.toggleHold(this.callId)).pipe(switchMap((callHolded) => __awaiter(this, void 0, void 0, function* () {
                if (this.doHold) {
                    return client.webrtc.methodExecutor.hold({ callId: this.callId }, { timeout: requestTimeout });
                }
                else {
                    return client.webrtc.methodExecutor.unhold({ callId: this.callId }, { timeout: requestTimeout });
                }
            })))));
        }
    }
    class UnholdRequest extends HoldRequest {
        constructor(callId) {
            super(callId);
            this.callId = callId;
            this.doHold = false;
        }
    }
    let AttendedTransferRequest$1 = class AttendedTransferRequest extends WebrtcRequestPromise {
        constructor(callId, heldCallId, media, fields) {
            super();
            this.callId = callId;
            this.heldCallId = heldCallId;
            this.media = media;
            this.fields = fields;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ call }) => __awaiter(this, void 0, void 0, function* () {
                var _a;
                let media = MediaParam.of(this.media);
                let fields = this.fields;
                if (call && (!this.media || !media._hasMedia())) {
                    media = call.localCallMedia;
                }
                if (call && !this.fields && call.localMedia) {
                    fields = new WebRTCField(null, new WebRTCFieldSession(call.isOffer, call.localDescription), null, null, null).toObject();
                }
                const response = yield client.webrtc.methodExecutor.attendedTransfer({ callId: this.callId, heldCallId: this.heldCallId, media, webrtcField: fields }, { timeout: requestTimeout });
                if (response && (call === null || call === void 0 ? void 0 : call.signalingState) === CallState.NEW_OUTBOUND) {
                    (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.log.debug(`stopping tone signals for attendedTransfer in ring state`);
                    call.toneSignalEnabled = false;
                }
                return response;
            })));
        }
    };
    class sendDTMFRequest extends WebrtcRequestPromise {
        constructor(callId, dtmf, playTone = true, dtmfDuration, dtmfInterToneGap) {
            super();
            this.callId = callId;
            this.dtmf = dtmf;
            this.playTone = playTone;
            this.dtmfDuration = dtmfDuration;
            this.dtmfInterToneGap = dtmfInterToneGap;
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ call, webrtc }) => {
                if (call) {
                    const dtmf = (this.dtmf || "").split("").reduce((d1, d2) => (dtmfValidator.test(d2) ? d1 + d2 : d1), "");
                    if (dtmf) {
                        return from(call.sendDTMF(dtmf, this.playTone, this.dtmfDuration, this.dtmfInterToneGap)).pipe(switchMap((isSentInband) => __awaiter(this, void 0, void 0, function* () {
                            if (isSentInband) {
                                return true;
                            }
                            else {
                                return client.webrtc.methodExecutor.sendDTMF({ callId: this.callId, dtmf }, { timeout: requestTimeout });
                            }
                        })));
                    }
                    else {
                        return throwError(() => new Error("Invalid DTMF"));
                    }
                }
                else {
                    const msg = `Webrtc sendDTMF - call ${this.callId} is unavailable`;
                    webrtc.methods.log.error(msg);
                    return throwError(() => new NoCallError(msg));
                }
            }));
        }
    }
    let MuteRequest$1 = class MuteRequest extends WebrtcRequestPromise {
        constructor(callId, media) {
            super();
            this.callId = callId;
            this.media = new MediaParamImpl(media);
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ call, webrtc }) => {
                const log = webrtc.methods.log;
                log.debug(`Webrtc MUTE is requested - callId: ${this.callId} - ` + `audio: ${!!(this.media && this.media.audio)} - ` + `video: ${!!(this.media && this.media.video)} - ` + `desktop: ${!!(this.media && this.media.desktop)} - ` + `data: ${!!this.media && this.media.data}`);
                if (this.media && Object.keys(this.media).length) {
                    if (call) {
                        let result = of(false);
                        if (this.media.audio) {
                            result = result.pipe(switchMap(() => call.toggleAudioMute(true, false, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                        }
                        if (this.media.video) {
                            result = result.pipe(switchMap(() => call.toggleVideoMute(true, false, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                        }
                        return result.pipe(switchMap(() => call.notifyCallMediaState(this.media, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                    }
                    else {
                        const msg = `Webrtc MUTE - call ${this.callId} is unavailable`;
                        log.error(msg);
                        return throwError(() => new NoCallError(msg));
                    }
                }
                else {
                    return throwError(() => new Error("Webrtc MUTE is called with any media to mute"));
                }
            }));
        }
    };
    let UnmuteRequest$1 = class UnmuteRequest extends WebrtcRequestPromise {
        constructor(callId, media) {
            super();
            this.callId = callId;
            this.media = new MediaParamImpl(media);
        }
        buildResponse(client, requestTimeout) {
            return this.checkWebrtcEnabled(client, { callId: this.callId }).pipe(switchMap(({ call, webrtc }) => {
                const log = webrtc.methods.log;
                log.debug(`Webrtc UNMUTE is requested - callId: ${this.callId} - ` + `audio: ${!!(this.media && this.media.audio)} - ` + `video: ${!!(this.media && this.media.video)} - ` + `desktop: ${!!(this.media && this.media.desktop)} - ` + `data: ${!!this.media && this.media.data}`);
                if (this.media && Object.keys(this.media).length) {
                    if (call) {
                        let result = of(false);
                        if (this.media.audio) {
                            result = result.pipe(switchMap(() => call.toggleAudioMute(false, false, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                        }
                        if (this.media.video) {
                            result = result.pipe(switchMap(() => call.toggleVideoMute(false, false, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                        }
                        return result.pipe(switchMap(() => call.notifyCallMediaState(this.media, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout)));
                    }
                    else {
                        const msg = `Webrtc UNMUTE - call ${this.callId} is unavailable`;
                        log.error(msg);
                        return throwError(() => new NoCallError(msg));
                    }
                }
                else {
                    return throwError(() => new Error("Webrtc UNMUTE is called with any media to unmute"));
                }
            }));
        }
    };

    function isWebrtcNotEnableError(error) {
        return error instanceof WebrtcNotEnableError;
    }
    function isNoCallError(error) {
        return error instanceof NoCallError;
    }
    class MethodFactory {
        static echoTestConnectivityCheck(media, mediaConfiguration, videoContainer) {
            return new EchoTestConnectivityCheck(media, mediaConfiguration, videoContainer);
        }
        static startVideoEchoTest(audio, video, videoContainer, mediaConfiguration) {
            return new StartVideoEchoTestRequest$1(audio, video, videoContainer, mediaConfiguration);
        }
        static dial(dialParam, videoContainer, mediaConstraints, userInteractionAction) {
            return new DialRequest$1(dialParam, videoContainer, mediaConstraints, userInteractionAction);
        }
        static answer(channelId, callId, media, customFields, videoContainer, mediaConfiguration) {
            return new AnswerRequest(channelId, callId, media, customFields, videoContainer, mediaConfiguration);
        }
        static hold(callId) {
            return new HoldRequest(callId);
        }
        static unhold(callId) {
            return new UnholdRequest(callId);
        }
        static attendedTransfer(callId, heldCallId, media, fields) {
            return new AttendedTransferRequest$1(callId, heldCallId, media, fields);
        }
        static blindTransfer(callId, accessCode, number, data) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.blindTransfer({ callId, accessCode, number, data }, options));
        }
        static sendDTMF(callId, dtmf, playTone = true, dtmfDuration, dtmfInterToneGap) {
            return new sendDTMFRequest(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap);
        }
        static forceCancel(callId) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.cancel({ callId }, options));
        }
        static cancel(callId, storeAction, execWebapiRequest) {
            return new CancelRequest(callId, storeAction, execWebapiRequest);
        }
        static createUserInteraction(createUserInteraction) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.createUserInteraction({ createUserInteraction }, options));
        }
        static removeCallFromUserInteraction(callId) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.removeCallFromUserInteraction({ callId }, options));
        }
        static updateWebRTCFields(callId, media, fields) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.updateWebRTCFields({ callId, media, webrtcField: fields.toObject() }, options));
        }
        static getWebrtcConfiguration() {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.getWebrtcConfiguration({}, options));
        }
        static setWebRTCAvailableMedia(media) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.setWebRTCAvailableMedia({ media }, options));
        }
        static mute(callId, media) {
            return new MuteRequest$1(callId, media);
        }
        static unmute(callId, media) {
            return new UnmuteRequest$1(callId, media);
        }
        static notifyMute(callId, media, fields) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.mute({ callId, media, fields: fields ? fields.toObject() : undefined }, options));
        }
        static notifyUnmute(callId, media, fields) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.unmute({ callId, media, fields: fields ? fields.toObject() : undefined }, options));
        }
        static startVideoOnCall(callId, fields) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.startVideoOnCall({ callId, fields: fields ? fields.toObject() : undefined }, options));
        }
        static stopVideoOnCall(callId, fields) {
            return new WebrtcRequestExecutor((webrtc, options) => webrtc.methodExecutor.stopVideoOnCall({ callId, fields: fields ? fields.toObject() : undefined }, options));
        }
    }

    function isWebrtcNotEnabledOrIsNoWebrtcCall(err) {
        return isWebrtcNotEnableError(err) || isNoCallError(err);
    }
    function switchMapIfEmpty(getFirst, getSecond, shouldRunSecondOnFirstError = isWebrtcNotEnabledOrIsNoWebrtcCall) {
        return new Observable((response) => {
            var _a;
            let hasValue = false, subscriptionClosed = false, subscription = ((_a = getFirst()) !== null && _a !== void 0 ? _a : EMPTY)
                .pipe(catchError((err) => {
                if (!shouldRunSecondOnFirstError(err)) {
                    response.error(err);
                    hasValue = true;
                }
                return EMPTY;
            }))
                .subscribe({
                next: (value) => {
                    hasValue = true;
                    response.next(value);
                },
                complete: () => {
                    if (hasValue) {
                        response.complete();
                    }
                    else {
                        setTimeout(() => {
                            var _a;
                            if (!subscriptionClosed) {
                                subscription = ((_a = getSecond()) !== null && _a !== void 0 ? _a : EMPTY).subscribe(response);
                            }
                        });
                    }
                },
            });
            return () => {
                subscriptionClosed = true;
                subscription.unsubscribe();
            };
        });
    }
    class ClientRequestPromise extends RequestPromise {
        buildResponsePromise(client, result) {
            return {
                result: result,
                resultSync: of(result),
                errorResolver: client.methodsErrorResolver,
            };
        }
        execute(client, requestTimeout) {
            return this.buildResponsePromise(client, new Observable((result) => {
                var _a;
                const resultSubscription = (_a = this.buildResponse(client, requestTimeout)) === null || _a === void 0 ? void 0 : _a.subscribe(result);
                if (!resultSubscription) {
                    result.complete();
                }
                return () => resultSubscription === null || resultSubscription === void 0 ? void 0 : resultSubscription.unsubscribe;
            }));
        }
    }
    class StartVideoEchoTestRequest extends ClientRequestPromise {
        constructor(audio, video, videoContainer, mediaConfiguration) {
            super("", []);
            this.audio = audio;
            this.video = video;
            this.videoContainer = videoContainer;
            this.mediaConfiguration = mediaConfiguration;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.startVideoEchoTest(this.audio, this.video, this.videoContainer, this.mediaConfiguration, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => throwError(() => new Error(`WebRTC is not attached to client ${client.instanceId}`)));
        }
    }
    class DialRequest extends ClientRequestPromise {
        constructor(dialParam, videoContainer, mediaConfiguration, userInteractionAction) {
            super("dial", []);
            this.dialParam = dialParam;
            this.videoContainer = videoContainer;
            this.mediaConfiguration = mediaConfiguration;
            this.userInteractionAction = userInteractionAction;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.dial(this.dialParam, this.videoContainer, this.mediaConfiguration, this.userInteractionAction, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.withParameters(...new DialParams(this.dialParam).toRequestParams(client.phoneManagerActive))
                .doExecute(client, requestTimeout)
                .result.pipe(map((result) => (result ? "true" : null))));
        }
    }
    class AnswerOnChannelRequest extends ClientRequestPromise {
        constructor(channelType, callId, media, customFields, videoContainer, mediaConfiguration) {
            super("answer", [callId, null, null, customFields !== null && customFields !== void 0 ? customFields : null]);
            this.channelType = channelType;
            this.callId = callId;
            this.media = media;
            this.customFields = customFields;
            this.videoContainer = videoContainer;
            this.mediaConfiguration = mediaConfiguration;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.answer(this.channelType, this.callId, this.media, this.customFields, this.videoContainer, this.mediaConfiguration, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class CancelCallRequest extends ClientRequestPromise {
        constructor(callId) {
            super("cancel", [callId]);
            this.callId = callId;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.cancel(this.callId, true, true, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class HoldCallRequest extends ClientRequestPromise {
        constructor(callId) {
            super("hold", [callId]);
            this.callId = callId;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.hold(this.callId, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class UnholdCallRequest extends ClientRequestPromise {
        constructor(callId) {
            super("unhold", [callId]);
            this.callId = callId;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.unhold(this.callId, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class AttendedTransferRequest extends ClientRequestPromise {
        constructor(callId, heldCallId, media, fields) {
            super("attendedTransfer", [callId, heldCallId, ["audio"], fields]);
            this.callId = callId;
            this.heldCallId = heldCallId;
            this.media = media;
            this.fields = fields;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.attendedTransfer(this.callId, this.heldCallId, this.media, this.fields, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class BlindTransferRequest extends ClientRequestPromise {
        constructor(callId, accessCode, number, data) {
            super("blindTransfer", [callId, accessCode, number, data]);
            this.callId = callId;
            this.accessCode = accessCode;
            this.number = number;
            this.data = data;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.blindTransfer(this.callId, this.accessCode, this.number, this.data, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class SendDTMFRequest extends ClientRequestPromise {
        constructor(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap) {
            super("sendDTMF", [callId, dtmf]);
            this.callId = callId;
            this.dtmf = dtmf;
            this.playTone = playTone;
            this.dtmfDuration = dtmfDuration;
            this.dtmfInterToneGap = dtmfInterToneGap;
        }
        doExecuteInternal(client, requestTimeout) {
            const dtmf = (this.dtmf || "").split("").reduce((d1, d2) => (dtmfValidator.test(d2) ? d1 + d2 : d1), "");
            if (dtmf) {
                return super.doExecute(client, requestTimeout).result;
            }
            else {
                return throwError(() => new Error("Invalid DTMF"));
            }
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.sendDTMF(this.callId, this.dtmf, this.playTone, this.dtmfDuration, this.dtmfInterToneGap, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecuteInternal(client, requestTimeout));
        }
    }
    class MuteRequest extends ClientRequestPromise {
        constructor(callId, media) {
            super("mute", [callId, MediaParam.toCallMedia(media), null]);
            this.callId = callId;
            this.media = media;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.mute(this.callId, this.media, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class UnmuteRequest extends ClientRequestPromise {
        constructor(callId, media) {
            super("unmute", [callId, MediaParam.toCallMedia(media), null]);
            this.callId = callId;
            this.media = media;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.unmute(this.callId, this.media, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class CreateUserInteractionRequest extends ClientRequestPromise {
        constructor(createUserInteraction) {
            super("createUserInteraction", [createUserInteraction]);
            this.createUserInteraction = createUserInteraction;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.createUserInteraction(this.createUserInteraction, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }
    class RemoveCallFromUserInteractionRequest extends ClientRequestPromise {
        constructor(callId) {
            super("removeCallFromUserInteraction", [callId]);
            this.callId = callId;
        }
        buildResponse(client, requestTimeout) {
            return switchMapIfEmpty(() => { var _a; return (_a = client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.removeCallFromUserInteraction(this.callId, requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : this.options.timeout).result; }, () => this.doExecute(client, requestTimeout).result);
        }
    }

    class WebapiMethodFactory {
        static getPresenceStatusCustom() {
            return new RequestChunkedUpdate("getPresenceStatusCustom", []);
        }
        static startVideoEchoTest(audio, video, videoContainer, mediaConfiguration) {
            return new StartVideoEchoTestRequest(audio, video, videoContainer, mediaConfiguration);
        }
        static dial(dialParam, videoContainer, mediaConfiguration, userInteractionAction) {
            return new DialRequest(dialParam, videoContainer, mediaConfiguration, userInteractionAction);
        }
        static answerOnChannel(channelType, callId, media, customFields, videoContainer, mediaConfiguration) {
            return new AnswerOnChannelRequest(channelType, callId, media, customFields, videoContainer, mediaConfiguration);
        }
        static cancelCall(callId) {
            return new CancelCallRequest(callId);
        }
        static holdCall(callId) {
            return new HoldCallRequest(callId);
        }
        static unholdCall(callId) {
            return new UnholdCallRequest(callId);
        }
        static attendedTransfer(callId, heldCallId, media, fields) {
            return new AttendedTransferRequest(callId, heldCallId, media, fields);
        }
        static blindTransfer(callId, accessCode, number, data) {
            return new BlindTransferRequest(callId, accessCode, number, data);
        }
        static sendDTMF(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap) {
            return new SendDTMFRequest(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap);
        }
        static muteCall(callId, media) {
            return new MuteRequest(callId, media);
        }
        static unmuteCall(callId, media) {
            return new UnmuteRequest(callId, media);
        }
        static createUserInteraction(createUserInteraction) {
            return new CreateUserInteractionRequest(createUserInteraction);
        }
        static removeCallFromUserInteraction(callId) {
            return new RemoveCallFromUserInteractionRequest(callId);
        }
        static refreshToken(username, accessToken) {
            return new RequestPromise("refreshToken", [username, accessToken]);
        }
        static resumeChatToken() {
            return new RequestPromise("resumeChatToken", []);
        }
        static getRefreshToken() {
            return new RequestPromise("getRefreshToken", []);
        }
        static searchUsers(name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive) {
            return new RequestChunkedUpdate("searchUsers", [name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive]);
        }
        static searchUsersExtended(addressbookType, fields, exclusive, pageNumber, pageSize) {
            return new RequestChunkedUpdate("searchUsersExtended", [addressbookType, fields, exclusive, pageNumber, pageSize]);
        }
        static searchUsersExtendedByBackend(addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize) {
            return new RequestChunkedUpdate("searchUsersExtendedByBackend", [addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize]);
        }
        static getListOfCompany(name, backend, pageNumber, pageSize) {
            return new RequestChunked("getListOfCompany", [name, backend, pageNumber, pageSize]);
        }
        static exportAddressBook(addressBookConfigName) {
            return new RequestPromise("exportAddressBook", [addressBookConfigName]);
        }
        static importAddressBook(fileName, addressBookConfigName, doClean) {
            return new RequestPromise("importAddressBook", [fileName, addressBookConfigName, doClean]);
        }
        static monitorImportAddressBook() {
            return new RequestPromiseUpdate("monitorImportAddressBook", []);
        }
        static getAllCategories(addressbookType) {
            return new RequestPromiseUpdate("getAllCategories", [addressbookType]);
        }
        static getUserSites() {
            return new RequestPromise("getUserSites", []);
        }
        static getUnreadChat() {
            return new RequestChunked("getUnreadChat", []);
        }
        static isValidSession() {
            return new RequestPromise("isValidSession", []);
        }
        static logout(action) {
            return new RequestPromise("logout", [action]);
        }
        static isGrantedAccess() {
            return new RequestPromise("isGrantedAccess", []);
        }
        static getMaxPageSize() {
            return new RequestPromise("getMaxPageSize", []);
        }
        static getSessionProfile() {
            return new RequestPromise("getSessionProfile", []);
        }
        static getVersion() {
            return new RequestPromise("getVersion", []);
        }
        static chunkedRequest(chunk) {
            return new RequestPromise("chunkedRequest", [chunk]);
        }
        static resetChunkedRequest(requestId) {
            return new RequestPromise("resetChunkedRequest", [requestId]);
        }
        static runChunkedRequest(requestId, fileName) {
            return new RequestPromise("runChunkedRequestFile", [requestId, fileName]);
        }
        static getUserDetail() {
            return new RequestPromiseUpdate("getUserDetail", []).withPriorityOnRestart(1000);
        }
        static useProfile(action) {
            return new RequestPromiseUpdate("useProfile", [action]);
        }
        static useDevice(type, exten, force) {
            return new RequestPromise("useDevice", [type, exten, force]);
        }
        static startConference() {
            return new RequestPromise("startConference", []);
        }
        static getCurrentCalls() {
            return new RequestPromise("getCurrentCalls", []);
        }
        static isInternalNumber(number) {
            return new RequestPromise("isInternalNumber", [number]);
        }
        static getAllServiceCode() {
            return new RequestPromise("getAllServiceCode", []);
        }
        static getUserContactStatus(username) {
            return new RequestPromiseUpdate("getUserContactStatus", [username]);
        }
        static getAddressBookContact(uid, type) {
            return new RequestPromise("getAddressBookContact", [uid, type]);
        }
        static getAddressBookContactByUuid(uid) {
            return new RequestPromise("getAddressBookContactByUuid", [uid]);
        }
        static inboundCallExtension(type, device, enable, force) {
            return new RequestPromise("inboundCallExtension", [type, device, enable, force]);
        }
        static blindTransferMultiChannelToUser(callId, username, channelId) {
            return new RequestPromise("blindTransferMultiChannelToUser", [callId, username, channelId]);
        }
        static setCallData(callId, data) {
            return new RequestPromise("setCallData", [callId, data]);
        }
        static stopRecord(callId) {
            return new RequestPromise("stopRecord", [callId]);
        }
        static startRecord(callId) {
            return new RequestPromise("startRecord", [callId]);
        }
        static updateCallRecordingNote(tableName, id, note, additionalData) {
            return new RequestPromise("updateCallRecordingNote", [tableName, id, note, additionalData]);
        }
        static chanSpyUser(fromDeviceType, fromDevice, usernameToSpy, whisper, beep) {
            return new RequestPromise("chanSpyUser", [fromDeviceType, fromDevice, usernameToSpy, whisper, beep]);
        }
        static getFavouriteContacts() {
            return new RequestChunkedUpdate("getFavouriteContacts", []);
        }
        static addFavouriteItemGroup(name, position) {
            return new RequestPromise("addFavouriteItemGroup", [name, position]);
        }
        static setFavouriteItemGroup(id, name, expanded, position) {
            return new RequestPromise("setFavouriteItemGroup", [id, name, expanded, position]);
        }
        static setFavouriteItemGroups(groups) {
            return new RequestPromise("setFavouriteItemGroups", [groups]);
        }
        static delFavouriteItemGroup(id) {
            return new RequestPromise("delFavouriteItemGroup", [id]);
        }
        static setFavouriteItemContact(uid, type, groupId, position) {
            return new RequestPromise("setFavouriteItemContact", [uid, type, groupId, position]);
        }
        static addFavouriteItemContact(uid, type, groupId, position) {
            return new RequestPromise("addFavouriteItemContact", [uid, type, groupId, position]);
        }
        static delFavouriteItemContactFromGroup(uid, type, groupId) {
            return new RequestPromise("delFavouriteItemContactFromGroup", [uid, type, groupId]);
        }
        static getFavouriteUserGroups() {
            return new RequestChunked("getFavouriteUserGroups", []);
        }
        static delFavouriteItemContactFromGroups(uid, type, groupIds) {
            return new RequestPromise("delFavouriteItemContactFromGroups", [uid, type, groupIds]);
        }
        static addFavouriteItemContactToGroups(uid, type, groupIds) {
            return new RequestPromise("addFavouriteItemContactToGroups", [uid, type, groupIds]);
        }
        static getServicesCallQueue() {
            return new RequestChunkedUpdate("getServicesCallQueue", []);
        }
        static getSkillsetsCallQueue() {
            return new RequestChunkedUpdate("getSkillsetsCallQueue", []);
        }
        static getClientConfig() {
            return new RequestPromise("getClientConfig", []);
        }
        static setClientConfig(value) {
            return new RequestPromise("setClientConfig", [value]);
        }
        static setUserStatusReady(channelId) {
            return new RequestPromise("setUserStatusReady", [channelId]);
        }
        static setUserStatusNotReady(channelId) {
            return new RequestPromise("setUserStatusNotReady", [channelId]);
        }
        static setUserStatusWorkNotReady(channelId) {
            return new RequestPromise("setUserStatusWorkNotReady", [channelId]);
        }
        static setActivityCode(action) {
            return new RequestPromise("setActivityCode", [action]);
        }
        static enterOnConferenceRoom(fromDeviceType, fromDevice) {
            return new RequestPromise("enterOnConferenceRoom", [fromDeviceType, fromDevice]);
        }
        static transferToConferenceRoom(callId) {
            return new RequestPromise("transferToConferenceRoom", [callId]);
        }
        static kickOffAllFromConferenceRoom() {
            return new RequestPromise("kickOffAllFromConferenceRoom", []);
        }
        static getAddressBooks() {
            return new RequestPromise("getAddressBooks", []);
        }
        static addAddressBookContact(backendConfigName, contact) {
            return new RequestPromise("addAddressBookContact", [backendConfigName, contact]);
        }
        static setAddressBookContact(contact) {
            return new RequestPromise("setAddressBookContact", [contact]);
        }
        static setAgentNoteOnAddressBookContact(uuid, agentNote) {
            return new RequestPromise("setAgentNoteOnAddressBookContact", [uuid, agentNote]);
        }
        static mergeAddressBookContact(originUid, contactDestination) {
            return new RequestPromise("mergeAddressBookContact", [originUid, contactDestination]);
        }
        static forgetAddressBookContact(originUid, force) {
            return new RequestPromise("forgetAddressBookContact", [originUid, force]);
        }
        static delAddressBookContact(contactId) {
            return new RequestPromise("delAddressBookContact", [contactId]);
        }
        static acquireWebRTCSession(force) {
            return new RequestPromise("acquireWebRTCSession", [force]);
        }
        static freeWebRTCSession() {
            return new RequestPromise("freeWebRTCSession", []);
        }
        static conferenceAttendeeMute(callId) {
            return new RequestPromise("conferenceAttendeeMute", [callId]);
        }
        static conferenceAttendeeUnmute(callId) {
            return new RequestPromise("conferenceAttendeeUnmute", [callId]);
        }
        static getInternalFieldConfigs() {
            return new RequestPromise("getInternalFieldConfigs", []);
        }
        static getExternalFieldConfigs() {
            return new RequestPromise("getExternalFieldConfigs", []);
        }
        static getPersonalFieldConfigs() {
            return new RequestPromise("getPersonalFieldConfigs", []);
        }
        static searchUserCallHistoryItems(fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize) {
            return new RequestChunked("searchUserCallHistoryItems", [fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize]);
        }
        static setUserCallHistoryItem(ids, read) {
            return new RequestPromise("setUserCallHistoryItem", [ids, read]);
        }
        static delUserCallHistoryItem(ids) {
            return new RequestPromise("delUserCallHistoryItem", [ids]);
        }
        static resetUserCallHistoryItems(transportType) {
            return new RequestPromise("resetUserCallHistoryItems", [transportType]);
        }
        static resetUserCallHistoryItemsByContact(contact) {
            return new RequestPromise("resetUserCallHistoryItemsByContact", [contact]);
        }
        static searchUserChatHistoryItems(contactUsername, insertGreaterThan, pageNumber, pageSize) {
            return new RequestChunked("searchUserChatHistoryItems", [contactUsername, insertGreaterThan, pageNumber, pageSize]);
        }
        static getClassConfigurationPermission() {
            return new RequestPromiseUpdate("getClassConfigurationPermission", []);
        }
        static getConfiguration() {
            return new RequestPromiseUpdate("getConfiguration", []);
        }
        static resetPassword(password) {
            return new RequestPromise("resetPassword", [password]);
        }
        static resetPin(pin) {
            return new RequestPromise("resetPin", [pin]);
        }
        static setDirectoryFields(directoryFields) {
            return new RequestPromise("setDirectoryFields", [directoryFields]);
        }
        static setName(name) {
            return new RequestPromise("setName", [name]);
        }
        static setSurname(surname) {
            return new RequestPromise("setSurname", [surname]);
        }
        static setCallFowardSettings(callFowardSettings) {
            return new RequestPromise("setCallFowardSettings", [callFowardSettings]);
        }
        static setVoicemailSettings(voicemail) {
            return new RequestPromise("setVoicemailSettings", [voicemail]);
        }
        static setConferenceSettings(conference) {
            return new RequestPromise("setConferenceSettings", [conference]);
        }
        static getServiceForCallFoward() {
            return new RequestPromise("getServiceForCallFoward", []);
        }
        static searchFaxDocument(faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize) {
            return new RequestChunkedUpdate("searchFaxDocument", [faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize]);
        }
        static getQueuedFaxDocument() {
            return new RequestChunkedUpdate("getQueuedFaxDocument", []);
        }
        static sendFaxDocument(faxBoxId, numbers, emailToNotify, priority, fileNames) {
            return new RequestPromise("sendFaxDocument", [faxBoxId, numbers, emailToNotify, priority, fileNames]);
        }
        static sendSms(number, message, contact, account) {
            return new RequestPromise("sendSms", [number, message, contact, account]);
        }
        static stopEnqueuedFaxDocument(id) {
            return new RequestPromise("stopEnqueuedFaxDocument", [id]);
        }
        static deleteFaxDocument(id) {
            return new RequestPromise("deleteFaxDocument", [id]);
        }
        static deleteFaxDocumentFromFileSystem(faxDoc) {
            return new RequestPromise("deleteFaxDocumentFromFileSystem", [faxDoc]);
        }
        static updateFaxDocument(id, read, note) {
            return new RequestPromise("updateFaxDocument", [id, read, note]);
        }
        static setCallResult(action) {
            return new RequestPromise("setCallResult", [action]);
        }
        static getUserInteractions() {
            return new RequestChunkedUpdate("getUserInteractions", []);
        }
        static setServiceStatusVisible(service, visible) {
            return new RequestPromise("setServiceStatusVisible", [service, visible]);
        }
        static getWebClientVersion() {
            return new RequestPromiseUpdate("getWebClientVersion", []);
        }
        static getClientParams() {
            return new RequestPromiseUpdate("getClientParams", []);
        }
        static setClientParam(values) {
            return new RequestPromise("setClientParam", [values]);
        }
        static getGeneralParams(params) {
            return new RequestPromise("getGeneralParams", [params]);
        }
        static updateUserInteraction(id, setReadAllRecords = false, status = UserInteractionStatus.CLOSED, action, lastUpdateActivityTime) {
            return new RequestPromise("updateUserInteraction", [id, setReadAllRecords, status, action !== null && action !== void 0 ? action : null, lastUpdateActivityTime !== null && lastUpdateActivityTime !== void 0 ? lastUpdateActivityTime : null]);
        }
        static setPinnedUserInteraction(action) {
            return new RequestPromise("setPinnedUserInteraction", [action]);
        }
        static cleanUserInteractions(interactionsToExclude) {
            return new RequestPromise("cleanUserInteractions", interactionsToExclude ? [interactionsToExclude] : []);
        }
        static getCurrentUserInteractions() {
            return new RequestPromise("getCurrentUserInteractions", []);
        }
        static getAllActivityCode() {
            return new RequestPromise("getAllActivityCode", []);
        }
        static getRoomDeskConfig(roomId) {
            return new RequestChunkedUpdate("getRoomDeskConfig", [roomId]);
        }
        static getActiveServiceCalls(profileId) {
            return new RequestChunkedUpdate("getActiveServiceCalls", [profileId]);
        }
        static servicePickup(fromDeviceType, fromDevice, callId, skillset, mcId = "0") {
            return new RequestPromise("servicePickup", [fromDeviceType, fromDevice, callId, skillset, mcId]);
        }
        static servicePickupPrivateParkedCall(fromDeviceType, fromDevice, callId) {
            return new RequestPromise("servicePickupPrivateParkedCall", [fromDeviceType, fromDevice, callId]);
        }
        static updateWorkingSessionsNote(id, note) {
            return new RequestPromise("updateWorkingSessionsNote", [id, note]);
        }
        static setDND(active) {
            return new RequestPromise("setDND", [active]);
        }
        static tqmParkPrivate(callId, fromDeviceType, fromDevice, service, cli, data) {
            return new RequestPromise("tqmParkPrivate", [callId, fromDeviceType, fromDevice, service, cli, data]);
        }
        static tqmParkPublic(fromDeviceType, fromDevice, number) {
            return new RequestPromise("tqmParkPublic", [fromDeviceType, fromDevice, number]);
        }
        static freeDevice(type, device) {
            return new RequestPromise("freeDevice", [type, device]);
        }
        static isCallTaggable(number) {
            return new RequestPromise("isCallTaggable", [number]);
        }
        static getIntranetSections() {
            return new RequestChunked("getIntranetSections", []);
        }
        static getIntranetPages() {
            return new RequestChunked("getIntranetPages", []);
        }
        static getIntranetPage(id) {
            return new RequestPromise("getIntranetPage", [id]);
        }
        static getIntranetSection(id) {
            return new RequestPromise("getIntranetSection", [id]);
        }
        static addIntranetSection(name, position) {
            return new RequestPromise("addIntranetSection", [name, position]);
        }
        static setIntranetSection(id, name, position) {
            return new RequestPromise("setIntranetSection", [id, name, position]);
        }
        static resetIntranetSectionPosition(sectionIdList) {
            return new RequestPromise("resetIntranetSectionPosition", [sectionIdList]);
        }
        static delIntranetSection(id) {
            return new RequestPromise("delIntranetSection", [id]);
        }
        static getIntranetItemsOnSection(sectionId) {
            return new RequestChunked("getIntranetItemsOnSection", [sectionId]);
        }
        static addIntranetItemToSection(sectionId, description, url, image, position) {
            return new RequestPromise("addIntranetItemToSection", [sectionId, description, url, image, position]);
        }
        static setIntranetItemPosition(uid, sectionId, position) {
            return new RequestPromise("setIntranetItemPosition", [uid, sectionId, position]);
        }
        static setIntranetItem(uid, sectionId, description, url, image, position) {
            return new RequestPromise("setIntranetItem", [uid, sectionId, description, url, image, position]);
        }
        static delIntranetItem(uid) {
            return new RequestPromise("delIntranetItem", [uid]);
        }
        static resetIntranetItemPosition(itemIdList) {
            return new RequestPromise("resetIntranetItemPosition", [itemIdList]);
        }
        static noteSearch(searchCriteria) {
            return new RequestChunked("noteSearch", [searchCriteria]);
        }
        static noteGet(noteUid) {
            return new RequestPromise("noteGet", [noteUid]);
        }
        static noteAdd(note) {
            return new RequestPromise("noteAdd", [note]);
        }
        static noteSet(note) {
            return new RequestPromise("noteSet", [note]);
        }
        static noteContactSet(noteUid, noteContacts) {
            return new RequestPromise("noteContactSet", [noteUid, noteContacts]);
        }
        static noteTagAdd(noteUid, tag) {
            return new RequestPromise("noteTagAdd", [noteUid, tag]);
        }
        static noteTagDel(noteUid, tag) {
            return new RequestPromise("noteTagDel", [noteUid, tag]);
        }
        static noteTagGet() {
            return new RequestChunked("noteTagGet", []);
        }
        static noteSetArchived(noteUid, archived) {
            return new RequestPromise("noteSetArchived", [noteUid, archived]);
        }
        static noteSetDeleted(noteUid, deleted) {
            return new RequestPromise("noteSetDeleted", [noteUid, deleted]);
        }
        static startNoteCounterTotalNotify() {
            return new RequestPromiseUpdate("startNoteCounterTotalNotify", []);
        }
        static startNoteUpdateNotify() {
            return new RequestPromiseUpdate("startNoteUpdateNotify", []);
        }
        static startClientStatusNotify() {
            return new RequestPromiseUpdate("startClientStatusNotify", []);
        }
        static contactNoteExpiredNotify() {
            return new RequestPromiseUpdate("contactNoteExpiredNotify", []);
        }
        static contactNoteReminderNotify() {
            return new RequestPromiseUpdate("contactNoteReminderNotify", []);
        }
        static isSecurePasswordEnabled() {
            return new RequestPromise("isSecurePasswordEnabled", []);
        }
        static abandonedCallsSearchClosed(searchCriteria) {
            return new RequestChunked("abandonedCallsSearchClosed", [searchCriteria]);
        }
        static abandonedCallsSearchOpened(searchCriteria) {
            return new RequestChunkedUpdate("abandonedCallsSearchOpened", [searchCriteria]);
        }
        static abandonedCallsSearchOpenedPaged(searchCriteria, page, size, order) {
            return new RequestChunked("abandonedCallsSearchOpenedPaged", [searchCriteria, page, size, order]);
        }
        static abandonedCallClose(id) {
            return new RequestPromise("abandonedCallClose", [id]);
        }
        static abandonedCallDelete(id) {
            return new RequestPromise("abandonedCallDelete", [id]);
        }
        static abandonedCallRetryExceeded(id) {
            return new RequestPromise("abandonedCallRetryExceeded", [id]);
        }
        static abandonedCallUnlock(id, force) {
            return new RequestPromise("abandonedCallUnlock", [id, force]);
        }
        static abandonedCallLock(id) {
            return new RequestPromise("abandonedCallLock", [id]);
        }
        static abandonedCallUpdateNote(id, startTime, note) {
            return new RequestPromise("abandonedCallUpdateNote", [id, startTime, note]);
        }
        static getAgentsOnServices(serviceCodes) {
            return new RequestChunked("getAgentsOnServices", [serviceCodes]);
        }
        static getAgentsOnServicesCheckMc1002(serviceCodes, checkMc1002Sync) {
            return new RequestChunked("getAgentsOnServicesCheckMc1002", [serviceCodes, checkMc1002Sync]);
        }
        static getServicesByCode(serviceCodes) {
            return new RequestChunked("getServicesByCode", [serviceCodes]);
        }
        static getServices() {
            return new RequestChunked("getServices", []);
        }
        static setWinWebVersion(version) {
            return new RequestPromise("setWinWebVersion", [version]);
        }
        static setClientDetail(id, platform, so, release, clientVersion) {
            return new RequestPromise("setClientDetail", [id, platform, so, release, clientVersion]);
        }
        static setAppDetail(action) {
            return new RequestPromise("setAppDetail", [action]);
        }
        static ackCallMessage(callId, counter) {
            return new RequestPromise("ackCallMessage", [callId, counter]);
        }
        static ticketSearch(action) {
            return new RequestChunkedUpdate("ticketSearch", [action]);
        }
        static ticketEscalatedSearch(action) {
            return new RequestChunkedUpdate("ticketEscalatedSearch", [action]);
        }
        static ticketSearchForMerge(action) {
            return new RequestChunkedUpdate("ticketSearchForMerge", [action]);
        }
        static ticketSearchForLink(action) {
            return new RequestChunkedUpdate("ticketSearchForLink", [action]);
        }
        static ticketGet(ticketId, withUpdatePolicy) {
            return new RequestPromiseUpdate("ticketGet", [ticketId, withUpdatePolicy]);
        }
        static ticketGetPreview(ticketId) {
            return new RequestPromise("ticketGetPreview", [ticketId]);
        }
        static ticketGetArticles(ticketId) {
            return new RequestChunkedUpdate("ticketGetArticles", [ticketId]);
        }
        static ticketGetArticlesFB(ticketId, serviceCode, callLink, postMessageId) {
            return new RequestChunkedUpdate("ticketGetArticlesFB", [ticketId, serviceCode, callLink, postMessageId]);
        }
        static ticketGetArticlesLight(ticketId, articleIds, serviceCode, callLink) {
            return new RequestChunkedUpdate("ticketGetArticlesLight", [ticketId, articleIds, serviceCode, callLink]);
        }
        static ticketGetArticlesLightFB(ticketId, articleIds, serviceCode, callLink) {
            return new RequestChunkedUpdate("ticketGetArticlesLightFB", [ticketId, articleIds, serviceCode, callLink]);
        }
        static ticketGetArticlesTreeFB(ticketId) {
            return new RequestPromise("ticketGetArticlesTreeFB", [ticketId]);
        }
        static ticketGetNewArticlesTreeFB(ticketId, lastOwnerViewAt) {
            return new RequestPromise("ticketGetNewArticlesTreeFB", [ticketId, lastOwnerViewAt]);
        }
        static ticketGetArticlesPreview(ticketId) {
            return new RequestChunked("ticketGetArticlesPreview", [ticketId]);
        }
        static ticketGetArticlesPreviewByArticleId(firstArticleId, lastArticleId) {
            return new RequestChunked("ticketGetArticlesPreviewByArticleId", [firstArticleId, lastArticleId]);
        }
        static ticketGetHistory(ticketId) {
            return new RequestChunkedUpdate("ticketGetHistory", [ticketId]);
        }
        static ticketGetLinks(ticketId, serviceCodes) {
            return new RequestChunkedUpdate("ticketGetLinks", [ticketId, serviceCodes]);
        }
        static ticketAddLinks(ticketTargetId, ticketSourceNumber, linkType) {
            return new RequestPromise("ticketAddLinks", [ticketTargetId, ticketSourceNumber, linkType]);
        }
        static ticketDeleteLinks(ticketTargetId, ticketSourceId, linkType) {
            return new RequestPromise("ticketDeleteLinks", [ticketTargetId, ticketSourceId, linkType]);
        }
        static ticketAdd(ticket) {
            return new RequestPromise("ticketAdd", [ticket]);
        }
        static ticketAddWithAttachments(ticket, attachments) {
            return new RequestPromise("ticketAddWithAttachments", [ticket, attachments]);
        }
        static ticketMerge(ticketMaster, ticketSlaveId) {
            return new RequestPromise("ticketMerge", [ticketMaster, ticketSlaveId]);
        }
        static ticketUpdate(ticket) {
            return new RequestPromise("ticketUpdate", [ticket]);
        }
        static ticketMultipleUpdate(ticketIdList, field, value) {
            return new RequestPromise("ticketMultipleUpdate", [ticketIdList, field, value]);
        }
        static ticketSetViewByOwner(ticket) {
            return new RequestPromise("ticketSetViewByOwner", [ticket]);
        }
        static ticketAddArticle(ticket) {
            return new RequestPromise("ticketAddArticle", [ticket]);
        }
        static ticketAddArticleWithAttachments(article, attachments) {
            return new RequestPromise("ticketAddArticleWithAttachments", [article, attachments]);
        }
        static ticketSignatureGet(serviceCode) {
            return new RequestPromise("ticketSignatureGet", [serviceCode]);
        }
        static ticketGetEmailAddresses() {
            return new RequestPromise("ticketGetEmailAddresses", []);
        }
        static ticketSetRead(ticketId) {
            return new RequestPromise("ticketSetRead", [ticketId]);
        }
        static ticketGetFieldConfigs() {
            return new RequestPromise("ticketGetFieldConfigs", []);
        }
        static ticketGetInboundEmailAddressOnService(serviceCode) {
            return new RequestPromise("ticketGetInboundEmailAddressOnService", [serviceCode]);
        }
        static ticketGetSettings() {
            return new RequestPromise("ticketGetSettings", []);
        }
        static ticketStartSession(ticketId, interactionId, action) {
            return new RequestPromise("ticketStartSession", [ticketId, interactionId, action]);
        }
        static ticketStopSession(ticketId, interactionId, action) {
            return new RequestPromise("ticketStopSession", [ticketId, interactionId, action]);
        }
        static ticketIsAcdOnAgentBar(ticketId) {
            return new RequestPromise("ticketIsAcdOnAgentBar", [ticketId]);
        }
        static getWebrtcConfiguration() {
            return new RequestPromise("getWebrtcConfiguration", []);
        }
        static lookupSearch(value) {
            return new RequestChunked("lookupSearch", [value]);
        }
        static callLookupSearch(value) {
            return new RequestChunked("callLookupSearch", [value]);
        }
        static startChatSessionNotify() {
            return new RequestPromiseUpdate("startChatSessionNotify", []);
        }
        static sendChatEventMessage(chatId, message) {
            return new RequestPromise("sendChatEventMessage", [chatId, message]);
        }
        static searchChatMessageChannel(action) {
            return new RequestChunkedUpdate("searchChatMessageChannel", [action]);
        }
        static chatAgentReceivedMessage(action) {
            return new RequestPromise("chatAgentReceivedMessage", [action]);
        }
        static chatAgentReadMessage(action) {
            return new RequestPromise("chatAgentReadMessage", [action]);
        }
        static channelInfoHistoryItemSearch(action) {
            return new RequestChunked("channelInfoHistoryItemSearch", [action]);
        }
        static chatUpdateFile(file) {
            return new RequestPromise("chatUpdateFile", [file]);
        }
        static channelInfoHistoryFileSearch(action) {
            return new RequestChunked("channelInfoHistoryFileSearch", [action]);
        }
        static widgetJourneySearch(action) {
            return new RequestChunkedUpdate("widgetJourneySearch", [action]);
        }
        static moveInteractionToContact(moveInteraction) {
            return new RequestPromise("moveInteractionToContact", [moveInteraction]);
        }
        static _internalTest_updateContactOnInteraction(moveInteraction) {
            return new RequestPromise("_internalTest_updateContactOnInteraction", [moveInteraction]);
        }
        static getServicesByChannel(action) {
            return new RequestChunked("getServicesByChannel", [action]);
        }
        static transferChannelToService(callId, serviceCode) {
            return new RequestPromise("transferChannelToService", [callId, serviceCode]);
        }
        static setOutboundCallBlocked(active) {
            return new RequestPromise("setOutboundCallBlocked", [active]);
        }
        static chatSendRecapOfSession(action) {
            return new RequestPromise("chatSendRecapOfSession", [action]);
        }
        static callbackRequestSearchClosed(searchAction) {
            return new RequestChunked("callbackRequestSearchClosed", [searchAction]);
        }
        static callbackRequestSearchOpen(searchAction) {
            return new RequestChunkedUpdate("callbackRequestSearchOpen", [searchAction]);
        }
        static callbackRequestsSearchOpenPaginated(searchAction, page, size, order) {
            return new RequestChunked("callbackRequestsSearchOpenPaginated", [searchAction, page, size, order]);
        }
        static callbackRequestClose(id) {
            return new RequestPromise("callbackRequestClose", [id]);
        }
        static callbackRequestDelete(id) {
            return new RequestPromise("callbackRequestDelete", [id]);
        }
        static callbackRequestUnlock(id, force) {
            return new RequestPromise("callbackRequestUnlock", [id, force]);
        }
        static callbackRequestLock(id) {
            return new RequestPromise("callbackRequestLock", [id]);
        }
        static callbackRequestUpdateNote(id, startTime, note) {
            return new RequestPromise("callbackRequestUpdateNote", [id, startTime, note]);
        }
        static getInsightUrl() {
            return new RequestPromise("getInsightUrl", []);
        }
        static searchADSAlarmHistory() {
            return new RequestChunked("searchADSAlarmHistory", []);
        }
        static startDelayedTaskNotify() {
            return new RequestPromiseUpdate("startDelayedTaskNotify", []);
        }
        static startADSAlarmNotify() {
            return new RequestPromiseUpdate("startADSAlarmNotify", []);
        }
        static validateAddressBookContactField(uid, field, position) {
            return new RequestPromise("validateAddressBookContactField", [uid, field, position]);
        }
        static setCensusResult(userInteractionId, result, backend, number) {
            return new RequestPromise("setCensusResult", (backend !== null && backend !== void 0 ? backend : null) ? [userInteractionId, result, backend, number !== null && number !== void 0 ? number : null] : [userInteractionId, result]);
        }
        static getCustomerJourney(uidContact, page, size, agentFilter) {
            return new RequestChunked("getCustomerJourney", [uidContact, page, size, agentFilter]);
        }
        static getCustomerJourneyInteractionAmounts(uidContact, agentFilter) {
            return new RequestPromise("getCustomerJourneyInteractionAmounts", [uidContact, agentFilter]);
        }
        static searchLoggedProfileByChannel(action) {
            return new RequestChunked("searchLoggedProfileByChannel", [action]);
        }
        static usersThatWaitToSetNR() {
            return new RequestChunkedUpdate("usersThatWaitToSetNR", []);
        }
        static acceptRequestToSetNR(username) {
            return new RequestPromise("acceptRequestToSetNR", [username]);
        }
        static denyRequestToSetNR(username) {
            return new RequestPromise("denyRequestToSetNR", [username]);
        }
        static setUserStatusNotReadyAskingToSupervisor() {
            return new RequestPromise("setUserStatusNotReadyAskingToSupervisor", []);
        }
        static resetRequestNRToSupervisor() {
            return new RequestPromise("resetRequestNRToSupervisor", []);
        }
        static getActiveLicense() {
            return new RequestPromise("getActiveLicense", []);
        }
        static getListOfNumbersWithInternationalPrefix(number) {
            return new RequestPromise("getListOfNumbersWithInternationalPrefix", [number]);
        }
        static searchFilterGetFieldByScope(scope) {
            return new RequestPromise("searchFilterGetFieldByScope", [scope]);
        }
        static searchFilterSearch(scopeApplication, stringToSearch) {
            return new RequestPromise("searchFilterSearch", [scopeApplication, stringToSearch]);
        }
        static searchFilterGetById(searchFilterId) {
            return new RequestPromise("searchFilterGetById", [searchFilterId]);
        }
        static searchFilterGetByIdList(searchFilterIdList) {
            return new RequestPromise("searchFilterGetByIdList", [searchFilterIdList]);
        }
        static searchFilterAdd(searchFilter) {
            return new RequestPromise("searchFilterAdd", [searchFilter]);
        }
        static searchFilterUpdate(searchFilter) {
            return new RequestPromise("searchFilterUpdate", [searchFilter]);
        }
        static searchFilterDelete(searchFilterId) {
            return new RequestPromise("searchFilterDelete", [searchFilterId]);
        }
        static searchFilterOnUserByApplication(scopeApplication) {
            return new RequestPromise("searchFilterOnUserByApplication", [scopeApplication]);
        }
        static searchFilterAddOnUserByApplication(searchFilterId, scopeApplication) {
            return new RequestPromise("searchFilterAddOnUserByApplication", [searchFilterId, scopeApplication]);
        }
        static searchFilterDeleteOnUserByApplication(searchFilterId, scopeApplication) {
            return new RequestPromise("searchFilterDeleteOnUserByApplication", [searchFilterId, scopeApplication]);
        }
        static sendCommandResponse(commandResult) {
            return new RequestPromise("sendCommandResponse", [commandResult]);
        }
        static publishNewIncomingCall(callEvent) {
            return new RequestPromise("publishNewIncomingCall", [callEvent]);
        }
        static publishNewOutgoingCall(callEvent) {
            return new RequestPromise("publishNewOutgoingCall", [callEvent]);
        }
        static publishEvent(event) {
            return new RequestPromise("publishEvent", [event]);
        }
        static searchFilterEnable(searchFilterId) {
            return new RequestPromise("searchFilterEnable", [searchFilterId]);
        }
        static searchFilterDisable(searchFilterId) {
            return new RequestPromise("searchFilterDisable", [searchFilterId]);
        }
        static searchCampaign(action) {
            return new RequestChunked("searchCampaign", [action]);
        }
        static startCampaign(action) {
            return new RequestPromise("startCampaign", [action]);
        }
        static stopCampaign(action) {
            return new RequestPromise("stopCampaign", [action]);
        }
        static getCampaignStatus() {
            return new RequestChunkedUpdate("getCampaignStatus", []);
        }
        static searchCampaignProcessedByRunId(action) {
            return new RequestChunked("searchCampaignProcessedByRunId", [action]);
        }
        static exportCampaignRunIdDetail(runEndtime, runId, type) {
            return new RequestPromise("exportCampaignRunIdDetail", [runEndtime, runId, type]);
        }
        static createCampaign(action) {
            return new RequestPromise("createCampaign", [action]);
        }
        static setCampaign(campaign) {
            return new RequestPromise("setCampaign", [campaign]);
        }
        static getCampaign(id) {
            return new RequestPromise("getCampaign", [id]);
        }
        static updateImgProfile(img) {
            return new RequestPromise("updateImgProfile", [img]);
        }
        static ticketGetArticlesTimeAccounting(ticketId) {
            return new RequestPromise("ticketGetArticlesTimeAccounting", [ticketId]);
        }
        static ticketGetMergedArticlesTimeAccounting(ticketArticleIdList) {
            return new RequestPromise("ticketGetMergedArticlesTimeAccounting", [ticketArticleIdList]);
        }
        static ticketGetArticleTimeAccounting(ticketId) {
            return new RequestPromise("ticketGetArticleTimeAccounting", [ticketId]);
        }
        static knowledgeBaseSearch(knowledgeBaseId, categoryId, query) {
            return new RequestPromise("knowledgeBaseSearch", [knowledgeBaseId, categoryId, query]);
        }
        static knowledgeBaseSetAnswerOnCall(interactionId, callId, answerId, answerUrl) {
            return new RequestPromise("knowledgeBaseSetAnswerOnCall", [interactionId, callId, answerId, answerUrl]);
        }
        static knowledgeBaseSetNotFoundAnswerOnCall(interactionId, callId) {
            return new RequestPromise("knowledgeBaseSetNotFoundAnswerOnCall", [interactionId, callId]);
        }
        static knowledgeBaseSetNoAnswerOnCall(interactionId, callId) {
            return new RequestPromise("knowledgeBaseSetNoAnswerOnCall", [interactionId, callId]);
        }
        static knowledgeBaseSetAnswerOnTicket(ticketId, answerId, answerUrl) {
            return new RequestPromise("knowledgeBaseSetAnswerOnTicket", [ticketId, answerId, answerUrl]);
        }
        static knowledgeBaseSetNoAnswerOnTicket(ticketId) {
            return new RequestPromise("knowledgeBaseSetNoAnswerOnTicket", [ticketId]);
        }
        static knowledgeBaseSetCategoryOnTicket(ticketId, categoryId, categoryUrl) {
            return new RequestPromise("knowledgeBaseSetCategoryOnTicket", [ticketId, categoryId, categoryUrl]);
        }
        static knowledgeBaseGetAnswerHits(answerId) {
            return new RequestPromise("knowledgeBaseGetAnswerHits", [answerId]);
        }
        static ticketAddArticleByCopy(originalArticle, destinationTicketId) {
            return new RequestPromise("ticketAddArticleByCopy", [originalArticle, destinationTicketId]);
        }
        static ticketUpdateArticleIsInternal(ticketArticleId, internal) {
            return new RequestPromise("ticketUpdateArticleIsInternal", [ticketArticleId, internal]);
        }
        static omnideskCreateMeeting(action) {
            return new RequestPromise("omnideskCreateMeeting", [action]);
        }
        static omnideskCreateScheduledMeeting(action) {
            return new RequestPromise("omnideskCreateScheduledMeeting", [action]);
        }
        static omnideskSetScheduledMeeting(action) {
            return new RequestPromise("omnideskSetScheduledMeeting", [action]);
        }
        static omnideskDeleteScheduledMeetingEvent(action) {
            return new RequestPromise("omnideskDeleteScheduledMeetingEvent", [action]);
        }
        static omnideskGetMeeting(action) {
            return new RequestPromise("omnideskGetMeeting", [action]);
        }
        static omnideskSearchMeeting(action) {
            return new RequestChunked("omnideskSearchMeeting", [action]);
        }
        static omnideskGetParticipantToken(action) {
            return new RequestPromise("omnideskGetParticipantToken", [action]);
        }
        static omnideskGetJwt(action) {
            return new RequestPromise("omnideskGetJwt", [action]);
        }
        static omnideskAddParticipantToMeeting(action) {
            return new RequestPromise("omnideskAddParticipantToMeeting", [action]);
        }
        static omnideskResetParticipantToken(action) {
            return new RequestPromise("omnideskResetParticipantToken", [action]);
        }
        static omnideskLeaveMeeting(meetingParticipantId) {
            return new RequestPromise("omnideskLeaveMeeting", [meetingParticipantId]);
        }
        static omnideskCloseMeeting(meetingId) {
            return new RequestPromise("omnideskCloseMeeting", [meetingId]);
        }
        static omnideskGenerateLinkToMeeting(meetingId) {
            return new RequestPromise("omnideskGenerateLinkToMeeting", [meetingId]);
        }
        static omnideskRemoveParticipantFromMeeting(action) {
            return new RequestPromise("omnideskRemoveParticipantFromMeeting", [action]);
        }
        static omnideskResumeMeeting(action) {
            return new RequestPromise("omnideskResumeMeeting", [action]);
        }
        static startOmnideskCounterTotalNotify() {
            return new RequestPromiseUpdate("startOmnideskCounterTotalNotify", []);
        }
        static omnideskScheduledMeetingNotify() {
            return new RequestPromiseUpdate("omnideskScheduledMeetingNotify", []);
        }
        static omnideskUpdateScheduleMeeting(action) {
            return new RequestPromise("omnideskUpdateScheduleMeeting", [action]);
        }
        static omnideskCreateChatGroupForMeeting(action) {
            return new RequestPromise("omnideskCreateChatGroupForMeeting", [action]);
        }
        static omnideskCreateChatGroupForMeetingAndSendGroupId(action) {
            return new RequestPromise("omnideskCreateChatGroupForMeetingAndSendGroupId", [action]);
        }
        static omnideskResetLostMeetingOnContact(contact) {
            return new RequestPromise("omnideskResetLostMeetingOnContact", [contact]);
        }
        static sendClientCommandResponse(commandResult) {
            return new RequestPromise("sendClientCommandResponse", [commandResult]);
        }
        static getUserDetailLight() {
            return new RequestPromise("getUserDetailLight", []);
        }
        static sendFeedback(action) {
            return new RequestPromise("sendFeedback", [action]);
        }
        static setPresenceStatus(action) {
            return new RequestPromise("setPresenceStatus", [action]);
        }
        static customerPortalIsCustomerRegistered(customerEmail) {
            return new RequestPromise("customerPortalIsCustomerRegistered", [customerEmail]);
        }
        static customerPortalGetCustomerSettings(t4youUid) {
            return new RequestPromise("customerPortalGetCustomerSettings", [t4youUid]);
        }
        static customerPortalSetCustomerSettings(cps) {
            return new RequestPromise("customerPortalSetCustomerSettings", [cps]);
        }
        static customerPortalRestoreCustomerPassword(cps) {
            return new RequestPromise("customerPortalRestoreCustomerPassword", [cps]);
        }
        static setStandby(action) {
            return new RequestPromise("setStandby", [action]);
        }
        static dialATXferOnGenericDevice(action) {
            return new RequestPromise("dialATXferOnGenericDevice", [action]);
        }
        static cancelTransferOnGenericDevice(action) {
            return new RequestPromise("cancelTransferOnGenericDevice", [action]);
        }
        static getCurrentSkillsetsWithProfiles() {
            return new RequestPromiseUpdate("getCurrentSkillsetsWithProfiles", []);
        }
        static setOutOfService(action) {
            return new RequestPromise("setOutOfService", [action]);
        }
        static setPhoneManagerActive(action) {
            return new RequestPromise("setPhoneManagerActive", [action]);
        }
        static ticketUpdateWithReminder(ticket, reminderTicketId) {
            return new RequestPromise("ticketUpdateWithReminder", [ticket, reminderTicketId]);
        }
        static ticketCloseById(ticketId) {
            return new RequestPromise("ticketCloseById", [ticketId]);
        }
        static ticketAddManualReminderAndUpdate(ticket, remindedArticle) {
            return new RequestPromise("ticketAddManualReminderAndUpdate", [ticket, remindedArticle]);
        }
        static clearTicketIdOnCall(callId) {
            return new RequestPromise("clearTicketIdOnCall", [callId]);
        }
        static getSupportVersion() {
            return new RequestPromise("getSupportVersion", []);
        }
        static getSupportFeatures(version) {
            return new RequestPromise("getSupportFeatures", [version]);
        }
        static updateTqmConfigurations(action) {
            return new RequestPromise("updateTqmConfigurations", [action]);
        }
        static getThemesAvailable() {
            return new RequestPromise("getThemesAvailable", []);
        }
        static setCustomThemeStyleValues(action) {
            return new RequestPromise("setCustomThemeStyleValues", [action]);
        }
        static getCampaignToNotify() {
            return new RequestChunkedUpdate("getCampaignToNotify", []);
        }
        static setCampaignNotifiedRead(campaignId) {
            return new RequestPromise("setCampaignNotifiedRead", [campaignId]);
        }
    }

    function exceptionInitializer(exception) {
        try {
            return exceptionInitializer$1(exception, Errors);
        }
        catch (e) {
            return e;
        }
    }
    const DEFAULT_LOWER_PRIORITY_METHODS = ["getUserContactStatus"];
    const DEFAULT_METHOD_TIMEOUT = {
        getUserDetail: 30000,
        exportAddressBook: 3600000,
        importAddressBook: 300000,
        sendFeedback: 120000,
        useProfile: 30000,
        getFavouriteContacts: 30000,
        updateImgProfile: 30000,
        getAgentsOnServicesCheckMc1002: 60000,
        ticketSearch: 15000,
        ticketEscalatedSearch: 15000,
        ticketSearchForMerge: 15000,
        ticketSearchForLink: 15000,
        ticketGet: 15000,
        ticketGetPreview: 15000,
        ticketGetArticles: 120000,
        ticketGetArticlesLight: 120000,
        ticketGetArticlesPreview: 15000,
        ticketGetArticlesPreviewByArticleId: 15000,
        ticketGetHistory: 15000,
        ticketGetLinks: 15000,
        ticketAddLinks: 15000,
        ticketDeleteLinks: 15000,
        ticketAdd: 15000,
        ticketAddWithAttachments: 15000,
        ticketMerge: 15000,
        ticketUpdate: 15000,
        ticketMultipleUpdate: 15000,
        ticketSetViewByOwner: 15000,
        ticketAddArticle: 15000,
        ticketAddArticleWithAttachments: 15000,
        ticketSignatureGet: 15000,
        ticketGetEmailAddresses: 15000,
        ticketSetRead: 15000,
        ticketGetFieldConfigs: 15000,
        ticketGetInboundEmailAddressOnService: 15000,
        ticketGetSettings: 15000,
        ticketStartSession: 15000,
        ticketStopSession: 15000,
        ticketIsAcdOnAgentBar: 15000,
        ticketGetArticlesTimeAccounting: 120000,
        ticketGetMergedArticlesTimeAccounting: 120000,
        ticketGetArticleTimeAccounting: 120000,
        ticketAddArticleByCopy: 120000,
        omnideskCreateMeeting: 120000,
        omnideskCreateScheduledMeeting: 120000,
        omnideskSetScheduledMeeting: 120000,
        omnideskDeleteScheduledMeetingEvent: 120000,
        omnideskGetMeeting: 120000,
        omnideskGetJwt: 120000,
        omnideskSearchMeeting: 30000,
        omnideskGetParticipantToken: 120000,
        omnideskAddParticipantToMeeting: 120000,
        omnideskResetParticipantToken: 120000,
        omnideskLeaveMeeting: 120000,
        omnideskCloseMeeting: 120000,
        omnideskGenerateLinkToMeeting: 120000,
        omnideskRemoveParticipantFromMeeting: 120000,
        omnideskResumeMeeting: 120000,
    };
    class WebapiClientMethodExecutor extends MethodExecutor {
        constructor(
        webapiClientMethod) {
            super(webapiClientMethod.client);
            this.webapiClientMethod = webapiClientMethod;
        }
        _buildResponse(request) {
            return this.webapiClientMethod._buildResponse(request);
        }
        loginForce() {
            return this.webapiClientMethod.loginForce();
        }
        loginCustom(customData, rememberMe, requestTimeout) {
            return this.webapiClientMethod.loginCustom(customData, rememberMe, requestTimeout);
        }
        loginByAccessToken(accessToken, rememberMe, requestTimeout) {
            return this.webapiClientMethod.loginByAccessToken(accessToken, rememberMe, requestTimeout);
        }
        login(username, password, rememberMe, requestTimeout) {
            return this.webapiClientMethod.login(username, password, rememberMe, requestTimeout);
        }
        logoutAndExit(action, requestTimeout) {
            return this.webapiClientMethod.logoutAndExit(action, requestTimeout);
        }
        startCallNotify(requestTimeout) {
            return this.webapiClientMethod.startCallNotify(requestTimeout);
        }
        stopCallNotify() {
            return this.webapiClientMethod.stopCallNotify();
        }
        startClientCommandNotify(requestTimeout) {
            return this.webapiClientMethod.startClientCommandNotify();
        }
        stopClientCommandNotify() {
            return this.webapiClientMethod.stopClientCommandNotify();
        }
        startVideoEchoTest(audio, video, videoContainer, mediaConfiguration, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.startVideoEchoTest(audio, video, videoContainer, mediaConfiguration), requestTimeout).result);
        }
        dial(dialParam, videoContainer, mediaConfiguration, userInteractionAction, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.dial(dialParam, videoContainer, mediaConfiguration, userInteractionAction), requestTimeout).result);
        }
        answerOnChannel(channelType, callId, media, customFields, videoContainer, mediaConfiguration, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.answerOnChannel(channelType, callId, media, customFields, videoContainer, mediaConfiguration), requestTimeout).result);
        }
        cancel(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.cancelCall(callId), requestTimeout).result);
        }
        hold(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.holdCall(callId), requestTimeout).result);
        }
        unhold(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.unholdCall(callId), requestTimeout).result);
        }
        attendedTransfer(callId, heldCallId, media, fields, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.attendedTransfer(callId, heldCallId, media, fields), requestTimeout).result);
        }
        blindTransfer(callId, accessCode, number, data, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.blindTransfer(callId, accessCode, number, data), requestTimeout).result);
        }
        sendDTMF(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendDTMF(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap), requestTimeout).result);
        }
        mute(callId, media, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.muteCall(callId, media), requestTimeout).result);
        }
        unmute(callId, media, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.unmuteCall(callId, media), requestTimeout).result);
        }
        createUserInteraction(createUserInteraction, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.createUserInteraction(createUserInteraction), requestTimeout).result);
        }
        removeCallFromUserInteraction(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.removeCallFromUserInteraction(callId), requestTimeout).result);
        }
        refreshToken(username, accessToken, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.refreshToken(username, accessToken), requestTimeout).result);
        }
        resumeChatToken(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resumeChatToken(), requestTimeout).result);
        }
        getRefreshToken(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getRefreshToken(), requestTimeout).result);
        }
        searchUsers(name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.searchUsers(name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive), requestTimeout).toLiveResult();
        }
        searchUsersExtended(addressbookType, fields, exclusive, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.searchUsersExtended(addressbookType, fields, exclusive, pageNumber, pageSize), requestTimeout).toLiveResult();
        }
        searchUsersExtendedByBackend(addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.searchUsersExtendedByBackend(addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize), requestTimeout).toLiveResult();
        }
        getListOfCompany(name, backend, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getListOfCompany(name, backend, pageNumber, pageSize), requestTimeout);
        }
        exportAddressBook(addressBookConfigName, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.exportAddressBook(addressBookConfigName), requestTimeout).result);
        }
        importAddressBook(fileName, addressBookConfigName, doClean, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.importAddressBook(fileName, addressBookConfigName, doClean), requestTimeout).result);
        }
        monitorImportAddressBook(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.monitorImportAddressBook(), requestTimeout).response;
        }
        getAllCategories(addressbookType, requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getAllCategories(addressbookType), requestTimeout).response;
        }
        getUserSites(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getUserSites(), requestTimeout).result);
        }
        getUnreadChat(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getUnreadChat(), requestTimeout);
        }
        isValidSession(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.isValidSession(), requestTimeout).result);
        }
        logout(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.logout(action), requestTimeout).result);
        }
        isGrantedAccess(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.isGrantedAccess(), requestTimeout).result);
        }
        getMaxPageSize(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getMaxPageSize(), requestTimeout).result);
        }
        getSessionProfile(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getSessionProfile(), requestTimeout).result);
        }
        getVersion(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getVersion(), requestTimeout).result);
        }
        chunkedRequest(chunk, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chunkedRequest(chunk), requestTimeout).result);
        }
        resetChunkedRequest(requestId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetChunkedRequest(requestId), requestTimeout).result);
        }
        runChunkedRequest(requestId, fileName, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.runChunkedRequest(requestId, fileName), requestTimeout).result);
        }
        getUserDetail(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getUserDetail(), requestTimeout).response;
        }
        useProfile(action, requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.useProfile(action), requestTimeout).response;
        }
        useDevice(type, exten, force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.useDevice(type, exten, force), requestTimeout).result);
        }
        startConference(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.startConference(), requestTimeout).result);
        }
        getCurrentCalls(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getCurrentCalls(), requestTimeout).result);
        }
        isInternalNumber(number, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.isInternalNumber(number), requestTimeout).result);
        }
        getAllServiceCode(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getAllServiceCode(), requestTimeout).result);
        }
        getUserContactStatus(username, requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getUserContactStatus(username), requestTimeout).response;
        }
        getAddressBookContact(uid, type, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getAddressBookContact(uid, type), requestTimeout).result);
        }
        getAddressBookContactByUuid(uid, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getAddressBookContactByUuid(uid), requestTimeout).result);
        }
        inboundCallExtension(type, device, enable, force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.inboundCallExtension(type, device, enable, force), requestTimeout).result);
        }
        blindTransferMultiChannelToUser(callId, username, channelId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.blindTransferMultiChannelToUser(callId, username, channelId), requestTimeout).result);
        }
        setCallData(callId, data, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCallData(callId, data), requestTimeout).result);
        }
        stopRecord(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.stopRecord(callId), requestTimeout).result);
        }
        startRecord(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.startRecord(callId), requestTimeout).result);
        }
        updateCallRecordingNote(tableName, id, note, additionalData, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.updateCallRecordingNote(tableName, id, note, additionalData), requestTimeout).result);
        }
        chanSpyUser(fromDeviceType, fromDevice, usernameToSpy, whisper, beep, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chanSpyUser(fromDeviceType, fromDevice, usernameToSpy, whisper, beep), requestTimeout).result);
        }
        getFavouriteContacts(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getFavouriteContacts(), requestTimeout).toLiveResult();
        }
        addFavouriteItemGroup(name, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addFavouriteItemGroup(name, position), requestTimeout).result);
        }
        setFavouriteItemGroup(id, name, expanded, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setFavouriteItemGroup(id, name, expanded, position), requestTimeout).result);
        }
        setFavouriteItemGroups(groups, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setFavouriteItemGroups(groups), requestTimeout).result);
        }
        delFavouriteItemGroup(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delFavouriteItemGroup(id), requestTimeout).result);
        }
        setFavouriteItemContact(uid, type, groupId, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setFavouriteItemContact(uid, type, groupId, position), requestTimeout).result);
        }
        addFavouriteItemContact(uid, type, groupId, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addFavouriteItemContact(uid, type, groupId, position), requestTimeout).result);
        }
        delFavouriteItemContactFromGroup(uid, type, groupId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delFavouriteItemContactFromGroup(uid, type, groupId), requestTimeout).result);
        }
        getFavouriteUserGroups(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getFavouriteUserGroups(), requestTimeout);
        }
        delFavouriteItemContactFromGroups(uid, type, groupIds, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delFavouriteItemContactFromGroups(uid, type, groupIds), requestTimeout).result);
        }
        addFavouriteItemContactToGroups(uid, type, groupIds, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addFavouriteItemContactToGroups(uid, type, groupIds), requestTimeout).result);
        }
        getServicesCallQueue(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getServicesCallQueue(), requestTimeout).response;
        }
        getSkillsetsCallQueue(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getSkillsetsCallQueue(), requestTimeout).response;
        }
        getClientConfig(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getClientConfig(), requestTimeout).result);
        }
        setClientConfig(value, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setClientConfig(value), requestTimeout).result);
        }
        setUserStatusReady(channelId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setUserStatusReady(channelId), requestTimeout).result);
        }
        setUserStatusNotReady(channelId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setUserStatusNotReady(channelId), requestTimeout).result);
        }
        setUserStatusWorkNotReady(channelId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setUserStatusWorkNotReady(channelId), requestTimeout).result);
        }
        setActivityCode(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setActivityCode(action), requestTimeout).result);
        }
        enterOnConferenceRoom(fromDeviceType, fromDevice, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.enterOnConferenceRoom(fromDeviceType, fromDevice), requestTimeout).result);
        }
        transferToConferenceRoom(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.transferToConferenceRoom(callId), requestTimeout).result);
        }
        kickOffAllFromConferenceRoom(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.kickOffAllFromConferenceRoom(), requestTimeout).result);
        }
        getAddressBooks(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getAddressBooks(), requestTimeout).result);
        }
        addAddressBookContact(backendConfigName, contact, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addAddressBookContact(backendConfigName, contact), requestTimeout).result);
        }
        setAddressBookContact(contact, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setAddressBookContact(contact), requestTimeout).result);
        }
        setAgentNoteOnAddressBookContact(uuid, agentNote, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setAgentNoteOnAddressBookContact(uuid, agentNote), requestTimeout).result);
        }
        mergeAddressBookContact(originUid, contactDestination, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.mergeAddressBookContact(originUid, contactDestination), requestTimeout).result);
        }
        forgetAddressBookContact(originUid, force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.forgetAddressBookContact(originUid, force), requestTimeout).result);
        }
        delAddressBookContact(contactId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delAddressBookContact(contactId), requestTimeout).result);
        }
        acquireWebRTCSession(force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.acquireWebRTCSession(force), requestTimeout).result);
        }
        freeWebRTCSession(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.freeWebRTCSession(), requestTimeout).result);
        }
        conferenceAttendeeMute(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.conferenceAttendeeMute(callId), requestTimeout).result);
        }
        conferenceAttendeeUnmute(callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.conferenceAttendeeUnmute(callId), requestTimeout).result);
        }
        getInternalFieldConfigs(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getInternalFieldConfigs(), requestTimeout).result);
        }
        getExternalFieldConfigs(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getExternalFieldConfigs(), requestTimeout).result);
        }
        getPersonalFieldConfigs(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getPersonalFieldConfigs(), requestTimeout).result);
        }
        searchUserCallHistoryItems(fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchUserCallHistoryItems(fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize), requestTimeout);
        }
        setUserCallHistoryItem(ids, read, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setUserCallHistoryItem(ids, read), requestTimeout).result);
        }
        delUserCallHistoryItem(ids, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delUserCallHistoryItem(ids), requestTimeout).result);
        }
        resetUserCallHistoryItems(transportType, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetUserCallHistoryItems(transportType), requestTimeout).result);
        }
        resetUserCallHistoryItemsByContact(contact, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetUserCallHistoryItemsByContact(contact), requestTimeout).result);
        }
        searchUserChatHistoryItems(contactUsername, insertGreaterThan, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchUserChatHistoryItems(contactUsername, insertGreaterThan, pageNumber, pageSize), requestTimeout);
        }
        getClassConfigurationPermission(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getClassConfigurationPermission(), requestTimeout).toLiveResult();
        }
        getConfiguration(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getConfiguration(), requestTimeout).toLiveResult();
        }
        resetPassword(password, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetPassword(password), requestTimeout).result);
        }
        resetPin(pin, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetPin(pin), requestTimeout).result);
        }
        setDirectoryFields(directoryFields, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setDirectoryFields(directoryFields), requestTimeout).result);
        }
        setName(name, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setName(name), requestTimeout).result);
        }
        setSurname(surname, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setSurname(surname), requestTimeout).result);
        }
        setCallFowardSettings(callFowardSettings, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCallFowardSettings(callFowardSettings), requestTimeout).result);
        }
        setVoicemailSettings(voicemail, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setVoicemailSettings(voicemail), requestTimeout).result);
        }
        setConferenceSettings(conference, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setConferenceSettings(conference), requestTimeout).result);
        }
        getServiceForCallFoward(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getServiceForCallFoward(), requestTimeout).result);
        }
        searchFaxDocument(faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.searchFaxDocument(faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize), requestTimeout).toLiveResult();
        }
        getQueuedFaxDocument(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getQueuedFaxDocument(), requestTimeout).toLiveResult();
        }
        sendFaxDocument(faxBoxId, numbers, emailToNotify, priority, fileNames, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendFaxDocument(faxBoxId, numbers, emailToNotify, priority, fileNames), requestTimeout).result);
        }
        sendSms(number, message, contact, account, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendSms(number, message, contact, account), requestTimeout).result);
        }
        stopEnqueuedFaxDocument(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.stopEnqueuedFaxDocument(id), requestTimeout).result);
        }
        deleteFaxDocument(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.deleteFaxDocument(id), requestTimeout).result);
        }
        deleteFaxDocumentFromFileSystem(faxDoc, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.deleteFaxDocumentFromFileSystem(faxDoc), requestTimeout).result);
        }
        updateFaxDocument(id, read, note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.updateFaxDocument(id, read, note), requestTimeout).result);
        }
        setCallResult(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCallResult(action), requestTimeout).result);
        }
        getUserInteractions(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getUserInteractions(), requestTimeout).toLiveResult();
        }
        setServiceStatusVisible(service, visible, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setServiceStatusVisible(service, visible), requestTimeout).result);
        }
        getWebClientVersion(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getWebClientVersion(), requestTimeout).toLiveResult();
        }
        getClientParams(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getClientParams(), requestTimeout).toLiveResult();
        }
        setClientParam(values, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setClientParam(values), requestTimeout).result);
        }
        getGeneralParams(params, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getGeneralParams(params), requestTimeout).result);
        }
        updateUserInteraction(id, setReadAllRecords = false, status = UserInteractionStatus.CLOSED, action, lastUpdateActivityTime, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.updateUserInteraction(id, setReadAllRecords, status, action, lastUpdateActivityTime), requestTimeout).result);
        }
        setPinnedUserInteraction(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setPinnedUserInteraction(action), requestTimeout).result);
        }
        cleanUserInteractions(interactionsToExclude, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.cleanUserInteractions(interactionsToExclude ? interactionsToExclude : []), requestTimeout).result);
        }
        getCurrentUserInteractions(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getCurrentUserInteractions(), requestTimeout).result);
        }
        getAllActivityCode(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getAllActivityCode(), requestTimeout).result);
        }
        getRoomDeskConfig(roomId, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getRoomDeskConfig(roomId), requestTimeout).toLiveResult();
        }
        getActiveServiceCalls(profileId, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getActiveServiceCalls(profileId), requestTimeout).toLiveResult();
        }
        servicePickup(fromDeviceType, fromDevice, callId, skillset, mcId = "0", requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.servicePickup(fromDeviceType, fromDevice, callId, skillset, mcId), requestTimeout).result);
        }
        servicePickupPrivateParkedCall(fromDeviceType, fromDevice, callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.servicePickupPrivateParkedCall(fromDeviceType, fromDevice, callId), requestTimeout).result);
        }
        updateWorkingSessionsNote(id, note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.updateWorkingSessionsNote(id, note), requestTimeout).result);
        }
        setDND(active, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setDND(active), requestTimeout).result);
        }
        tqmParkPrivate(callId, fromDeviceType, fromDevice, service, cli, data, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.tqmParkPrivate(callId, fromDeviceType, fromDevice, service, cli, data), requestTimeout).result);
        }
        tqmParkPublic(fromDeviceType, fromDevice, number, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.tqmParkPublic(fromDeviceType, fromDevice, number), requestTimeout).result);
        }
        freeDevice(type, device, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.freeDevice(type, device), requestTimeout).result);
        }
        isCallTaggable(number, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.isCallTaggable(number), requestTimeout).result);
        }
        getIntranetSections(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getIntranetSections(), requestTimeout);
        }
        getIntranetPages(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getIntranetPages(), requestTimeout);
        }
        getIntranetPage(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getIntranetPage(id), requestTimeout).result);
        }
        getIntranetSection(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getIntranetSection(id), requestTimeout).result);
        }
        addIntranetSection(name, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addIntranetSection(name, position), requestTimeout).result);
        }
        setIntranetSection(id, name, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setIntranetSection(id, name, position), requestTimeout).result);
        }
        resetIntranetSectionPosition(sectionIdList, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetIntranetSectionPosition(sectionIdList), requestTimeout).result);
        }
        delIntranetSection(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delIntranetSection(id), requestTimeout).result);
        }
        getIntranetItemsOnSection(sectionId, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getIntranetItemsOnSection(sectionId), requestTimeout);
        }
        addIntranetItemToSection(sectionId, description, url, image, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.addIntranetItemToSection(sectionId, description, url, image, position), requestTimeout).result);
        }
        setIntranetItemPosition(uid, sectionId, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setIntranetItemPosition(uid, sectionId, position), requestTimeout).result);
        }
        setIntranetItem(uid, sectionId, description, url, image, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setIntranetItem(uid, sectionId, description, url, image, position), requestTimeout).result);
        }
        delIntranetItem(uid, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.delIntranetItem(uid), requestTimeout).result);
        }
        resetIntranetItemPosition(itemIdList, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetIntranetItemPosition(itemIdList), requestTimeout).result);
        }
        noteSearch(searchCriteria, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.noteSearch(searchCriteria), requestTimeout);
        }
        noteGet(noteUid, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteGet(noteUid), requestTimeout).result);
        }
        noteAdd(note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteAdd(note), requestTimeout).result);
        }
        noteSet(note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteSet(note), requestTimeout).result);
        }
        noteContactSet(noteUid, noteContacts, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteContactSet(noteUid, noteContacts), requestTimeout).result);
        }
        noteTagAdd(noteUid, tag, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteTagAdd(noteUid, tag), requestTimeout).result);
        }
        noteTagDel(noteUid, tag, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteTagDel(noteUid, tag), requestTimeout).result);
        }
        noteTagGet(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.noteTagGet(), requestTimeout);
        }
        noteSetArchived(noteUid, archived, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteSetArchived(noteUid, archived), requestTimeout).result);
        }
        noteSetDeleted(noteUid, deleted, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.noteSetDeleted(noteUid, deleted), requestTimeout).result);
        }
        startNoteCounterTotalNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startNoteCounterTotalNotify(), requestTimeout).response;
        }
        startNoteUpdateNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startNoteUpdateNotify(), requestTimeout).response;
        }
        startClientStatusNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startClientStatusNotify(), requestTimeout).response;
        }
        omnideskScheduledMeetingNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.omnideskScheduledMeetingNotify(), requestTimeout).response;
        }
        contactNoteExpiredNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.contactNoteExpiredNotify(), requestTimeout).response;
        }
        contactNoteReminderNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.contactNoteReminderNotify(), requestTimeout).response;
        }
        isSecurePasswordEnabled(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.isSecurePasswordEnabled(), requestTimeout).result);
        }
        abandonedCallsSearchClosed(searchCriteria, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.abandonedCallsSearchClosed(searchCriteria), requestTimeout);
        }
        abandonedCallsSearchOpened(searchCriteria, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.abandonedCallsSearchOpened(searchCriteria), requestTimeout).toLiveResult();
        }
        abandonedCallsSearchOpenedPaged(searchCriteria, page, size, order, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.abandonedCallsSearchOpenedPaged(searchCriteria, page, size, order), requestTimeout);
        }
        abandonedCallClose(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallClose(id), requestTimeout).result);
        }
        abandonedCallDelete(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallDelete(id), requestTimeout).result);
        }
        abandonedCallRetryExceeded(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallRetryExceeded(id), requestTimeout).result);
        }
        abandonedCallUnlock(id, force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallUnlock(id, force), requestTimeout).result);
        }
        abandonedCallLock(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallLock(id), requestTimeout).result);
        }
        abandonedCallUpdateNote(id, startTime, note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.abandonedCallUpdateNote(id, startTime, note), requestTimeout).result);
        }
        getAgentsOnServices(serviceCodes, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getAgentsOnServices(serviceCodes), requestTimeout);
        }
        getAgentsOnServicesCheckMc1002(serviceCodes, checkMc1002Sync, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getAgentsOnServicesCheckMc1002(serviceCodes, checkMc1002Sync), requestTimeout);
        }
        getServicesByCode(serviceCodes, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getServicesByCode(serviceCodes), requestTimeout);
        }
        getServices(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getServices(), requestTimeout);
        }
        setWinWebVersion(version, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setWinWebVersion(version), requestTimeout).result);
        }
        setClientDetail(id, platform, so, release, clientVersion, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setClientDetail(id, platform, so, release, clientVersion), requestTimeout).result);
        }
        setAppDetail(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setAppDetail(action), requestTimeout).result);
        }
        ackCallMessage(callId, counter, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ackCallMessage(callId, counter), requestTimeout).result);
        }
        ticketSearch(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketSearch(action), requestTimeout).toLiveResult();
        }
        ticketEscalatedSearch(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketEscalatedSearch(action), requestTimeout).toLiveResult();
        }
        ticketSearchForMerge(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketSearchForMerge(action), requestTimeout).toLiveResult();
        }
        ticketSearchForLink(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketSearchForLink(action), requestTimeout).toLiveResult();
        }
        ticketGet(ticketId, withUpdatePolicy, requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.ticketGet(ticketId, withUpdatePolicy), requestTimeout).toLiveResult();
        }
        ticketGetPreview(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetPreview(ticketId), requestTimeout).result);
        }
        ticketGetArticles(ticketId, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketGetArticles(ticketId), requestTimeout).toLiveResult();
        }
        ticketGetArticlesLight(ticketId, articleIds, serviceCode, callLink, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketGetArticlesLight(ticketId, articleIds, serviceCode, callLink), requestTimeout).toLiveResult();
        }
        ticketGetArticlesPreview(ticketId, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.ticketGetArticlesPreview(ticketId), requestTimeout);
        }
        ticketGetArticlesPreviewByArticleId(firstArticleId, lastArticleId, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.ticketGetArticlesPreviewByArticleId(firstArticleId, lastArticleId), requestTimeout);
        }
        ticketGetHistory(ticketId, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketGetHistory(ticketId), requestTimeout).toLiveResult();
        }
        ticketGetLinks(ticketId, serviceCodes, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.ticketGetLinks(ticketId, serviceCodes), requestTimeout).toLiveResult();
        }
        ticketAddLinks(ticketTargetId, ticketSourceNumber, linkType, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketAddLinks(ticketTargetId, ticketSourceNumber, linkType), requestTimeout).result);
        }
        ticketDeleteLinks(ticketTargetId, ticketSourceId, linkType, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketDeleteLinks(ticketTargetId, ticketSourceId, linkType), requestTimeout).result);
        }
        ticketAdd(ticket, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketAdd(ticket), requestTimeout).result);
        }
        ticketAddWithAttachments(ticket, attachments, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketAddWithAttachments(ticket, attachments), requestTimeout).result);
        }
        ticketMerge(ticketMaster, ticketSlaveId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketMerge(ticketMaster, ticketSlaveId), requestTimeout).result);
        }
        ticketUpdate(ticket, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketUpdate(ticket), requestTimeout).result);
        }
        ticketMultipleUpdate(ticketIdList, field, value, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketMultipleUpdate(ticketIdList, field, value), requestTimeout).result);
        }
        ticketSetViewByOwner(ticket, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketSetViewByOwner(ticket), requestTimeout).result);
        }
        ticketAddArticle(ticket, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketAddArticle(ticket), requestTimeout).result);
        }
        ticketAddArticleWithAttachments(article, attachments, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketAddArticleWithAttachments(article, attachments), requestTimeout).result);
        }
        ticketSignatureGet(serviceCode, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketSignatureGet(serviceCode), requestTimeout).result);
        }
        ticketGetEmailAddresses(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetEmailAddresses()).result);
        }
        ticketSetRead(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketSetRead(ticketId), requestTimeout).result);
        }
        ticketGetFieldConfigs(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetFieldConfigs(), requestTimeout).result);
        }
        ticketGetInboundEmailAddressOnService(serviceCode, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetInboundEmailAddressOnService(serviceCode), requestTimeout).result);
        }
        ticketGetSettings(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetSettings(), requestTimeout).result);
        }
        ticketStartSession(ticketId, interactionId, action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketStartSession(ticketId, interactionId, action), requestTimeout).result);
        }
        ticketStopSession(ticketId, interactionId, action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketStopSession(ticketId, interactionId, action), requestTimeout).result);
        }
        ticketIsAcdOnAgentBar(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketIsAcdOnAgentBar(ticketId), requestTimeout).result);
        }
        getWebrtcConfiguration(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getWebrtcConfiguration(), requestTimeout).result);
        }
        lookupSearch(value, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.lookupSearch(value), requestTimeout);
        }
        callLookupSearch(value, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.callLookupSearch(value), requestTimeout);
        }
        startChatSessionNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startChatSessionNotify(), requestTimeout).toLiveResult();
        }
        sendChatEventMessage(chatId, message, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendChatEventMessage(chatId, message), requestTimeout).result);
        }
        searchChatMessageChannel(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.searchChatMessageChannel(action), requestTimeout).toLiveResult();
        }
        chatAgentReceivedMessage(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chatAgentReceivedMessage(action), requestTimeout).result);
        }
        chatAgentReadMessage(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chatAgentReadMessage(action), requestTimeout).result);
        }
        channelInfoHistoryItemSearch(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.channelInfoHistoryItemSearch(action), requestTimeout);
        }
        chatUpdateFile(file, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chatUpdateFile(file), requestTimeout).result);
        }
        channelInfoHistoryFileSearch(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.channelInfoHistoryFileSearch(action), requestTimeout);
        }
        widgetJourneySearch(action, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.widgetJourneySearch(action), requestTimeout).toLiveResult();
        }
        moveInteractionToContact(moveInteraction, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.moveInteractionToContact(moveInteraction), requestTimeout).result);
        }
        _internalTest_updateContactOnInteraction(moveInteraction, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory._internalTest_updateContactOnInteraction(moveInteraction), requestTimeout).result);
        }
        getServicesByChannel(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getServicesByChannel(action), requestTimeout);
        }
        transferChannelToService(callId, serviceCode, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.transferChannelToService(callId, serviceCode), requestTimeout).result);
        }
        setOutboundCallBlocked(active, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setOutboundCallBlocked(active), requestTimeout).result);
        }
        chatSendRecapOfSession(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.chatSendRecapOfSession(action), requestTimeout).result);
        }
        callbackRequestSearchClosed(searchAction, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.callbackRequestSearchClosed(searchAction), requestTimeout);
        }
        callbackRequestSearchOpen(searchAction, requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.callbackRequestSearchOpen(searchAction), requestTimeout).toLiveResult();
        }
        callbackRequestsSearchOpenPaginated(searchAction, page, size, order, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.callbackRequestsSearchOpenPaginated(searchAction, page, size, order), requestTimeout);
        }
        callbackRequestClose(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.callbackRequestClose(id), requestTimeout).result);
        }
        callbackRequestDelete(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.callbackRequestDelete(id), requestTimeout).result);
        }
        callbackRequestUnlock(id, force, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.callbackRequestUnlock(id, force), requestTimeout).result);
        }
        callbackRequestLock(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.callbackRequestLock(id), requestTimeout).result);
        }
        callbackRequestUpdateNote(id, startTime, note, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.callbackRequestUpdateNote(id, startTime, note), requestTimeout).result);
        }
        getInsightUrl(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getInsightUrl(), requestTimeout).result);
        }
        searchADSAlarmHistory(requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchADSAlarmHistory(), requestTimeout);
        }
        startDelayedTaskNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startDelayedTaskNotify(), requestTimeout).response;
        }
        startADSAlarmNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startADSAlarmNotify(), requestTimeout).response;
        }
        validateAddressBookContactField(uid, field, position, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.validateAddressBookContactField(uid, field, position), requestTimeout).result);
        }
        setCensusResult(userInteractionId, result, backend, number, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCensusResult(userInteractionId, result, backend, number), requestTimeout).result);
        }
        getCustomerJourney(uidContact, page, size, agentFilter, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.getCustomerJourney(uidContact, page, size, agentFilter), requestTimeout);
        }
        getCustomerJourneyInteractionAmounts(uidContact, agentFilter, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getCustomerJourneyInteractionAmounts(uidContact, agentFilter), requestTimeout).result);
        }
        searchLoggedProfileByChannel(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchLoggedProfileByChannel(action), requestTimeout);
        }
        usersThatWaitToSetNR(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.usersThatWaitToSetNR(), requestTimeout).toLiveResult();
        }
        acceptRequestToSetNR(username, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.acceptRequestToSetNR(username), requestTimeout).result);
        }
        denyRequestToSetNR(username, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.denyRequestToSetNR(username), requestTimeout).result);
        }
        setUserStatusNotReadyAskingToSupervisor(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setUserStatusNotReadyAskingToSupervisor(), requestTimeout).result);
        }
        resetRequestNRToSupervisor(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.resetRequestNRToSupervisor(), requestTimeout).result);
        }
        getActiveLicense(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getActiveLicense(), requestTimeout).result);
        }
        getListOfNumbersWithInternationalPrefix(number, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getListOfNumbersWithInternationalPrefix(number), requestTimeout).result);
        }
        searchFilterGetFieldByScope(scope, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterGetFieldByScope(scope), requestTimeout).result);
        }
        searchFilterSearch(scopeApplication, stringToSearch, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterSearch(scopeApplication, stringToSearch), requestTimeout).result);
        }
        searchFilterGetById(searchFilterId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterGetById(searchFilterId), requestTimeout).result);
        }
        searchFilterGetByIdList(searchFilterIdList, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterGetByIdList(searchFilterIdList), requestTimeout).result);
        }
        searchFilterAdd(searchFilter, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterAdd(searchFilter), requestTimeout).result);
        }
        searchFilterUpdate(searchFilter, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterUpdate(searchFilter), requestTimeout).result);
        }
        searchFilterDelete(searchFilterId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterDelete(searchFilterId), requestTimeout).result);
        }
        searchFilterOnUserByApplication(scopeApplication, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterOnUserByApplication(scopeApplication), requestTimeout).result);
        }
        searchFilterAddOnUserByApplication(searchFilterId, scopeApplication, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterAddOnUserByApplication(searchFilterId, scopeApplication), requestTimeout).result);
        }
        searchFilterDeleteOnUserByApplication(searchFilterId, scopeApplication, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterDeleteOnUserByApplication(searchFilterId, scopeApplication), requestTimeout).result);
        }
        sendCommandResponse(commandResult, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendCommandResponse(commandResult), requestTimeout).result);
        }
        publishNewIncomingCall(callEvent, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.publishNewIncomingCall(callEvent), requestTimeout).result);
        }
        publishNewOutgoingCall(callEvent, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.publishNewOutgoingCall(callEvent), requestTimeout).result);
        }
        publishEvent(event, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.publishEvent(event), requestTimeout).result);
        }
        searchFilterEnable(searchFilterId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterEnable(searchFilterId), requestTimeout).result);
        }
        searchFilterDisable(searchFilterId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.searchFilterDisable(searchFilterId), requestTimeout).result);
        }
        searchCampaign(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchCampaign(action), requestTimeout);
        }
        startCampaign(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.startCampaign(action), requestTimeout).result);
        }
        stopCampaign(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.stopCampaign(action), requestTimeout).result);
        }
        getCampaignStatus(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getCampaignStatus(), requestTimeout).toLiveResult();
        }
        searchCampaignProcessedByRunId(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.searchCampaignProcessedByRunId(action), requestTimeout);
        }
        exportCampaignRunIdDetail(runEndtime, runId, type, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.exportCampaignRunIdDetail(runEndtime, runId, type), requestTimeout).result);
        }
        createCampaign(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.createCampaign(action), requestTimeout).result);
        }
        setCampaign(campaign, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCampaign(campaign), requestTimeout).result);
        }
        getCampaign(id, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getCampaign(id), requestTimeout).result);
        }
        updateImgProfile(img, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.updateImgProfile(img), requestTimeout).result);
        }
        ticketGetArticlesTimeAccounting(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetArticlesTimeAccounting(ticketId), requestTimeout).result);
        }
        ticketGetMergedArticlesTimeAccounting(ticketArticleIdList, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetMergedArticlesTimeAccounting(ticketArticleIdList), requestTimeout).result);
        }
        ticketGetArticleTimeAccounting(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.ticketGetArticleTimeAccounting(ticketId), requestTimeout).result);
        }
        knowledgeBaseSearch(knowledgeBaseId, categoryId, query, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSearch(knowledgeBaseId, categoryId, query), requestTimeout).result);
        }
        knowledgeBaseSetAnswerOnCall(interactionId, callId, answerId, answerUrl, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetAnswerOnCall(interactionId, callId, answerId, answerUrl), requestTimeout).result);
        }
        knowledgeBaseSetNotFoundAnswerOnCall(interactionId, callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetNotFoundAnswerOnCall(interactionId, callId), requestTimeout).result);
        }
        knowledgeBaseSetNoAnswerOnCall(interactionId, callId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetNoAnswerOnCall(interactionId, callId), requestTimeout).result);
        }
        knowledgeBaseSetAnswerOnTicket(ticketId, answerId, answerUrl, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetAnswerOnTicket(ticketId, answerId, answerUrl), requestTimeout).result);
        }
        knowledgeBaseSetNoAnswerOnTicket(ticketId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetNoAnswerOnTicket(ticketId), requestTimeout).result);
        }
        knowledgeBaseSetCategoryOnTicket(ticketId, categoryId, categoryUrl, requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseSetCategoryOnTicket(ticketId, categoryId, categoryUrl), requestTimeout);
        }
        knowledgeBaseGetAnswerHits(answerId, requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.knowledgeBaseGetAnswerHits(answerId), requestTimeout);
        }
        ticketAddArticleByCopy(originalArticle, destinationTicketId, requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.ticketAddArticleByCopy(originalArticle, destinationTicketId), requestTimeout);
        }
        omnideskUpdateScheduleMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskUpdateScheduleMeeting(action), requestTimeout).result);
        }
        omnideskCreateChatGroupForMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskCreateChatGroupForMeeting(action), requestTimeout).result);
        }
        omnideskCreateChatGroupForMeetingAndSendGroupId(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskCreateChatGroupForMeetingAndSendGroupId(action), requestTimeout).result);
        }
        omnideskResetLostMeetingOnContact(contact, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskResetLostMeetingOnContact(contact), requestTimeout).result);
        }
        omnideskCreateMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskCreateMeeting(action), requestTimeout).result);
        }
        omnideskCreateScheduledMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskCreateScheduledMeeting(action), requestTimeout).result);
        }
        omnideskSetScheduledMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskSetScheduledMeeting(action), requestTimeout).result);
        }
        omnideskDeleteScheduledMeetingEvent(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskDeleteScheduledMeetingEvent(action), requestTimeout).result);
        }
        omnideskGetMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskGetMeeting(action), requestTimeout).result);
        }
        omnideskSearchMeeting(action, requestTimeout) {
            return this.executeRequestChunked(WebapiMethodFactory.omnideskSearchMeeting(action), requestTimeout);
        }
        omnideskGetParticipantToken(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskGetParticipantToken(action), requestTimeout).result);
        }
        omnideskGetJwt(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskGetJwt(action), requestTimeout).result);
        }
        omnideskAddParticipantToMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskAddParticipantToMeeting(action), requestTimeout).result);
        }
        omnideskResetParticipantToken(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskResetParticipantToken(action), requestTimeout).result);
        }
        omnideskLeaveMeeting(meetingParticipantId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskLeaveMeeting(meetingParticipantId), requestTimeout).result);
        }
        omnideskCloseMeeting(meetingId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskCloseMeeting(meetingId), requestTimeout).result);
        }
        omnideskGenerateLinkToMeeting(meetingId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskGenerateLinkToMeeting(meetingId), requestTimeout).result);
        }
        omnideskRemoveParticipantFromMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskRemoveParticipantFromMeeting(action), requestTimeout).result);
        }
        omnideskResumeMeeting(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.omnideskResumeMeeting(action), requestTimeout).result);
        }
        startOmnideskCounterTotalNotify(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.startOmnideskCounterTotalNotify(), requestTimeout).response;
        }
        sendClientCommandResponse(commandResult, requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.sendClientCommandResponse(commandResult), requestTimeout);
        }
        getUserDetailLight(requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.getUserDetailLight(), requestTimeout);
        }
        sendFeedback(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.sendFeedback(action), requestTimeout).result);
        }
        setPresenceStatus(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setPresenceStatus(action), requestTimeout).result);
        }
        getPresenceStatusCustom(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getPresenceStatusCustom(), requestTimeout).response;
        }
        setStandby(action) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setStandby(action)).result);
        }
        dialATXferOnGenericDevice(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.dialATXferOnGenericDevice(action), requestTimeout).result);
        }
        cancelTransferOnGenericDevice(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.cancelTransferOnGenericDevice(action), requestTimeout).result);
        }
        getCurrentSkillsetsWithProfiles(requestTimeout) {
            return this.executeRequestPromiseUpdate(WebapiMethodFactory.getCurrentSkillsetsWithProfiles(), requestTimeout).response;
        }
        setOutOfService(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setOutOfService(action), requestTimeout).result);
        }
        setPhoneManagerActive(action, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setPhoneManagerActive(action), requestTimeout).result);
        }
        clearTicketIdOnCall(callId, requestTimeout) {
            return this.executeRequestPromise(WebapiMethodFactory.clearTicketIdOnCall(callId), requestTimeout).result.toPromise();
        }
        getSupportVersion(requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.getSupportVersion(), requestTimeout).result);
        }
        getCampaignToNotify(requestTimeout) {
            return this.executeRequestChunkedUpdate(WebapiMethodFactory.getCampaignToNotify(), requestTimeout).toLiveResult();
        }
        setCampaignNotifiedRead(campaignId, requestTimeout) {
            return toPromise$1(this.executeRequestPromise(WebapiMethodFactory.setCampaignNotifiedRead(campaignId), requestTimeout).result);
        }
    }

    class WebapiConfig {
        constructor(config, prefix) {
            this.sessionParams = null;
            this.logConfig = new WebapiClientLogConfig();
            this.storageUrl = null;
            this.storageTimeout = 5000;
            this.retryOptions = new RetryOptions();
            this.heartbeatInterval = 5000;
            this.rememberMe = true;
            this.selfManagedLogin = true;
            this.requestEnableUntilReconnect = false;
            this.connectionRevivalLowerPriorityMethos = [...DEFAULT_LOWER_PRIORITY_METHODS];
            this.requestTimeout = 15000;
            this.mappedRequestTimeout = Object.assign({}, DEFAULT_METHOD_TIMEOUT);
            this.loginTimeout = 60000;
            this.cookie_path = null;
            this.phoneManagerActive = true;
            this.multisession = false;
            this.remoteCommandHandler = null;
            if (!config)
                return;
            loadConfig(prefix, WebapiConfig.CHECK_OPTIONS, this, config);
        }
    }
    WebapiConfig.CHECK_OPTIONS = {
        mandatory: {
            url: (urlValue) => {
                let url = stringCheck(urlValue);
                if (isEmpty(url)) {
                    return undefined;
                }
                else {
                    url = url.replace(/^(http:|https:|ws:|wss:)\/\//i, "http://");
                    if (!/^http:\/\//i.test(url)) {
                        url = "http://" + url;
                    }
                    try {
                        if (/^https:/i.test(document.location.protocol)) {
                            url = url.replace(/^http:\/\//i, "https://");
                        }
                    }
                    catch (e) { }
                    return url;
                }
            },
            userAgent: (userAgentConfig, prefix) => {
                const userAgent = objectCheck(userAgentConfig);
                return userAgent ? new WebapiUserAgentConfig(userAgent, arrayConcat(prefix, ["agent"])) : userAgent;
            },
        },
        optional: {
            sessionParams: (value) => {
                const objectValue = typeof value == "object" ? value : undefined;
                if (!!objectValue) {
                    delete value["force"];
                    delete value["access_token"];
                    delete value["deviceid"];
                    delete value["jsessionid"];
                }
                return objectValue;
            },
            storageUrl: (url) => WebapiConfig.CHECK_OPTIONS.mandatory.url(url),
            retryOptions: (retry, prefix) => {
                const value = objectCheck(retry);
                return value ? new RetryOptions(value, arrayConcat(prefix, ["retryOptions"])) : value;
            },
            heartbeatInterval: numberCheck,
            rememberMe: booleanCheck,
            selfManagedLogin: booleanCheck,
            requestEnableUntilReconnect: booleanCheck,
            phoneManagerActive: booleanCheck,
            multisession: booleanCheck,
            remoteCommandHandler: functionCheck,
            requestTimeout: numberCheck,
            connectionRevivalLowerPriorityMethos: objectCheck,
            mappedRequestTimeout: objectCheck,
            loginTimeout: numberCheck,
            cookie_path: stringCheck,
            logConfig: (retry, prefix) => {
                const value = objectCheck(retry);
                return value ? new WebapiClientLogConfig(value, arrayConcat(prefix, ["logConfig"])) : value;
            },
        },
    };
    class WebapiClientLogConfig extends LogConfig {
        constructor(options, prefix) {
            super(options, prefix);
        }
    }
    class WebapiUserAgentConfig {
        constructor(options, prefix) {
            if (!options)
                return;
            loadConfig(prefix, WebapiUserAgentConfig.CHECK_OPTIONS, this, options);
        }
        isTVox() {
            var _a, _b;
            const uaType = this.type.trim().toLowerCase();
            const uaDescription = (_a = this.description) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
            return "tvoxclient" === uaType || ((_b = ("custom" === uaType && (uaDescription === null || uaDescription === void 0 ? void 0 : uaDescription.startsWith("tvox sdk")))) !== null && _b !== void 0 ? _b : false);
        }
    }
    WebapiUserAgentConfig.CHECK_OPTIONS = {
        mandatory: {
            type: stringCheck,
            version: stringCheck,
        },
        optional: {
            description: stringCheck,
        },
    };

    class LocalStoreManager {
        constructor() {
            this.syncKeys = [];
            this._dbEvent = new Subject();
            this.reservedKeys = ["sync_keys", "addToSyncKeys", "removeFromSyncKeys", "getSessionStorage", "setSessionStorage", "addToSessionStorage", "removeFromSessionStorage", "clearAllSessionsStorage", "raiseDBEvent"];
            this.sessionStorageTransferHandler = (event) => {
                if (!event.newValue)
                    return;
                if (event.key == "getSessionStorage") {
                    if (sessionStorage.length) {
                        localStorage.setItem("setSessionStorage", JSON.stringify(sessionStorage, MapOrSet_toJSON));
                        localStorage.removeItem("setSessionStorage");
                    }
                }
                else if (event.key == "setSessionStorage") {
                    if (!this.syncKeys.length)
                        this.loadSyncKeys();
                    let data = JSON.parse(event.newValue);
                    for (let key in data) {
                        if (this.syncKeysContains(key))
                            sessionStorage.setItem(key, data[key]);
                    }
                }
                else if (event.key == "addToSessionStorage") {
                    let data = JSON.parse(event.newValue);
                    this.addToSessionStorageHelper(data["data"], data["key"]);
                }
                else if (event.key == "removeFromSessionStorage") {
                    this.removeFromSessionStorageHelper(event.newValue);
                }
                else if (event.key == "clearAllSessionsStorage" && sessionStorage.length) {
                    this.clearInstanceSessionStorage();
                }
                else if (event.key == "addToSyncKeys") {
                    this.addToSyncKeysHelper(event.newValue);
                }
                else if (event.key == "removeFromSyncKeys") {
                    this.removeFromSyncKeysHelper(event.newValue);
                }
                else if (event.key == "raiseDBEvent") {
                    this.raiseDBEventHelper(event.newValue);
                }
            };
        }
        initialiseStorageSyncListener() {
            if (LocalStoreManager.syncListenerInitialised == true)
                return;
            LocalStoreManager.syncListenerInitialised = true;
            window.addEventListener("storage", this.sessionStorageTransferHandler, false);
            this.syncSessionStorage();
        }
        deinitialiseStorageSyncListener() {
            window.removeEventListener("storage", this.sessionStorageTransferHandler, false);
            LocalStoreManager.syncListenerInitialised = false;
        }
        syncSessionStorage() {
            localStorage.setItem("getSessionStorage", "_dummy");
            localStorage.removeItem("getSessionStorage");
        }
        clearAllStorage() {
            this.clearAllSessionsStorage();
            this.clearLocalStorage();
        }
        clearAllSessionsStorage() {
            this.clearInstanceSessionStorage();
            localStorage.removeItem(LocalStoreManager.DBKEY_SYNC_KEYS);
            localStorage.setItem("clearAllSessionsStorage", "_dummy");
            localStorage.removeItem("clearAllSessionsStorage");
        }
        clearInstanceSessionStorage() {
            sessionStorage.clear();
            this.syncKeys = [];
        }
        clearLocalStorage() {
            localStorage.clear();
        }
        addToSessionStorage(data, key) {
            this.addToSessionStorageHelper(data, key);
            this.addToSyncKeysBackup(key);
            localStorage.setItem("addToSessionStorage", JSON.stringify({ key: key, data: data }, MapOrSet_toJSON));
            localStorage.removeItem("addToSessionStorage");
        }
        addToSessionStorageHelper(data, key) {
            this.addToSyncKeysHelper(key);
            sessionStorage.setItem(key, data);
        }
        removeFromSessionStorage(keyToRemove) {
            this.removeFromSessionStorageHelper(keyToRemove);
            this.removeFromSyncKeysBackup(keyToRemove);
            localStorage.setItem("removeFromSessionStorage", keyToRemove);
            localStorage.removeItem("removeFromSessionStorage");
        }
        removeFromSessionStorageHelper(keyToRemove) {
            sessionStorage.removeItem(keyToRemove);
            this.removeFromSyncKeysHelper(keyToRemove);
        }
        testForInvalidKeys(key) {
            if (!key)
                throw new Error("key cannot be empty");
            if (this.reservedKeys.some((x) => x == key))
                throw new Error(`The storage key "${key}" is reserved and cannot be used. Please use a different key`);
        }
        syncKeysContains(key) {
            return this.syncKeys.some((x) => x == key);
        }
        loadSyncKeys() {
            if (this.syncKeys.length)
                return;
            this.syncKeys = this.getSyncKeysFromStorage();
        }
        getSyncKeysFromStorage(defaultValue = []) {
            let data = localStorage.getItem(LocalStoreManager.DBKEY_SYNC_KEYS);
            if (data == null)
                return defaultValue;
            else
                return JSON.parse(data);
        }
        addToSyncKeys(key) {
            this.addToSyncKeysHelper(key);
            this.addToSyncKeysBackup(key);
            localStorage.setItem("addToSyncKeys", key);
            localStorage.removeItem("addToSyncKeys");
        }
        addToSyncKeysBackup(key) {
            let storedSyncKeys = this.getSyncKeysFromStorage();
            if (!storedSyncKeys.some((x) => x == key)) {
                storedSyncKeys.push(key);
                localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys, MapOrSet_toJSON));
            }
        }
        removeFromSyncKeysBackup(key) {
            let storedSyncKeys = this.getSyncKeysFromStorage();
            let index = storedSyncKeys.indexOf(key);
            if (index > -1) {
                storedSyncKeys.splice(index, 1);
                localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys, MapOrSet_toJSON));
            }
        }
        addToSyncKeysHelper(key) {
            if (!this.syncKeysContains(key))
                this.syncKeys.push(key);
        }
        removeFromSyncKeys(key) {
            this.removeFromSyncKeysHelper(key);
            this.removeFromSyncKeysBackup(key);
            localStorage.setItem("removeFromSyncKeys", key);
            localStorage.removeItem("removeFromSyncKeys");
        }
        removeFromSyncKeysHelper(key) {
            let index = this.syncKeys.indexOf(key);
            if (index > -1) {
                this.syncKeys.splice(index, 1);
            }
        }
        saveSessionData(data, key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            this.removeFromSyncKeys(key);
            localStorage.removeItem(key);
            sessionStorage.setItem(key, data);
        }
        saveSyncedSessionData(data, key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            localStorage.removeItem(key);
            this.addToSessionStorage(data, key);
        }
        savePermanentData(data, key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            this.removeFromSessionStorage(key);
            localStorage.setItem(key, data);
        }
        moveDataToSessionStorage(key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            let data = this.getData(key);
            if (data == null)
                return;
            this.saveSessionData(data, key);
        }
        moveDataToSyncedSessionStorage(key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            let data = this.getData(key);
            if (data == null)
                return;
            this.saveSyncedSessionData(data, key);
        }
        moveDataToPermanentStorage(key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            let data = this.getData(key);
            if (data == null)
                return;
            this.savePermanentData(data, key);
        }
        getData(key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            let data = sessionStorage.getItem(key);
            if (data == null)
                data = localStorage.getItem(key);
            return data;
        }
        getDataObject(key = LocalStoreManager.DBKEY_USER_DATA) {
            let data = this.getData(key);
            if (data != null)
                return JSON.parse(data);
            else
                return null;
        }
        deleteData(key = LocalStoreManager.DBKEY_USER_DATA) {
            this.testForInvalidKeys(key);
            this.removeFromSessionStorage(key);
            localStorage.removeItem(key);
        }
        raiseDBEvent(event) {
            this.raiseDBEventHelper(event);
            localStorage.setItem("raiseDBEvent", event);
            localStorage.removeItem("raiseDBEvent");
        }
        raiseDBEventHelper(event) {
            this._dbEvent.next(event);
        }
        getDBEventListener() {
            return this._dbEvent.asObservable();
        }
    }
    LocalStoreManager.syncListenerInitialised = false;
    LocalStoreManager.DBKEY_USER_DATA = "user_data";
    LocalStoreManager.DBKEY_SYNC_KEYS = "sync_keys";

    var ServiceScope;
    (function (ServiceScope) {
        ServiceScope[ServiceScope["websocket"] = 0] = "websocket";
        ServiceScope[ServiceScope["login"] = 1] = "login";
        ServiceScope[ServiceScope["upload"] = 2] = "upload";
    })(ServiceScope || (ServiceScope = {}));

    var retryExports = {};
    var retry$1 = {
      get exports(){ return retryExports; },
      set exports(v){ retryExports = v; },
    };

    var retry = {};

    function RetryOperation(timeouts, options) {
      if (typeof options === 'boolean') {
        options = { forever: options };
      }
      this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
      this._timeouts = timeouts;
      this._options = options || {};
      this._maxRetryTime = options && options.maxRetryTime || Infinity;
      this._fn = null;
      this._errors = [];
      this._attempts = 1;
      this._operationTimeout = null;
      this._operationTimeoutCb = null;
      this._timeout = null;
      this._operationStart = null;
      this._timer = null;
      if (this._options.forever) {
        this._cachedTimeouts = this._timeouts.slice(0);
      }
    }
    var retry_operation = RetryOperation;
    RetryOperation.prototype.reset = function() {
      this._attempts = 1;
      this._timeouts = this._originalTimeouts.slice(0);
    };
    RetryOperation.prototype.stop = function() {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (this._timer) {
        clearTimeout(this._timer);
      }
      this._timeouts       = [];
      this._cachedTimeouts = null;
    };
    RetryOperation.prototype.retry = function(err) {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (!err) {
        return false;
      }
      var currentTime = new Date().getTime();
      if (err && currentTime - this._operationStart >= this._maxRetryTime) {
        this._errors.push(err);
        this._errors.unshift(new Error('RetryOperation timeout occurred'));
        return false;
      }
      this._errors.push(err);
      var timeout = this._timeouts.shift();
      if (timeout === undefined) {
        if (this._cachedTimeouts) {
          this._errors.splice(0, this._errors.length - 1);
          timeout = this._cachedTimeouts.slice(-1);
        } else {
          return false;
        }
      }
      var self = this;
      this._timer = setTimeout(function() {
        self._attempts++;
        if (self._operationTimeoutCb) {
          self._timeout = setTimeout(function() {
            self._operationTimeoutCb(self._attempts);
          }, self._operationTimeout);
          if (self._options.unref) {
              self._timeout.unref();
          }
        }
        self._fn(self._attempts);
      }, timeout);
      if (this._options.unref) {
          this._timer.unref();
      }
      return true;
    };
    RetryOperation.prototype.attempt = function(fn, timeoutOps) {
      this._fn = fn;
      if (timeoutOps) {
        if (timeoutOps.timeout) {
          this._operationTimeout = timeoutOps.timeout;
        }
        if (timeoutOps.cb) {
          this._operationTimeoutCb = timeoutOps.cb;
        }
      }
      var self = this;
      if (this._operationTimeoutCb) {
        this._timeout = setTimeout(function() {
          self._operationTimeoutCb();
        }, self._operationTimeout);
      }
      this._operationStart = new Date().getTime();
      this._fn(this._attempts);
    };
    RetryOperation.prototype.try = function(fn) {
      console.log('Using RetryOperation.try() is deprecated');
      this.attempt(fn);
    };
    RetryOperation.prototype.start = function(fn) {
      console.log('Using RetryOperation.start() is deprecated');
      this.attempt(fn);
    };
    RetryOperation.prototype.start = RetryOperation.prototype.try;
    RetryOperation.prototype.errors = function() {
      return this._errors;
    };
    RetryOperation.prototype.attempts = function() {
      return this._attempts;
    };
    RetryOperation.prototype.mainError = function() {
      if (this._errors.length === 0) {
        return null;
      }
      var counts = {};
      var mainError = null;
      var mainErrorCount = 0;
      for (var i = 0; i < this._errors.length; i++) {
        var error = this._errors[i];
        var message = error.message;
        var count = (counts[message] || 0) + 1;
        counts[message] = count;
        if (count >= mainErrorCount) {
          mainError = error;
          mainErrorCount = count;
        }
      }
      return mainError;
    };

    (function (exports) {
    	var RetryOperation = retry_operation;
    	exports.operation = function(options) {
    	  var timeouts = exports.timeouts(options);
    	  return new RetryOperation(timeouts, {
    	      forever: options && (options.forever || options.retries === Infinity),
    	      unref: options && options.unref,
    	      maxRetryTime: options && options.maxRetryTime
    	  });
    	};
    	exports.timeouts = function(options) {
    	  if (options instanceof Array) {
    	    return [].concat(options);
    	  }
    	  var opts = {
    	    retries: 10,
    	    factor: 2,
    	    minTimeout: 1 * 1000,
    	    maxTimeout: Infinity,
    	    randomize: false
    	  };
    	  for (var key in options) {
    	    opts[key] = options[key];
    	  }
    	  if (opts.minTimeout > opts.maxTimeout) {
    	    throw new Error('minTimeout is greater than maxTimeout');
    	  }
    	  var timeouts = [];
    	  for (var i = 0; i < opts.retries; i++) {
    	    timeouts.push(this.createTimeout(i, opts));
    	  }
    	  if (options && options.forever && !timeouts.length) {
    	    timeouts.push(this.createTimeout(i, opts));
    	  }
    	  timeouts.sort(function(a,b) {
    	    return a - b;
    	  });
    	  return timeouts;
    	};
    	exports.createTimeout = function(attempt, opts) {
    	  var random = (opts.randomize)
    	    ? (Math.random() + 1)
    	    : 1;
    	  var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
    	  timeout = Math.min(timeout, opts.maxTimeout);
    	  return timeout;
    	};
    	exports.wrap = function(obj, options, methods) {
    	  if (options instanceof Array) {
    	    methods = options;
    	    options = null;
    	  }
    	  if (!methods) {
    	    methods = [];
    	    for (var key in obj) {
    	      if (typeof obj[key] === 'function') {
    	        methods.push(key);
    	      }
    	    }
    	  }
    	  for (var i = 0; i < methods.length; i++) {
    	    var method   = methods[i];
    	    var original = obj[method];
    	    obj[method] = function retryWrapper(original) {
    	      var op       = exports.operation(options);
    	      var args     = Array.prototype.slice.call(arguments, 1);
    	      var callback = args.pop();
    	      args.push(function(err) {
    	        if (op.retry(err)) {
    	          return;
    	        }
    	        if (err) {
    	          arguments[0] = op.mainError();
    	        }
    	        callback.apply(this, arguments);
    	      });
    	      op.attempt(function() {
    	        original.apply(obj, args);
    	      });
    	    }.bind(obj, original);
    	    obj[method].options = options;
    	  }
    	};
    } (retry));

    (function (module) {
    	module.exports = retry;
    } (retry$1));
    getDefaultExportFromCjs(retryExports);

    var DEFAULT_WEBSOCKET_CONFIG = {
        url: '',
        deserializer: function (e) { return JSON.parse(e.data); },
        serializer: function (value) { return JSON.stringify(value); },
    };
    var WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = 'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }';
    var WebSocketSubject = (function (_super) {
        __extends(WebSocketSubject, _super);
        function WebSocketSubject(urlConfigOrSource, destination) {
            var _this = _super.call(this) || this;
            _this._socket = null;
            if (urlConfigOrSource instanceof Observable) {
                _this.destination = destination;
                _this.source = urlConfigOrSource;
            }
            else {
                var config = (_this._config = __assign({}, DEFAULT_WEBSOCKET_CONFIG));
                _this._output = new Subject();
                if (typeof urlConfigOrSource === 'string') {
                    config.url = urlConfigOrSource;
                }
                else {
                    for (var key in urlConfigOrSource) {
                        if (urlConfigOrSource.hasOwnProperty(key)) {
                            config[key] = urlConfigOrSource[key];
                        }
                    }
                }
                if (!config.WebSocketCtor && WebSocket) {
                    config.WebSocketCtor = WebSocket;
                }
                else if (!config.WebSocketCtor) {
                    throw new Error('no WebSocket constructor can be found');
                }
                _this.destination = new ReplaySubject();
            }
            return _this;
        }
        WebSocketSubject.prototype.lift = function (operator) {
            var sock = new WebSocketSubject(this._config, this.destination);
            sock.operator = operator;
            sock.source = this;
            return sock;
        };
        WebSocketSubject.prototype._resetState = function () {
            this._socket = null;
            if (!this.source) {
                this.destination = new ReplaySubject();
            }
            this._output = new Subject();
        };
        WebSocketSubject.prototype.multiplex = function (subMsg, unsubMsg, messageFilter) {
            var self = this;
            return new Observable(function (observer) {
                try {
                    self.next(subMsg());
                }
                catch (err) {
                    observer.error(err);
                }
                var subscription = self.subscribe({
                    next: function (x) {
                        try {
                            if (messageFilter(x)) {
                                observer.next(x);
                            }
                        }
                        catch (err) {
                            observer.error(err);
                        }
                    },
                    error: function (err) { return observer.error(err); },
                    complete: function () { return observer.complete(); },
                });
                return function () {
                    try {
                        self.next(unsubMsg());
                    }
                    catch (err) {
                        observer.error(err);
                    }
                    subscription.unsubscribe();
                };
            });
        };
        WebSocketSubject.prototype._connectSocket = function () {
            var _this = this;
            var _a = this._config, WebSocketCtor = _a.WebSocketCtor, protocol = _a.protocol, url = _a.url, binaryType = _a.binaryType;
            var observer = this._output;
            var socket = null;
            try {
                socket = protocol ? new WebSocketCtor(url, protocol) : new WebSocketCtor(url);
                this._socket = socket;
                if (binaryType) {
                    this._socket.binaryType = binaryType;
                }
            }
            catch (e) {
                observer.error(e);
                return;
            }
            var subscription = new Subscription(function () {
                _this._socket = null;
                if (socket && socket.readyState === 1) {
                    socket.close();
                }
            });
            socket.onopen = function (evt) {
                var _socket = _this._socket;
                if (!_socket) {
                    socket.close();
                    _this._resetState();
                    return;
                }
                var openObserver = _this._config.openObserver;
                if (openObserver) {
                    openObserver.next(evt);
                }
                var queue = _this.destination;
                _this.destination = Subscriber.create(function (x) {
                    if (socket.readyState === 1) {
                        try {
                            var serializer = _this._config.serializer;
                            socket.send(serializer(x));
                        }
                        catch (e) {
                            _this.destination.error(e);
                        }
                    }
                }, function (err) {
                    var closingObserver = _this._config.closingObserver;
                    if (closingObserver) {
                        closingObserver.next(undefined);
                    }
                    if (err && err.code) {
                        socket.close(err.code, err.reason);
                    }
                    else {
                        observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT));
                    }
                    _this._resetState();
                }, function () {
                    var closingObserver = _this._config.closingObserver;
                    if (closingObserver) {
                        closingObserver.next(undefined);
                    }
                    socket.close();
                    _this._resetState();
                });
                if (queue && queue instanceof ReplaySubject) {
                    subscription.add(queue.subscribe(_this.destination));
                }
            };
            socket.onerror = function (e) {
                _this._resetState();
                observer.error(e);
            };
            socket.onclose = function (e) {
                if (socket === _this._socket) {
                    _this._resetState();
                }
                var closeObserver = _this._config.closeObserver;
                if (closeObserver) {
                    closeObserver.next(e);
                }
                if (e.wasClean) {
                    observer.complete();
                }
                else {
                    observer.error(e);
                }
            };
            socket.onmessage = function (e) {
                try {
                    var deserializer = _this._config.deserializer;
                    observer.next(deserializer(e));
                }
                catch (err) {
                    observer.error(err);
                }
            };
        };
        WebSocketSubject.prototype._subscribe = function (subscriber) {
            var _this = this;
            var source = this.source;
            if (source) {
                return source.subscribe(subscriber);
            }
            if (!this._socket) {
                this._connectSocket();
            }
            this._output.subscribe(subscriber);
            subscriber.add(function () {
                var _socket = _this._socket;
                if (_this._output.observers.length === 0) {
                    if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
                        _socket.close();
                    }
                    _this._resetState();
                }
            });
            return subscriber;
        };
        WebSocketSubject.prototype.unsubscribe = function () {
            var _socket = this._socket;
            if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
                _socket.close();
            }
            this._resetState();
            _super.prototype.unsubscribe.call(this);
        };
        return WebSocketSubject;
    }(AnonymousSubject));

    class RxWebsocketSubject extends Subject {
        constructor(
        client,
        retryOptions,
        retryWait,
        urlGenerator,
        webSocketSubjectConfig,
        deserializer,
        serializer) {
            super();
            this.retryOptions = retryOptions;
            this.retryWait = retryWait;
            this.urlGenerator = urlGenerator;
            this.webSocketSubjectConfig = webSocketSubjectConfig;
            this.deserializer = deserializer;
            this.serializer = serializer;
            this.operation = null;
            this.socket = null;
            this.connectionObserver = null;
            this.closeEvent = null;
            this.reconnecting = false;
            this.log = Log$1.of("transport:socket", client);
            this.connectionStatus = new Observable((observer) => {
                this.connectionObserver = observer;
            }).pipe(share(), distinctUntilChanged());
            if (!deserializer) {
                this.deserializer = (e) => {
                    return JSON.parse(e.data);
                };
            }
            if (!this.serializer) {
                this.serializer = (data) => {
                    return JSON.stringify(data, MapOrSet_toJSON);
                };
            }
            this.wsSubjectConfig = {
                url: null,
                closingObserver: webSocketSubjectConfig.closingObserver,
                closeObserver: {
                    next: (e) => {
                        var _a, _b;
                        this.closeEvent = e;
                        this.internalDisconnect();
                        this.socket = null;
                        this.nativeSocket = undefined;
                        (_a = this.webSocketSubjectConfig.closeObserver) === null || _a === void 0 ? void 0 : _a.next(e);
                        if (this.operation && !this.operation.retry({ name: String(e.code), message: e.reason })) {
                            this.log.info("End reconnecting operation, no more attempt, call connect() to reconnect");
                            this.operation = null;
                            this.reconnecting = false;
                        }
                        else {
                            this.reconnecting = !!this.operation;
                        }
                        (_b = this.connectionObserver) === null || _b === void 0 ? void 0 : _b.next(false);
                    },
                },
                openObserver: {
                    next: (e) => {
                        var _a, _b;
                        if (e.target && e.target.hasOwnProperty("readyState")) {
                            this.nativeSocket = e.target;
                        }
                        this.closeEvent = null;
                        (_a = this.connectionObserver) === null || _a === void 0 ? void 0 : _a.next(true);
                        (_b = this.webSocketSubjectConfig.openObserver) === null || _b === void 0 ? void 0 : _b.next(e);
                    },
                },
                deserializer: this.deserializer,
                serializer: this.serializer,
            };
            this.connect();
        }
        protocolReady() {
            if (this.operation) {
                this.operation.reset();
                const operationErrors = this.operation.errors();
                if (operationErrors && operationErrors.length) {
                    operationErrors.splice(0, operationErrors.length);
                }
                this.reconnecting = false;
            }
        }
        disconnect() {
            var _a, _b;
            this.log.info("Disconnet from ws");
            (_a = this.operation) === null || _a === void 0 ? void 0 : _a.stop();
            const operationErrors = (_b = this.operation) === null || _b === void 0 ? void 0 : _b.errors();
            if (operationErrors && operationErrors.length) {
                operationErrors.splice(0, operationErrors.length);
            }
            this.operation = null;
            this.reconnecting = false;
            this.internalDisconnect();
        }
        connect() {
            if (!this.operation) {
                this.log.info("Connect to ws");
                this.operation = retryExports.operation(Object.assign({}, this.retryOptions));
                this.operation.attempt(this.internalConnect.bind(this));
            }
        }
        internalDisconnect() {
            if (this.socket) {
                this.socket.unsubscribe();
            }
        }
        internalConnect(currentAttempt) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                this.log.info(`Attempt ${currentAttempt} to connect to ws`);
                this.wsSubjectConfig.url = this.webSocketSubjectConfig.url || this.urlGenerator();
                this.internalDisconnect();
                try {
                    if (!(yield this.retryWait(this.closeEvent, currentAttempt))) {
                        this.log.info("retryWait return false, stop reconnecting");
                        (_a = this.operation) === null || _a === void 0 ? void 0 : _a.stop();
                        this.operation = null;
                        this.reconnecting = false;
                        return;
                    }
                }
                catch (e) {
                    (_b = this.operation) === null || _b === void 0 ? void 0 : _b.retry({ name: String(e.code), message: e.reason });
                    return;
                }
                this.socket = new WebSocketSubject(this.wsSubjectConfig);
                this.socket.subscribe((message) => {
                    try {
                        this.next(message);
                    }
                    catch (err) {
                        this.log.error("Unhandled error", err);
                    }
                }, (err) => {
                    this.log.error("Socket error", err);
                });
            });
        }
        send(message) {
            if (this.socket) {
                if (this.nativeSocket && this.nativeSocket.readyState !== 1) {
                    this.log.debug(`message not being sent, websocket readyState is ${this.nativeSocket.readyState}`);
                }
                this.socket.next(message);
            }
            else {
                this.log.error("Unable to send, socket is not connected");
            }
            return this;
        }
    }

    var clientExports = {};
    var client = {
      get exports(){ return clientExports; },
      set exports(v){ clientExports = v; },
    };

    (function (module, exports) {
     (function (root) {
    	  function CrossStorageClient(url, opts) {
    	    opts = opts || {};
    	    this._id = CrossStorageClient._generateUUID();
    	    this._promise = opts.promise || Promise;
    	    this._frameId = opts.frameId || 'CrossStorageClient-' + this._id;
    	    this._origin = CrossStorageClient._getOrigin(url);
    	    this._requests = {};
    	    this._connected = false;
    	    this._closed = false;
    	    this._count = 0;
    	    this._timeout = opts.timeout || 5000;
    	    this._listener = null;
    	    this._storageEventListeners = {};
    	    this._storageEventListenerCount = 0;
    	    this._installListener();
    	    var frame;
    	    if (opts.frameId) {
    	      frame = document.getElementById(opts.frameId);
    	    }
    	    if (frame) {
    	      this._poll();
    	    }
    	    frame = frame || this._createFrame(url);
    	    this._hub = frame.contentWindow;
    	  }
    	  CrossStorageClient.frameStyle = {
    	    display: 'none',
    	    position: 'absolute',
    	    top: '-999px',
    	    left: '-999px'
    	  };
    	  CrossStorageClient._getOrigin = function (url) {
    	    var uri, protocol, origin;
    	    uri = document.createElement('a');
    	    uri.href = url;
    	    if (!uri.host) {
    	      uri = window.location;
    	    }
    	    if (!uri.protocol || uri.protocol === ':') {
    	      protocol = window.location.protocol;
    	    } else {
    	      protocol = uri.protocol;
    	    }
    	    origin = protocol + '//' + uri.host;
    	    origin = origin.replace(/:80$|:443$/, '');
    	    return origin;
    	  };
    	  CrossStorageClient._generateUUID = function () {
    	    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);
    	    });
    	  };
    	  CrossStorageClient.prototype.onConnect = function () {
    	    var client = this;
    	    if (this._connected) {
    	      return this._promise.resolve();
    	    } else if (this._closed) {
    	      return this._promise.reject(new Error('CrossStorageClient has closed'));
    	    }
    	    if (!this._requests.connect) {
    	      this._requests.connect = [];
    	    }
    	    return new this._promise(function (resolve, reject) {
    	      var timeout = setTimeout(function () {
    	        reject(new Error('CrossStorageClient could not connect'));
    	      }, client._timeout);
    	      client._requests.connect.push(function (err) {
    	        clearTimeout(timeout);
    	        if (err) return reject(err);
    	        resolve();
    	      });
    	    });
    	  };
    	  CrossStorageClient.prototype.set = function (key, value) {
    	    return this._request('set', {
    	      key: key,
    	      value: value
    	    });
    	  };
    	  CrossStorageClient.prototype.get = function (key) {
    	    var args = Array.prototype.slice.call(arguments);
    	    return this._request('get', { keys: args });
    	  };
    	  CrossStorageClient.prototype.listen = function (callback) {
    	    this._storageEventListenerCount++;
    	    var eventKey = this._id + ":" + this._storageEventListenerCount;
    	    this._storageEventListeners[eventKey] = callback;
    	    return this._request('listen', { eventKey: eventKey }).then(function () {
    	      return eventKey
    	    });
    	  };
    	  CrossStorageClient.prototype.unlisten = function (eventKey) {
    	    delete this._storageEventListeners[eventKey];
    	    return this._request('unlisten', { eventKey: eventKey });
    	  };
    	  CrossStorageClient.prototype.del = function () {
    	    var args = Array.prototype.slice.call(arguments);
    	    return this._request('del', { keys: args });
    	  };
    	  CrossStorageClient.prototype.clear = function () {
    	    return this._request('clear');
    	  };
    	  CrossStorageClient.prototype.getKeys = function () {
    	    return this._request('getKeys');
    	  };
    	  CrossStorageClient.prototype.close = function () {
    	    var frame = document.getElementById(this._frameId);
    	    if (frame) {
    	      frame.parentNode.removeChild(frame);
    	    }
    	    if (window.removeEventListener) {
    	      window.removeEventListener('message', this._listener, false);
    	    } else {
    	      window.detachEvent('onmessage', this._listener);
    	    }
    	    this._connected = false;
    	    this._closed = true;
    	  };
    	  CrossStorageClient.prototype._installListener = function () {
    	    var client = this;
    	    this._listener = function (message) {
    	      var i, origin, error, response;
    	      if (client._closed || !message.data || typeof message.data !== 'string') {
    	        return;
    	      }
    	      origin = (message.origin === 'null') ? 'file://' : message.origin;
    	      if (origin !== client._origin) return;
    	      if (message.data === 'cross-storage:unavailable') {
    	        if (!client._closed) client.close();
    	        if (!client._requests.connect) return;
    	        error = new Error('Closing client. Could not access localStorage in hub.');
    	        for (i = 0; i < client._requests.connect.length; i++) {
    	          client._requests.connect[i](error);
    	        }
    	        return;
    	      }
    	      if (message.data.indexOf('cross-storage:') !== -1 && !client._connected) {
    	        client._connected = true;
    	        if (!client._requests.connect) return;
    	        for (i = 0; i < client._requests.connect.length; i++) {
    	          client._requests.connect[i](error);
    	        }
    	        delete client._requests.connect;
    	      }
    	      if (message.data === 'cross-storage:ready') return;
    	      try {
    	        response = JSON.parse(message.data);
    	      } catch (e) {
    	        return;
    	      }
    	      if (response.type === 'event') {
    	        if (response.eventKey in client._storageEventListeners) {
    	          client._storageEventListeners[response.eventKey](response.eventData);
    	        }
    	        return;
    	      }
    	      if (!response.id) return;
    	      if (client._requests[response.id]) {
    	        client._requests[response.id](response.error, response.result);
    	      }
    	    };
    	    if (window.addEventListener) {
    	      window.addEventListener('message', this._listener, false);
    	    } else {
    	      window.attachEvent('onmessage', this._listener);
    	    }
    	  };
    	  CrossStorageClient.prototype._poll = function () {
    	    var client, interval, targetOrigin;
    	    client = this;
    	    targetOrigin = (client._origin === 'file://') ? '*' : client._origin;
    	    interval = setInterval(function () {
    	      if (client._connected) return clearInterval(interval);
    	      if (!client._hub) return;
    	      client._hub.postMessage('cross-storage:poll', targetOrigin);
    	    }, 1000);
    	  };
    	  CrossStorageClient.prototype._createFrame = function (url) {
    	    var frame, key;
    	    frame = window.document.createElement('iframe');
    	    frame.id = this._frameId;
    	    for (key in CrossStorageClient.frameStyle) {
    	      if (CrossStorageClient.frameStyle.hasOwnProperty(key)) {
    	        frame.style[key] = CrossStorageClient.frameStyle[key];
    	      }
    	    }
    	    window.document.body.appendChild(frame);
    	    frame.src = url;
    	    return frame;
    	  };
    	  CrossStorageClient.prototype._request = function (method, params) {
    	    var req, client;
    	    if (this._closed) {
    	      return this._promise.reject(new Error('CrossStorageClient has closed'));
    	    }
    	    client = this;
    	    client._count++;
    	    req = {
    	      id: this._id + ':' + client._count,
    	      method: 'cross-storage:' + method,
    	      params: params
    	    };
    	    return new this._promise(function (resolve, reject) {
    	      var timeout, originalToJSON, targetOrigin;
    	      timeout = setTimeout(function () {
    	        if (!client._requests[req.id]) return;
    	        delete client._requests[req.id];
    	        reject(new Error('Timeout: could not perform ' + req.method));
    	      }, client._timeout);
    	      client._requests[req.id] = function (err, result) {
    	        clearTimeout(timeout);
    	        delete client._requests[req.id];
    	        if (err) return reject(new Error(err));
    	        resolve(result);
    	      };
    	      if (Array.prototype.toJSON) {
    	        originalToJSON = Array.prototype.toJSON;
    	        Array.prototype.toJSON = null;
    	      }
    	      targetOrigin = (client._origin === 'file://') ? '*' : client._origin;
    	      client._hub.postMessage(JSON.stringify(req), targetOrigin);
    	      if (originalToJSON) {
    	        Array.prototype.toJSON = originalToJSON;
    	      }
    	    });
    	  };
    	  if (module.exports) {
    	    module.exports = CrossStorageClient;
    	  } else {
    	    exports.CrossStorageClient = CrossStorageClient;
    	  }
    	}());
    } (client, clientExports));

    var hubExports = {};
    var hub = {
      get exports(){ return hubExports; },
      set exports(v){ hubExports = v; },
    };

    (function (module, exports) {
     (function (root) {
    	  var CrossStorageHub = {};
    	  CrossStorageHub.init = function (permissions) {
    	    var available = true;
    	    try {
    	      if (!window.localStorage) available = false;
    	    } catch (e) {
    	      available = false;
    	    }
    	    if (!available) {
    	      try {
    	        return window.parent.postMessage('cross-storage:unavailable', '*');
    	      } catch (e) {
    	        return;
    	      }
    	    }
    	    CrossStorageHub._permissions = permissions || [];
    	    CrossStorageHub._eventListeners = {};
    	    CrossStorageHub._installListener();
    	    window.parent.postMessage('cross-storage:ready', '*');
    	  };
    	  CrossStorageHub._installListener = function () {
    	    var listener = CrossStorageHub._listener;
    	    if (window.addEventListener) {
    	      window.addEventListener('message', listener, false);
    	    } else {
    	      window.attachEvent('onmessage', listener);
    	    }
    	  };
    	  CrossStorageHub._listener = function (message) {
    	    var origin, targetOrigin, request, method, error, result, response;
    	    origin = (message.origin === 'null') ? 'file://' : message.origin;
    	    if (message.data === 'cross-storage:poll') {
    	      return window.parent.postMessage('cross-storage:ready', message.origin);
    	    }
    	    if (message.data === 'cross-storage:ready') return;
    	    try {
    	      request = JSON.parse(message.data);
    	    } catch (err) {
    	      return;
    	    }
    	    if (!request || typeof request.method !== 'string') {
    	      return;
    	    }
    	    method = request.method.split('cross-storage:')[1];
    	    if (!method) {
    	      return;
    	    } else if (!CrossStorageHub._permitted(origin, method)) {
    	      error = 'Invalid permissions for ' + method;
    	    } else {
    	      try {
    	        result = CrossStorageHub['_' + method](request.params);
    	      } catch (err) {
    	        error = err.message;
    	      }
    	    }
    	    response = JSON.stringify({
    	      id: request.id,
    	      error: error,
    	      result: result
    	    });
    	    targetOrigin = (origin === 'file://') ? '*' : origin;
    	    window.parent.postMessage(response, targetOrigin);
    	  };
    	  CrossStorageHub._permitted = function (origin, method) {
    	    var available, i, entry, match;
    	    if (method === 'unlisten') method = 'listen';
    	    available = ['get', 'set', 'listen', 'del', 'clear', 'getKeys'];
    	    if (!CrossStorageHub._inArray(method, available)) {
    	      return false;
    	    }
    	    for (i = 0; i < CrossStorageHub._permissions.length; i++) {
    	      entry = CrossStorageHub._permissions[i];
    	      if (!(entry.origin instanceof RegExp) || !(entry.allow instanceof Array)) {
    	        continue;
    	      }
    	      match = entry.origin.test(origin);
    	      if (match && CrossStorageHub._inArray(method, entry.allow)) {
    	        return true;
    	      }
    	    }
    	    return false;
    	  };
    	  CrossStorageHub._set = function (params) {
    	    window.localStorage.setItem(params.key, params.value);
    	  };
    	  CrossStorageHub._get = function (params) {
    	    var storage, result, i, value;
    	    storage = window.localStorage;
    	    result = [];
    	    for (i = 0; i < params.keys.length; i++) {
    	      try {
    	        value = storage.getItem(params.keys[i]);
    	      } catch (e) {
    	        value = null;
    	      }
    	      result.push(value);
    	    }
    	    return (result.length > 1) ? result : result[0];
    	  };
    	  CrossStorageHub._listen = function (params) {
    	    if (params.eventKey in CrossStorageHub._eventListeners) {
    	      throw new Error("Can't reuse eventKeys")
    	    }
    	    var handler = function (event) {
    	      if (event.storageArea != window.localStorage) return;
    	      var data = {
    	        type: 'event',
    	        eventKey: params.eventKey,
    	        eventData: {
    	          key: event.key,
    	          newValue: event.newValue,
    	          oldValue: event.oldValue,
    	          url: event.url
    	        }
    	      };
    	      window.parent.postMessage(JSON.stringify(data), '*');
    	    };
    	    if (window.addEventListener) {
    	      window.addEventListener('storage', handler, false);
    	    } else {
    	      window.attachEvent('onstorage', handler);
    	    }
    	    CrossStorageHub._eventListeners[params.eventKey] = handler;
    	  };
    	  CrossStorageHub._unlisten = function (params) {
    	    var handler = CrossStorageHub._eventListeners[params.eventKey];
    	    if (window.removeEventListener) {
    	      window.removeEventListener('storage', handler, false);
    	    } else {
    	      window.detachEvent('onstorage', handler);
    	    }
    	    CrossStorageHub._eventListeners[params.eventKey] = null;
    	  };
    	  CrossStorageHub._del = function (params) {
    	    for (var i = 0; i < params.keys.length; i++) {
    	      window.localStorage.removeItem(params.keys[i]);
    	    }
    	  };
    	  CrossStorageHub._clear = function () {
    	    window.localStorage.clear();
    	  };
    	  CrossStorageHub._getKeys = function (params) {
    	    var i, length, keys;
    	    keys = [];
    	    length = window.localStorage.length;
    	    for (i = 0; i < length; i++) {
    	      keys.push(window.localStorage.key(i));
    	    }
    	    return keys;
    	  };
    	  CrossStorageHub._inArray = function (value, array) {
    	    for (var i = 0; i < array.length; i++) {
    	      if (value === array[i]) return true;
    	    }
    	    return false;
    	  };
    	  CrossStorageHub._now = function () {
    	    if (typeof Date.now === 'function') {
    	      return Date.now();
    	    }
    	    return new Date().getTime();
    	  };
    	  if (module.exports) {
    	    module.exports = CrossStorageHub;
    	  } else {
    	    exports.CrossStorageHub = CrossStorageHub;
    	  }
    	}());
    } (hub, hubExports));

    var lib = {
      CrossStorageClient: clientExports,
      CrossStorageHub:    hubExports
    };

    class Heartbeat {
        constructor(
        heartbeatInterval) {
            this.heartbeatInterval = heartbeatInterval;
            this.heartbeatCheckId = null;
            this.connected = false;
        }
        setConnected(connected) {
            this.connected = connected;
        }
        setTransportSocket(transportSocket) {
            this.transportSocket = transportSocket;
        }
        heartbeat() {
            if (this.heartbeatCheckId)
                clearTimeout(this.heartbeatCheckId);
            this.heartbeatCheckId = setTimeout(() => {
                if (this.connected && this.transportSocket) {
                    this.transportSocket.send("ping");
                    this.heartbeat();
                }
            }, this.heartbeatInterval);
        }
    }
    class AbstractJsonRpcWebsocket {
        constructor(client, connectionEventSubject, retryOptions, heartbeatInterval, crossStorageUrl) {
            this.client = client;
            this.connectionEventSubject = connectionEventSubject;
            this.retryOptions = retryOptions;
            this.heartbeatInterval = heartbeatInterval;
            this.crossStorageUrl = crossStorageUrl;
            this.loading = false;
            this.connected = false;
            this.socketMessage = new Subject();
            this.currentIdRequest = 1;
            this.firstConnect = true;
            this.crossStorageEnabled = false;
            this.requestExecuted = new Map();
            this.stopActiveRequest = new Subject();
            this.log = Log$1.of("transport", client);
            this.logRequest = Log$1.of("transport:request", client);
            this.logResponse = Log$1.of("transport:response", client);
            this.heartbeatService = new Heartbeat(this.heartbeatInterval);
            this.socketMessage.pipe(tap(this.handleResponseMessage.bind(this)), debounceTime(200)).subscribe(this.heartbeatService.heartbeat);
            if (this.crossStorageUrl) {
                this.initCrossStorage();
            }
        }
        isReconnecting() {
            var _a;
            return !this.firstConnect && ((_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.reconnecting);
        }
        retryWait(event, retries) {
            return __awaiter(this, void 0, void 0, function* () {
                return true;
            });
        }
        getCrossStorage() {
            return this.crossStorage;
        }
        initCrossStorage() {
            return __awaiter(this, void 0, void 0, function* () {
                this.crossStorage = new CrossStorageManager(this.client, this, this.crossStorageUrl, () => this.crossStorageEnabled, (idRequest) => this.getResponseOf(idRequest), () => this.getNewIdRequest(), () => this.webSocketConnect(), () => this.webSocketDisconnect(), (response) => this.socketMessage.next(response), (message) => { var _a; return (_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.send(message); }, this.connectionEventSubject);
                yield this.crossStorage.connect();
                if (this.crossStorage.getLevel() === Storagelevel.slave) {
                    let result = yield this.crossStorage.getStorage().get(ConnectionKey.commonMethodsMessage);
                    if (result) {
                        this.crossStorage.commonMethodsRequestMap.fromJSON(JSON.parse(result));
                    }
                    this.connectionEventSubject.next({ connected: true });
                }
            });
        }
        disconnect() {
            if (this.crossStorage) {
                this.crossStorageEnabled = false;
                this.crossStorage.disconnect();
            }
            else {
                this.webSocketDisconnect();
            }
        }
        connect() {
            if (this.crossStorageUrl) {
                this.crossStorageEnabled = true;
            }
            else {
                this.webSocketConnect();
            }
        }
        getResponseOf(idRequest) {
            let requestData = this.requestExecuted.get(idRequest);
            if (!requestData) {
                requestData = RequestData.empty(new RequestIdentifier(idRequest));
                this.requestExecuted.set(idRequest, requestData);
            }
            return requestData.response;
        }
        handleResponseMessage(response) {
            if (response.hasOwnProperty("id")) {
                const request = this.requestExecuted.get(Math.abs(response.id));
                if (request) {
                    try {
                        request.response.next(response);
                    }
                    catch (e) {
                        this.log.warn("Client error on handle message", e);
                    }
                }
            }
        }
        webSocketConnect() {
            if (this.transportSocket && this.transportSocket.reconnecting) {
                this.log.debug("connection ws not available, reconnection is in progress");
                if (this.client.isRequestEnableUntilReconnect()) {
                    return;
                }
                else {
                    throw new ReconnectingInProgress({
                        clazz: "",
                        code: -8,
                        message: "Recconnecting is in progress, please retry after connection is complete",
                    });
                }
            }
            if (this.transportSocket && !this.connected) {
                this.transportSocket.connect();
                return;
            }
            let url = this.client.generateUrl(ServiceScope.websocket);
            this.log.debug(`connection ws to '${url}'`);
            this.webSocketDisconnect();
            this.transportSocket = new RxWebsocketSubject(this.client, this.retryOptions, this.retryWait.bind(this), () => this.client.generateUrl(ServiceScope.websocket), {
                url: "",
                closeObserver: {
                    next: (e) => {
                        this.log.debug(`ws closed, code ${e.code}`);
                        this.onClose(e);
                    },
                },
                openObserver: {
                    next: () => {
                        this.log.debug("ws open");
                        this.onOpen();
                    },
                },
            }, (message) => {
                try {
                    let response = JSON.parse(message.data);
                    this.logResponse.debug(" <-- ", response);
                    return response && response.id ? response : { id: "unknow", result: message };
                }
                catch (e) {
                    return { id: "service", result: message };
                }
            }, (request) => {
                let webSocketMessage;
                if (request instanceof RequestData) {
                    const jsonRpcMessage = { id: request.identifier.idRequest, method: request.method, params: request.params };
                    this.logRequest.debug(" --> ", jsonRpcMessage, { requestTimeout: request.options.timeout });
                    webSocketMessage = JSON.stringify(jsonRpcMessage, MapOrSet_toJSON);
                }
                else {
                    webSocketMessage = request;
                }
                return webSocketMessage;
            });
            this.transportSocket.subscribe((data) => this.socketMessage.next(data));
            this.transportSocket.connectionStatus.subscribe((isConnected) => {
                this.connected = isConnected;
                this.heartbeatService.setConnected(isConnected);
                this.connectionEventSubject.next({ connected: isConnected });
                if (isConnected) {
                    this.heartbeatService.heartbeat();
                }
            });
            this.heartbeatService.setTransportSocket(this.transportSocket);
            this.heartbeatService.heartbeat();
        }
        webSocketDisconnect() {
            if (this.transportSocket && this.connected) {
                this.log.debug("force disconnect previous socket");
                this.transportSocket.disconnect();
                this.transportSocket.unsubscribe();
                this.transportSocket = undefined;
            }
        }
        errorTimeoutToWebapiException(request) {
            return (e) => {
                if (e instanceof TimeoutError) {
                    this.log.error(`Timeout occurred, startTime ${request.requestTime ? LogUtils.dateToString(request.requestTime) : null} - timeout ${request.options.timeout} ms - id ${request.identifier.idRequest} - method ${request.method}`);
                    throw new TimeoutResponse();
                }
                else {
                    throw e;
                }
            };
        }
        waitSendRequest(requestData) {
            return __awaiter(this, void 0, void 0, function* () { });
        }
        getNewIdRequest() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.currentIdRequest === Number.MAX_SAFE_INTEGER) {
                    this.log.info("Reached Number.MAX_SAFE_INTEGER for idRequest, reset to 1000");
                    this.currentIdRequest = 999;
                }
                return new RequestIdentifier(++this.currentIdRequest);
            });
        }
        stopCurrentRequestWithException(exception) {
            this.stopActiveRequest.next(exception);
        }
        generateResultSyncFromRequest(request, responseData) {
            return new Observable((observer) => {
                var _a;
                const timeoutparsed = parseInt(`${(_a = request.requestTimeoutExpected) !== null && _a !== void 0 ? _a : this.getRequestTimeoutForMethod(request.method)}`);
                request.options.timeout = isNaN(timeoutparsed) || timeoutparsed < this.getRequestTimeout() ? this.getRequestTimeout() : timeoutparsed;
                const doNextResponse = request.responseIsChunked
                    ? (data) => {
                        var _a;
                        if (data.cRes) {
                            let pos = ((_a = data.i) !== null && _a !== void 0 ? _a : data.cRes.length) - data.cRes.length;
                            try {
                                data.cRes.forEach((chunk) => observer.next({ tot: data.tot, i: ++pos, data: chunk }));
                            }
                            catch (e) {
                                this.log.warn(`consumer has throw error on manage response of request ${request.identifier.idRequest} - ${request.method} - chunk ${pos}`, e);
                            }
                        }
                        if (data.part === "END") {
                            observer.complete();
                        }
                    }
                    : (data) => {
                        try {
                            observer.next(data);
                        }
                        catch (e) {
                            this.log.warn(`consumer has throw error on manage response of request ${request.identifier.idRequest} - ${request.method}`, e);
                        }
                        observer.complete();
                    };
                return merge(request.response.result,
                this.stopActiveRequest.asObservable().pipe(switchMap((exception) => throwError(() => exception))))
                    .pipe(timeout(request.options.timeout),
                catchError(this.errorTimeoutToWebapiException(request)))
                    .subscribe({
                    next: doNextResponse,
                    error: (error) => {
                        var _a, _b;
                        let errorEmitted;
                        try {
                            errorEmitted = (_b = (_a = responseData.errorResolver) === null || _a === void 0 ? void 0 : _a.call(responseData, error)) !== null && _b !== void 0 ? _b : error;
                            observer.error(errorEmitted);
                        }
                        catch (err) {
                            if (errorEmitted && err === errorEmitted) {
                                this.log.error(`Error received but not handled request ${request.identifier.idRequest} - ${request.method}`);
                            }
                            else {
                                throw err;
                            }
                        }
                    },
                    complete: () => this.emitEventComplete(request, false),
                });
            });
        }
        buildResponse(request) {
            var _a;
            let stopResult = returnFalse;
            let stopNotification = returnFalse;
            let resultSyncSubscription = Subscription.EMPTY;
            const [responseIsChunked, activateNotification] = [
                request instanceof RequestChunked || request instanceof RequestChunkedUpdate,
                request instanceof RequestPromiseUpdate || request instanceof RequestChunkedUpdate,
            ];
            const requestData = new RequestData(request.method, request.parameters, request.options, request.options.timeout, activateNotification, responseIsChunked);
            const resultSync = requestData.response.resultSync.asObservable().pipe(tap(() => {
                this.log.debug(`resultSync - emit`, requestData.compact());
            }), finalize(() => {
                this.log.debug(`resultSync - complete`, requestData.compact());
            }), share());
            const responseData = {
                result: new Observable((observer) => {
                    let firstResponseComplete;
                    resultSyncSubscription = resultSync
                        .pipe(finalize(() => {
                        firstResponseComplete = undefined;
                    }), concatMap((response) => {
                        if (observer.closed) {
                            this.log.warn(`resultSync - result is lost due to previous result complete at '${firstResponseComplete}', subscribe to resultSync to handle all result`, requestData.compact());
                            return response;
                        }
                        else {
                            const sharedResponse = response.pipe(finalize(() => {
                                firstResponseComplete = new Date();
                            }), share());
                            sharedResponse.subscribe(observer);
                            return sharedResponse;
                        }
                    }))
                        .subscribe();
                }),
                notification: EMPTY,
                stopNotification,
                resultSync,
                errorResolver: (_a = request.errorResolver) !== null && _a !== void 0 ? _a : this.client.methodsErrorResolver,
            };
            let createRequestData = new Observable((observer) => {
                from(this.waitSendRequest(requestData)).subscribe(observer);
            }).pipe(concatMap(() => __awaiter(this, void 0, void 0, function* () {
                requestData.identifier = yield this.getNewIdRequest();
            })));
            if (activateNotification) {
                createRequestData = createRequestData.pipe(shareReplay(1));
                let resultNotificationSubscription = Subscription.EMPTY;
                let stopNotificationDone = false;
                let stopNotificationAction = () => __awaiter(this, void 0, void 0, function* () {
                    if (requestData.identifier.idRequest) {
                        this.log.debug(`stopNotification ${requestData.identifier.idRequest}, method ${requestData.method}`);
                        try {
                            const response = yield toPromise$1(this.buildResponse(new RequestPromise("stopNotification", [requestData.identifier.idRequest])).response.result);
                            this.log.debug(`Notification ${requestData.identifier.idRequest} ${response ? "correctly" : "not"} stopped`);
                            this.emitEventComplete(requestData, true);
                            return response;
                        }
                        catch (err) {
                            this.log.error(`Notification ${requestData.identifier.idRequest} failed stopped`, err);
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                });
                stopNotification = responseData.stopNotification = () => __awaiter(this, void 0, void 0, function* () {
                    stopNotificationDone = true;
                    let result = true;
                    if (stopNotificationAction) {
                        result = yield stopNotificationAction();
                        if (result) {
                            stopNotificationAction = null;
                            resultNotificationSubscription.unsubscribe();
                            this.completeRequestExecution(requestData);
                        }
                        else {
                            stopNotificationDone = false;
                        }
                    }
                    else {
                        this.completeRequestExecution(requestData);
                    }
                    return result;
                });
                responseData.notification = createRequestData.pipe(switchMap(() => {
                    if (stopNotificationDone) {
                        this.log.debug(`stopNotification ${requestData.identifier.idRequest} of method '${requestData.method}' was called before subscribe to notification, return EMPTY observable`);
                        return EMPTY;
                    }
                    else {
                        return new Observable((observer) => {
                            (() => __awaiter(this, void 0, void 0, function* () {
                                resultNotificationSubscription.unsubscribe();
                                try {
                                    resultNotificationSubscription = requestData.response.notification.subscribe(observer);
                                    yield this.execRequest(requestData, false, false);
                                }
                                catch (err) {
                                    this.log.error("Error on activate result notification", err);
                                    observer.error(err);
                                    yield stopNotification();
                                }
                            }))();
                            return () => stopNotification();
                        });
                    }
                }));
            }
            let resultSubscription = Subscription.EMPTY;
            stopResult = () => __awaiter(this, void 0, void 0, function* () {
                resultSubscription.unsubscribe();
                if (!activateNotification) {
                    resultSyncSubscription.unsubscribe();
                }
                return true;
            });
            requestData.buildResponse = (forceSend, fromRevival) => {
                let sentDone, sentError;
                return {
                    sent: new Promise((_sentDone, _sentError) => {
                        sentDone = _sentDone;
                        sentError = _sentError;
                    }),
                    response: createRequestData.pipe(switchMap(() => new Observable((observer) => {
                        (() => __awaiter(this, void 0, void 0, function* () {
                            resultSubscription.unsubscribe();
                            try {
                                resultSubscription = this.generateResultSyncFromRequest(requestData, responseData)
                                    .pipe(finalize(() => (!requestData.withNotification ? this.completeRequestExecution(requestData) : null)))
                                    .subscribe(observer);
                                yield this.execRequest(requestData, forceSend, fromRevival);
                                sentDone();
                            }
                            catch (err) {
                                sentError(err);
                                this.log.error("Error on activate result", err);
                                observer.error(err);
                                stopResult();
                            }
                        }))();
                        return () => stopResult();
                    }).pipe(catchError((error) => {
                        stopNotification();
                        throw error;
                    }), finalize(() => stopResult())))),
                };
            };
            requestData.newResponse(false, false);
            return {
                response: responseData,
                toLiveResult: () => {
                    return {
                        result: responseData.result,
                        notification: responseData.notification,
                        resultSync: responseData.resultSync,
                        errorResolver: responseData.errorResolver,
                        stopResult,
                        stopNotification,
                    };
                },
            };
        }
        execRequest(request, force, requestFromRevival) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (!request.identifier)
                    throw new Error(`Error on send ${request.method}, identifier is unset`);
                const requestIdentifier = this.requestExecuted.get(request.identifier.idRequest);
                if (requestIdentifier) {
                    if (requestFromRevival && !force) {
                        this.log.warn(`Unable to execRequest of method ${request.method}, id ${request.identifier.idRequest} was used by previous method ${requestIdentifier.method} at ${requestIdentifier.requestTime}`);
                    }
                }
                else {
                    this.requestExecuted.set(request.identifier.idRequest, request);
                    force = force || !(this.crossStorage && this.crossStorage.execRequest(request));
                }
                if (force) {
                    request.requestTime = new Date();
                    (_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.send(request);
                }
            });
        }
        completeRequestExecution(request) {
            if (request.executed && request.identifier) {
                const requestData = this.requestExecuted.get(request.identifier.idRequest);
                if (requestData) {
                    this.requestExecuted.delete(request.identifier.idRequest);
                    requestData.complete();
                }
            }
        }
        emitEventComplete(request, isNotification) {
            if (this.crossStorage && request.identifier) {
                this.crossStorage.emitEventComplete(request.identifier, isNotification);
            }
        }
        emitErrorInternal(error, errorResolver) {
            const errorIdentity = () => error;
            const response = {
                result: throwError(errorIdentity),
                notification: throwError(errorIdentity),
                resultSync: throwError(errorIdentity),
                errorResolver: errorResolver !== null && errorResolver !== void 0 ? errorResolver : this.client.methodsErrorResolver,
                stopResult: returnFalse,
                stopNotification: returnFalse,
            };
            return {
                response,
                toLiveResult: () => {
                    return {
                        result: response.result,
                        notification: response.notification,
                        resultSync: response.resultSync,
                        errorResolver: response.errorResolver,
                        stopResult: returnFalse,
                        stopNotification: returnFalse,
                    };
                },
            };
        }
        generateActiveNotificationManager() {
            return __awaiter(this, void 0, void 0, function* () {
                const mappedRequest = yield this.mapRequestExecuted(Array.from(this.requestExecuted.values())
                    .filter((request) => !!request.method && request.executed && request.withNotification)
                    .sort((r1, r2) => (r1.options.priorityOnRestart === r2.options.priorityOnRestart ? 0 : r1.options.priorityOnRestart < r2.options.priorityOnRestart ? 1 : -1)));
                return new ActiveNotificationManager(mappedRequest, this.resendRequest.bind(this));
            });
        }
        resendRequest(requests, parallelSend = 1) {
            return __awaiter(this, void 0, void 0, function* () {
                if (requests && requests.length) {
                    return toPromise$1(from(requests).pipe(bufferCount(parallelSend), concatMap((requestGroup) => __awaiter(this, void 0, void 0, function* () {
                        const promises = requestGroup.reduce((result, req) => {
                            result.push(((request) => __awaiter(this, void 0, void 0, function* () {
                                try {
                                    yield this.elaborateResponseFromRevival(request, yield request.newResponse(true, true));
                                }
                                catch (err) {
                                    this.log.error(`Error on resend active notification - ${JSON.stringify(request.compact(), MapOrSet_toJSON)}`, err);
                                }
                                return;
                            }))(req));
                            return result;
                        }, []);
                        yield Promise.all(promises);
                        return;
                    })), last()));
                }
            });
        }
        mapRequestExecuted(requestExecuted) {
            return __awaiter(this, void 0, void 0, function* () {
                return { higher: requestExecuted, lower: [] };
            });
        }
        elaborateResponseFromRevival(request, response) {
            return __awaiter(this, void 0, void 0, function* () { });
        }
        emitError(request, error) {
            return this.emitErrorInternal(error, request.errorResolver);
        }
    }
    class ActiveNotificationManager {
        constructor(mappedRequest, resendRequestProto) {
            this.mappedRequest = mappedRequest;
            this.resendRequestProto = resendRequestProto;
            this._higherPriorityNotificationIsResended = false;
            this._lowerPriorityNotificationIsResended = false;
        }
        get higherPriorityNotificationIsResended() {
            return this._higherPriorityNotificationIsResended;
        }
        get lowerPriorityNotificationIsResended() {
            return this._lowerPriorityNotificationIsResended;
        }
        get higherPriorityNotification() {
            return this.mappedRequest.higher;
        }
        get lowerPriorityNotification() {
            return this.mappedRequest.lower;
        }
        resendHigherPriority(concurrent = ActiveNotificationManager.parallelHigherPriority) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._higherPriorityNotificationIsResended) {
                    try {
                        return yield this.resendRequestProto(this.higherPriorityNotification, concurrent);
                    }
                    finally {
                        this._higherPriorityNotificationIsResended = true;
                    }
                }
            });
        }
        resendLowerPriority(concurrent = ActiveNotificationManager.parallelLowerPriority) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._lowerPriorityNotificationIsResended) {
                    try {
                        return yield this.resendRequestProto(this.lowerPriorityNotification, concurrent);
                    }
                    finally {
                        this._lowerPriorityNotificationIsResended = true;
                    }
                }
            });
        }
    }
    ActiveNotificationManager.parallelHigherPriority = 1;
    ActiveNotificationManager.parallelLowerPriority = 5;
    class CrossStorageMessage {
        constructor(manager, eventHandler) {
            this.manager = manager;
            this.eventHandler = eventHandler;
        }
        notify(key, message) {
            return __awaiter(this, void 0, void 0, function* () {
                yield this.manager.getStorage().set(key, JSON.stringify(message, MapOrSet_toJSON));
                return message;
            });
        }
        retrive(connectionKey) {
            return this.manager.getStorage().get(connectionKey);
        }
        ping(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return (yield this.notify(ConnectionKey.pingToMaster, new StorageMessage(this.manager.getStorage()._id, message))).message;
            });
        }
        pong(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return (yield this.notify(ConnectionKey.pongToSlave, new StorageMessage(this.manager.getStorage()._id, message))).message;
            });
        }
        notifyHierarchy(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return (yield this.notify(ConnectionKey.hierarchy, new StorageMessage(this.manager.getStorage()._id, yield this.eventHandler.hierarchy(message)))).message;
            });
        }
        notifyCommonMethodsMap(message) {
            return this.notify(ConnectionKey.commonMethodsMessage, message);
        }
        decodePing(message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        }
        decodePong(message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        }
        decodeHierarchy(message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        }
        notifyWsResponse(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.notify(ConnectionKey.fromWsResponse, yield this.eventHandler.fromWsResponse(this.decodeWsResponse(JSON.stringify(message, MapOrSet_toJSON))));
            });
        }
        decodeWsResponse(message) {
            var _a, _b, _c, _d, _e, _f;
            const response = message ? FromWsMessage.fromStringMessage(message) : null;
            if ((_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.identifier) === null || _c === void 0 ? void 0 : _c.request) {
                response.data.message.identifier.request = new RequestIdentifier(response.data.message.identifier.request.idRequest);
            }
            if ((_f = (_e = (_d = response === null || response === void 0 ? void 0 : response.data) === null || _d === void 0 ? void 0 : _d.message) === null || _e === void 0 ? void 0 : _e.identifier) === null || _f === void 0 ? void 0 : _f.request) {
                response.data.message.identifier.realRequest = new RequestIdentifier(response.data.message.identifier.realRequest.idRequest);
            }
            return response;
        }
        notifyWsRequestId(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.notify(ConnectionKey.fromWsRequestId, yield this.eventHandler.fromWsRequestId(this.decodeWsRequestId(JSON.stringify(message, MapOrSet_toJSON))));
            });
        }
        notifyWsRequestIdUpdate(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.notify(ConnectionKey.fromWsRequestIdUpdate, yield this.eventHandler.fromWsRequestIdUpdate(JSON.parse(JSON.stringify(message, MapOrSet_toJSON))));
            });
        }
        decodeWsRequestId(message) {
            var _a, _b, _c, _d;
            const request = message ? FromWsMessage.fromStringMessage(message) : null;
            if ((_b = (_a = request === null || request === void 0 ? void 0 : request.data) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.request) {
                request.data.message.request = new RequestIdentifier(request.data.message.request.idRequest);
            }
            if ((_d = (_c = request === null || request === void 0 ? void 0 : request.data) === null || _c === void 0 ? void 0 : _c.message) === null || _d === void 0 ? void 0 : _d.realRequest) {
                request.data.message.realRequest = new RequestIdentifier(request.data.message.realRequest.idRequest);
            }
            return request;
        }
        notifyWsRequestComplete(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.notify(ConnectionKey.toWsRequestComplete, yield this.eventHandler.toWsRequestComplete(this.decodeWsRequestComplete(JSON.stringify(message, MapOrSet_toJSON))));
            });
        }
        decodeWsRequestComplete(message) {
            var _a, _b, _c, _d;
            const request = message ? ToWsMessage.fromStringMessage(message) : null;
            if ((_b = (_a = request === null || request === void 0 ? void 0 : request.data) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.identifier) {
                request.data.message.identifier = new RequestIdentifier((_d = (_c = request === null || request === void 0 ? void 0 : request.data) === null || _c === void 0 ? void 0 : _c.message) === null || _d === void 0 ? void 0 : _d.identifier.idRequest);
            }
            return request;
        }
        notifyWsRequest(message) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.notify(ConnectionKey.toWsRequest, yield this.eventHandler.toWsRequest(this.decodeWsRequest(JSON.stringify(message, MapOrSet_toJSON))));
            });
        }
        decodeWsRequest(message) {
            var _a;
            const request = message ? ToWsMessage.fromStringMessage(message) : null;
            if ((_a = request === null || request === void 0 ? void 0 : request.data) === null || _a === void 0 ? void 0 : _a.message) {
                request.data.message = RequestData.fromRequestData(request.data.message);
            }
            return request;
        }
        decodeCommonMethodsMap(message) {
            return message ? JSON.parse(message) : null;
        }
    }
    class CrossStorageHeartBeat {
        constructor(client, manger, onHeartBeatEnd, onHeartBeatOk, pongTimeout = 500, pingInterval = 5000) {
            this.manger = manger;
            this.onHeartBeatEnd = onHeartBeatEnd;
            this.onHeartBeatOk = onHeartBeatOk;
            this.pongTimeout = pongTimeout;
            this.pingInterval = pingInterval;
            this.errorCounter = 0;
            this.pongSubscription = Subscription.EMPTY;
            this.checkSubscription = Subscription.EMPTY;
            this.started = false;
            this.log = Log$1.of("transport:CrossStorageHeartBeat", client);
        }
        stop() {
            this.pongSubscription.unsubscribe();
            this.started = false;
        }
        stopCheck() {
            this.checkSubscription.unsubscribe();
        }
        start() {
            if (this.manger.getLevel() != Storagelevel.master) {
                this.started = true;
                this.log.info("PING");
                let idPing = new Date().toISOString();
                this.pongSubscription.unsubscribe();
                this.pongSubscription = this.manger
                    .getPongObserver()
                    .pipe(filter((pong) => pong.id_pong === idPing), timeout(this.pongTimeout), take(1))
                    .subscribe(() => {
                    this.log.info("PONG");
                    this.errorCounter = 0;
                    setTimeout(() => this.start(), this.pingInterval);
                }, (err) => {
                    this.errorCounter++;
                    this.log.warn("PONG lost");
                    if (this.errorCounter < 3) {
                        setTimeout(() => this.start(), 200);
                    }
                    else {
                        this.onHeartBeatEnd(err);
                        this.log.error("no PONG response");
                    }
                });
                this.manger.ping({ id_ping: idPing });
            }
            else {
                this.stop();
            }
        }
        check() {
            this.log.info("PING check master");
            let idPing = new Date().toISOString();
            this.checkSubscription.unsubscribe();
            this.checkSubscription = this.manger
                .getPongObserver()
                .pipe(filter((pong) => pong.id_pong === idPing), timeout(this.pongTimeout), take(1))
                .subscribe(() => {
                this.onHeartBeatOk(true);
                this.log.info("PONG check master");
            }, () => {
                this.errorCounter++;
                if (this.errorCounter < 3) {
                    this.log.warn("PONG check master lost");
                    this.check();
                }
                else {
                    this.onHeartBeatOk(false);
                    this.log.error("no PONG master response");
                }
            });
            this.manger.ping({ id_ping: idPing });
        }
        getStarted() {
            return this.started;
        }
    }
    class CrossStorageManager {
        constructor(client,
        transport,
        crossStorageUrl,
        isCrossStorageEnabled,
        getResponseOf,
        getNewIdRequest,
        webSocketConnect,
        webSocketDisconnect,
        onResponse,
        sendToSocket,
        connectionEventSubject) {
            this.transport = transport;
            this.crossStorageUrl = crossStorageUrl;
            this.isCrossStorageEnabled = isCrossStorageEnabled;
            this.getResponseOf = getResponseOf;
            this.getNewIdRequest = getNewIdRequest;
            this.webSocketConnect = webSocketConnect;
            this.webSocketDisconnect = webSocketDisconnect;
            this.onResponse = onResponse;
            this.sendToSocket = sendToSocket;
            this.connectionEventSubject = connectionEventSubject;
            this.pongSubject = new Subject();
            this.storageRequestMap = new Map();
            this.masterRequestMap = new Map();
            this.slaveRequestMap = new Map();
            this.commonMethodsRequestMap = new StringKeyMap();
            this.slaveChecked = new Subject();
            this.masterChecked = new Subject();
            this.methodsToMergeAndProxy = ["isChannelEnabled", "multiChannelServiceMonitor", "callChannelServiceMonitor", "videoChannelServiceMonitor", "chatChannelServiceMonitor", "mailChannelServiceMonitor", "callbackChannelServiceMonitor", "omnideskChannelServiceMonitor"];
            this.notCommonMethods = ["chatSendMessage", "widgetVisitUri", "chatChannelSessionNew", "chatChannelSessionMonitor", "chatChannelEventMonitor", "chatChannelSessionClose", "stopNotification", "chatReceivedMessage", "chatReadMessage", "chatSendRecapOfSession", "mailChannelSessionNew", "callbackChannelSessionNew", "videoChannelSessionNew", "callChannelSessionNew", "callChannelSessionClose", "echoTestSessionNew", "echoTestSessionStop"];
            this.serviceMonitormethods = ["multiChannelServiceMonitor", "callChannelServiceMonitor", "videoChannelServiceMonitor", "chatChannelServiceMonitor", "mailChannelServiceMonitor", "callbackChannelServiceMonitor", "omnideskChannelServiceMonitor"];
            this.decodeEventHandler = {
                pingToMaster: (event) => this.message.decodePing(event.newValue),
                pongToSlave: (event) => this.message.decodePong(event.newValue),
                hierarchy: (event) => this.message.decodeHierarchy(event.newValue),
                fromWsResponse: (event) => this.message.decodeWsResponse(event === null || event === void 0 ? void 0 : event.newValue),
                fromWsRequestId: (event) => this.message.decodeWsRequestId(event === null || event === void 0 ? void 0 : event.newValue),
                fromWsRequestIdUpdate: (event) => this.message.decodeWsRequestId(event === null || event === void 0 ? void 0 : event.newValue),
                toWsRequestComplete: (event) => this.message.decodeWsRequestComplete(event === null || event === void 0 ? void 0 : event.newValue),
                toWsRequest: (event) => this.message.decodeWsRequest(event === null || event === void 0 ? void 0 : event.newValue),
                CommonMethodsMessage: (event) => this.message.decodeCommonMethodsMap(event.newValue),
            };
            this.eventHandler = {
                pingToMaster: (ping) => {
                    if (this.storageLevel === Storagelevel.master) {
                        this.message.pong({
                            id_pong: ping.id_ping,
                            to_id: ping.from_id,
                        });
                    }
                    return Promise.resolve(ping);
                },
                pongToSlave: (pong) => {
                    if (pong.to_id === this.crossStorage._id) {
                        this.pongSubject.next(pong);
                    }
                    return Promise.resolve(pong);
                },
                hierarchy: (hierarchy) => {
                    return this.updateHierarchy(hierarchy);
                },
                fromWsResponse: (fromWsMessage) => __awaiter(this, void 0, void 0, function* () {
                    if (fromWsMessage && fromWsMessage.to_ids.indexOf(this.crossStorage._id) > -1) {
                        const requestIdentifier = this.slaveRequestMap.get(fromWsMessage.data.message.identifier.request.idRequest);
                        if (requestIdentifier) {
                            const jsonRpcResponse = fromWsMessage.data.message.data;
                            if (jsonRpcResponse) {
                                jsonRpcResponse.id = fromWsMessage.data.message.isNotification ? requestIdentifier.idNotification : requestIdentifier.idRequest;
                                this.onResponse(jsonRpcResponse);
                            }
                        }
                    }
                    return fromWsMessage;
                }),
                fromWsRequestId: (toWsIdMessage) => __awaiter(this, void 0, void 0, function* () {
                    if (toWsIdMessage && toWsIdMessage.to_ids.indexOf(this.crossStorage._id) > -1) {
                        const storagemsg = toWsIdMessage.data.message;
                        this.slaveRequestMap.set(storagemsg.realRequest.idRequest, storagemsg.request);
                        this.masterRequestMap.set(storagemsg.request.idRequest, storagemsg.realRequest);
                        if (storagemsg.activateNotification) {
                            this.masterRequestMap.set(storagemsg.request.idNotification, storagemsg.realRequest);
                            this.slaveRequestMap.set(storagemsg.realRequest.idNotification, storagemsg.request);
                        }
                    }
                    return toWsIdMessage;
                }),
                fromWsRequestIdUpdate: (toWsIdMessageUpdate) => __awaiter(this, void 0, void 0, function* () {
                    if (toWsIdMessageUpdate && toWsIdMessageUpdate.to_ids.indexOf(this.crossStorage._id) > -1) {
                        [
                            {
                                oldId: toWsIdMessageUpdate.data.message.request.idRequest,
                                newId: toWsIdMessageUpdate.data.message.realRequest.idRequest,
                                isNotification: false,
                            },
                            {
                                oldId: toWsIdMessageUpdate.data.message.request.idNotification,
                                newId: toWsIdMessageUpdate.data.message.realRequest.idNotification,
                                isNotification: true,
                            },
                        ].forEach((masterIdentification) => {
                            let slaveRequestIdentification = this.slaveRequestMap.get(masterIdentification.oldId);
                            if (slaveRequestIdentification) {
                                this.slaveRequestMap.set(masterIdentification.newId, slaveRequestIdentification);
                                this.slaveRequestMap.delete(masterIdentification.oldId);
                                let prevMasterIdentifier = this.masterRequestMap.get(masterIdentification.isNotification ? slaveRequestIdentification.idNotification : slaveRequestIdentification.idRequest);
                                if (prevMasterIdentifier && masterIdentification.isNotification) {
                                    prevMasterIdentifier.idNotification = masterIdentification.newId;
                                }
                                else if (prevMasterIdentifier) {
                                    prevMasterIdentifier.idRequest = masterIdentification.newId;
                                }
                            }
                        });
                    }
                    return toWsIdMessageUpdate;
                }),
                toWsRequestComplete: (toWsCompleteMessage) => __awaiter(this, void 0, void 0, function* () {
                    var _a;
                    if (this.storageLevel === Storagelevel.master) {
                        if (toWsCompleteMessage) {
                            let idToRemove = toWsCompleteMessage.data.message.isNotification ? toWsCompleteMessage.data.message.identifier.idNotification : toWsCompleteMessage.data.message.identifier.idRequest;
                            if (this.storageRequestMap.has(idToRemove)) {
                                (_a = this.storageRequestMap.get(idToRemove)) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                                this.storageRequestMap.delete(idToRemove);
                            }
                        }
                    }
                    return toWsCompleteMessage;
                }),
                toWsRequest: (toWsMessage) => __awaiter(this, void 0, void 0, function* () {
                    var _b, _c;
                    if (toWsMessage && this.storageLevel === Storagelevel.master) {
                        let storage_request = toWsMessage.data.message;
                        try {
                            let registerResult = yield this.registerRequest(toWsMessage.from_id, storage_request);
                            let realRequestIdentifier = registerResult.identifier;
                            let data = null;
                            if (registerResult.isNew) {
                                data = {
                                    registerRequest: this.commonMethodsRequestMap.get(storage_request.method) ? this.commonMethodsRequestMap.get(storage_request.method) : null,
                                    requestIdentifierNotication: {
                                        request: storage_request.identifier,
                                        realRequest: realRequestIdentifier,
                                        activateNotification: storage_request.withNotification,
                                    },
                                };
                            }
                            else {
                                throw stop;
                            }
                            let registerRequest = data.registerRequest;
                            let requestIdentifierNotication = data.requestIdentifierNotication;
                            if (registerRequest) {
                                yield this.message.notifyWsRequestIdUpdate(new FromWsMessage((_c = (_b = this.commonMethodsRequestMap.get(storage_request.method)) === null || _b === void 0 ? void 0 : _b.id_slaves) !== null && _c !== void 0 ? _c : [], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)));
                                registerRequest.id_slaves.push(toWsMessage.from_id);
                                this.commonMethodsRequestMap.set(storage_request.method, new RegisterRequestObj(registerRequest.id_slaves, storage_request, requestIdentifierNotication));
                                this.notifyCommonMethodsMap();
                            }
                            else {
                                if (this.notCommonMethods.indexOf(storage_request.method) < 0) {
                                    this.commonMethodsRequestMap.set(storage_request.method, new RegisterRequestObj([toWsMessage.from_id], storage_request, requestIdentifierNotication));
                                    this.notifyCommonMethodsMap();
                                }
                            }
                            yield this.message.notifyWsRequestId(new FromWsMessage([toWsMessage.from_id], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)));
                            const response = this.getResponseOf(requestIdentifierNotication.realRequest.idRequest).asObservable();
                            const responseHandler = this.notifyCrossStorageResponse(toWsMessage.from_id, false, storage_request.method, requestIdentifierNotication);
                            this.storageRequestMap.set(requestIdentifierNotication.realRequest.idRequest, response
                                .pipe(filter((response) => !responseIsNotification(response)), concatMap((response) => responseHandler(response)))
                                .subscribe());
                            if (storage_request.withNotification) {
                                const notificationResponseHandler = this.notifyCrossStorageResponse(toWsMessage.from_id, true, storage_request.method, requestIdentifierNotication);
                                this.storageRequestMap.set(requestIdentifierNotication.realRequest.idNotification, response
                                    .pipe(filter((response) => responseIsNotification(response)), concatMap((response) => notificationResponseHandler(response)))
                                    .subscribe());
                            }
                            storage_request.identifier.idRequest = requestIdentifierNotication.realRequest.idRequest;
                            yield this.sendToSocket(storage_request);
                        }
                        catch (error) {
                            if (error && error.stop) ;
                            else {
                                console.log(error);
                            }
                        }
                    }
                    return toWsMessage;
                }),
                CommonMethodsMessage: (commonMethodsMessage) => __awaiter(this, void 0, void 0, function* () {
                    this.commonMethodsRequestMap.fromJSON(commonMethodsMessage);
                    return this.commonMethodsRequestMap;
                }),
            };
            this.log = Log$1.of("transport:storage", client);
            this.message = new CrossStorageMessage(this, this.eventHandler);
            this.methodAnalizer = new CrossStorageMethodAnalizer();
            this.heartBeat = new CrossStorageHeartBeat(client, this, () => {
                this.masterReconnect();
            }, (res) => {
                this.masterChecked.next(res);
            });
        }
        getPongObserver() {
            return this.pongSubject.asObservable();
        }
        getMessage() {
            return this.message;
        }
        getStorage() {
            return this.crossStorage;
        }
        getLevel() {
            return this.storageLevel;
        }
        setString(key, value) {
            return this.crossStorage.set(key, value);
        }
        setValue(key, value) {
            return this.crossStorage.set(key, JSON.stringify(value, MapOrSet_toJSON));
        }
        getValue(key) {
            return this.crossStorage.get(key);
        }
        disconnect() {
            if (this.storageLevel === Storagelevel.master) {
                this.hierarchy.connectionMaster = null;
                if (this.hierarchy.connectionSlave.length > 0) {
                    this.hierarchy.connectionFutureMaster = this.hierarchy.connectionSlave[0];
                    this.hierarchy.connectionSlave.splice(0, 1);
                    this.notifyHierarchy();
                }
                else {
                    this.clear();
                }
                this.webSocketDisconnect();
            }
            else if (this.storageLevel === Storagelevel.slave) {
                var index = this.hierarchy.connectionSlave.indexOf(this.crossStorage._id);
                if (index > -1) {
                    this.hierarchy.connectionSlave.splice(index, 1);
                    this.notifyHierarchy();
                }
                this.connectionEventSubject.next({ connected: false });
            }
        }
        connect() {
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug("connect with cross-Storage");
                this.crossStorage = new lib.CrossStorageClient(this.crossStorageUrl, { timeout: 30000 });
                this.hierarchy = new HierarchyMessage(null, []);
                yield this.crossStorage.onConnect();
                this.crossStorage.listen((event) => this.storageEventHandler(event));
                let hierarchy = yield this.message.decodeHierarchy(yield this.message.retrive(ConnectionKey.hierarchy));
                this.hierarchy = hierarchy ? hierarchy : this.hierarchy;
                yield new Promise((resolve) => {
                    if (this.hierarchy.connectionMaster) {
                        this.log.debug("There is a master");
                        this.masterChecked.subscribe((res) => __awaiter(this, void 0, void 0, function* () {
                            if (res) {
                                this.log.debug("connecting as slave");
                                this.storageLevel = Storagelevel.slave;
                                this.hierarchy.connectionSlave.push(this.crossStorage._id);
                                this.heartBeat.start();
                                resolve(true);
                            }
                            else {
                                yield this.masterReconnect();
                                resolve(false);
                            }
                        }), () => __awaiter(this, void 0, void 0, function* () {
                            yield this.masterReconnect();
                            resolve(false);
                        }));
                        this.heartBeat.check();
                    }
                    else {
                        this.log.debug("There isn't a master");
                        this.masterConnect();
                        resolve(true);
                    }
                });
                return this.notifyHierarchy();
            });
        }
        masterConnect() {
            this.log.debug("Connecting as master");
            if (!this.transport.loading) {
                this.webSocketConnect();
            }
            this.storageLevel = Storagelevel.master;
            this.hierarchy.connectionMaster = this.crossStorage._id;
            this.hierarchy.connectionSlave = [];
        }
        slaveConnect() {
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug("connecting as slave");
                this.storageLevel = Storagelevel.slave;
                this.hierarchy.connectionSlave.push(this.crossStorage._id);
                this.heartBeat.start();
                return this.notifyHierarchy();
            });
        }
        masterReconnect() {
            this.log.debug("Check if there are slaves alive");
            return new Promise((resolve) => {
                this.slaveChecked.pipe(timeout(1000)).subscribe(() => __awaiter(this, void 0, void 0, function* () {
                    if (this.slavesCheck.length) {
                        this.slavesCheck.forEach((slave) => {
                            this.hierarchy.connectionSlave.splice(this.slavesCheck.indexOf(slave), 1);
                        });
                    }
                    yield this.reconnect();
                    resolve(this.hierarchy);
                }), () => __awaiter(this, void 0, void 0, function* () {
                    this.hierarchy.connectionSlave = [];
                    yield this.reconnect();
                    resolve(this.hierarchy);
                }));
            });
        }
        reconnect() {
            return new Promise((resolve) => {
                if (!this.transport.loading) {
                    this.webSocketConnect();
                }
                this.storageLevel = Storagelevel.master;
                this.hierarchy.connectionMaster = this.crossStorage._id;
                if (this.commonMethodsRequestMap && this.commonMethodsRequestMap.getSize() > 0) {
                    this.commonMethodsRequestMap.getMap().forEach((value, key) => {
                        const requestData = value.request;
                        const req = this.commonMethodsRequestMap.get(key);
                        if (req)
                            req.request = null;
                        this.eventHandler.toWsRequest(new ToWsMessage(this.crossStorage._id, new StorageMessage(this.crossStorage._id, RequestData.fromRequestData(requestData))));
                    });
                }
                resolve(true);
            });
        }
        clear() {
            for (var key in ConnectionKey) {
                this.crossStorage.del(ConnectionKey[key]);
            }
        }
        storageEventHandler(event) {
            this.log.debug("Event received -- ", event);
            if (event.newValue != null) {
                if (this.eventHandler[event.key]) {
                    this.eventHandler[event.key](this.decodeEventHandler[event.key](event));
                }
            }
        }
        notifyCrossStorageResponse(from_id, isNotification, method, identifier) {
            var _a, _b;
            const storagetMessageData = {
                identifier,
                isNotification,
                data: null,
            };
            const to_ids = this.commonMethodsRequestMap.get(method) ? (_b = (_a = this.commonMethodsRequestMap.get(method)) === null || _a === void 0 ? void 0 : _a.id_slaves) !== null && _b !== void 0 ? _b : [] : [from_id];
            const result = new FromWsMessage(to_ids, new StorageMessage(this.crossStorage._id, storagetMessageData));
            return (response) => {
                var _a, _b, _c;
                storagetMessageData.data = response;
                if (this.commonMethodsRequestMap.get(method)) {
                    const last_responses = ((_a = this.commonMethodsRequestMap.get(method)) === null || _a === void 0 ? void 0 : _a.lastResponse) || null;
                    if (this.serviceMonitormethods.indexOf(method) !== -1 && last_responses && last_responses.length > 0 && isNotification) {
                        const serviceMonitorResponse = response.result;
                        if (last_responses) {
                            last_responses.forEach((last_response) => {
                                last_response.result.cRes.forEach((serviceStatus) => {
                                    if (serviceStatus.service === serviceMonitorResponse.service) {
                                        serviceStatus.status = serviceMonitorResponse.status;
                                    }
                                });
                            });
                        }
                    }
                    else {
                        if (((_b = response.result) === null || _b === void 0 ? void 0 : _b.i) && response.result.i > 1) {
                            (_c = this.commonMethodsRequestMap.get(method)) === null || _c === void 0 ? void 0 : _c.lastResponse.push(response);
                        }
                        else {
                            const request = this.commonMethodsRequestMap.get(method);
                            if (request)
                                request.lastResponse = [response];
                        }
                    }
                }
                return this.message.notifyWsResponse(result);
            };
        }
        updateHierarchy(newHierarchy) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!newHierarchy) {
                    this.hierarchy.connectionFutureMaster = null;
                    this.hierarchy.connectionMaster = null;
                    this.hierarchy.connectionSlave = [];
                }
                else {
                    this.hierarchy = newHierarchy;
                }
                if (this.storageLevel === Storagelevel.slave && !this.heartBeat.getStarted) {
                    this.heartBeat.start();
                }
                if (!this.hierarchy.connectionMaster) {
                    this.connectionEventSubject.next({ connected: false });
                    if (this.hierarchy.connectionFutureMaster) {
                        this.heartBeat.stop();
                        if (this.hierarchy.connectionFutureMaster == this.crossStorage._id) {
                            this.log.debug(`I'm new master`);
                            this.storageLevel = Storagelevel.futureMaster;
                            this.hierarchy.connectionFutureMaster = null;
                            yield this.reconnect();
                            yield this.notifyHierarchy();
                        }
                    }
                }
                return newHierarchy;
            });
        }
        notifyHierarchy() {
            return this.message.notifyHierarchy(this.hierarchy);
        }
        notifyCommonMethodsMap() {
            return this.message.notifyCommonMethodsMap(this.commonMethodsRequestMap);
        }
        ping(message) {
            return this.message.ping({
                id_ping: message.id_ping,
                from_id: this.crossStorage._id,
            });
        }
        emitEventComplete(request, isNotification) {
            return __awaiter(this, void 0, void 0, function* () {
                let result = null;
                if (this.isCrossStorageEnabled() && this.storageLevel === Storagelevel.slave) {
                    let idToRemove = isNotification ? request.idNotification : request.idRequest;
                    let masterIdentifier = this.masterRequestMap.get(idToRemove);
                    if (masterIdentifier) {
                        result = yield this.message.notifyWsRequestComplete(new ToWsMessage(this.crossStorage._id, new StorageMessage(this.crossStorage._id, { isNotification: isNotification, identifier: masterIdentifier })));
                        this.masterRequestMap.delete(idToRemove);
                        this.slaveRequestMap.delete(isNotification ? masterIdentifier.idRequest : masterIdentifier.idNotification);
                    }
                }
                return result;
            });
        }
        execRequest(request) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.isCrossStorageEnabled()  ) {
                    yield this.message.notifyWsRequest(new ToWsMessage(this.crossStorage._id, new StorageMessage(this.crossStorage._id, request)));
                    return true;
                }
                else {
                    return false;
                }
            });
        }
        registerRequest(from_id, request) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                let needSocketRequest = true;
                const requestRegistered = this.commonMethodsRequestMap.get(request.method) ? this.commonMethodsRequestMap.get(request.method) : null;
                if (this.methodsToMergeAndProxy.indexOf(request.method) > -1 && (requestRegistered !== null && requestRegistered !== void 0 ? requestRegistered : null) !== null) {
                    const currentParam = [...request.params];
                    const newParams = yield (this.methodAnalizer[request.method] && requestRegistered.request ? this.methodAnalizer[request.method](currentParam, requestRegistered.request.params) : currentParam);
                    let notifyWsRequestId = false;
                    if (newParams) {
                        request.params.length = 0;
                        request.params.push.apply(request.params, newParams);
                        notifyWsRequestId = true;
                    }
                    else {
                        (_a = this.commonMethodsRequestMap.get(request.method)) === null || _a === void 0 ? void 0 : _a.id_slaves.push(from_id);
                        let requestIdentifierNotication = {
                            request: request.identifier,
                            realRequest: requestRegistered.requestIdentifierNotification.request,
                            activateNotification: requestRegistered.requestIdentifierNotification.activateNotification,
                        };
                        yield this.message.notifyWsRequestId(new FromWsMessage([from_id], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)));
                    }
                    const notifyWsResponseArray = new Array();
                    if (!notifyWsRequestId) {
                        requestRegistered.lastResponse.forEach((response) => {
                            const result = new FromWsMessage([from_id], new StorageMessage(this.crossStorage._id, {
                                identifier: requestRegistered.requestIdentifierNotification,
                                isNotification: responseIsNotification(response),
                                data: response,
                            }));
                            notifyWsResponseArray.push(this.message.notifyWsResponse(result));
                        });
                        try {
                            yield Promise.all(notifyWsResponseArray);
                            needSocketRequest = false;
                        }
                        catch (e) { }
                    }
                }
                try {
                    if (needSocketRequest) {
                        return {
                            isNew: needSocketRequest,
                            identifier: yield this.getNewIdRequest(),
                        };
                    }
                    else {
                        return {
                            isNew: false,
                            identifier: null,
                        };
                    }
                }
                catch (err) {
                    this.log.error("Error on handle request joiner", err);
                    throw err;
                }
            });
        }
        resendRequest() {
            return Promise.resolve(true);
        }
    }
    class CrossStorageMethodAnalizer {
        constructor() { }
        isChannelEnabled(newParams, oldParams) {
            if (oldParams) {
                let comparedParams = this.compareRequestParams((newParams !== null && newParams !== void 0 ? newParams : [])[0], (oldParams !== null && oldParams !== void 0 ? oldParams : [])[0]);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        newParams = union$1(newParams, oldParams);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        multiChannelServiceMonitor(newParams, oldParams) {
            if (oldParams) {
                if (newParams && newParams[0].type === oldParams[0].type) {
                    let comparedParams = this.compareRequestParams(newParams[0].services, oldParams[0].services);
                    switch (comparedParams) {
                        case 0:
                            newParams = null;
                            break;
                        case -1:
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                            oldParams = newParams;
                            break;
                    }
                }
                else {
                    newParams = null;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        videoChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        callChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                if (comparedParams === 0) {
                    newParams = null;
                }
                else if (comparedParams === -1) {
                    if (newParams)
                        newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                    oldParams = newParams;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        chatChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        omnideskChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        callbackChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        mailChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        whatsappChannelServiceMonitor(newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                let comparedParams = this.compareRequestParams(newParams ? (_a = newParams[0].services) !== null && _a !== void 0 ? _a : [] : [], oldParams ? (_b = oldParams[0].services) !== null && _b !== void 0 ? _b : [] : []);
                switch (comparedParams) {
                    case 0:
                        newParams = null;
                        break;
                    case -1:
                        if (newParams)
                            newParams[0].services = union$1(newParams[0].services, oldParams[0].services);
                        oldParams = newParams;
                        break;
                }
            }
            else {
                oldParams = newParams;
            }
            return Promise.resolve(newParams);
        }
        compareRequestParams(request_1, request_2) {
            if (request_1.length === request_2.length) {
                for (let index = 0; index < request_1.length; index++) {
                    if (request_2.indexOf(request_1[index]) < 0) {
                        return -1;
                    }
                }
                return 0;
            }
            else if (request_1.length < request_2.length) {
                for (let index = 0; index < request_1.length; index++) {
                    if (request_2.indexOf(request_1[index]) < 0) {
                        return -1;
                    }
                }
                return 0;
            }
            else if (request_1.length > request_2.length) {
                for (let index = 0; index < request_2.length; index++) {
                    if (request_1.indexOf(request_2[index]) < 0) {
                        return -1;
                    }
                }
                return 1;
            }
            else {
                return -1;
            }
        }
    }
    class MyMap {
        constructor() {
            this.data = new Map();
        }
        get(key) {
            return this.data.get(key);
        }
        set(key, value) {
            this.data.set(key, value);
        }
        getSize() {
            return this.data.size;
        }
        getMap() {
            return this.data;
        }
        toJSON() {
            let obj = Object.create(null);
            this.data.forEach((value, key) => {
                obj[key] = value;
            });
            return obj;
        }
        delete(key) {
            this.data.delete(key);
        }
        fromJSON(obj) {
            if (obj) {
                for (let key in obj) {
                    this.data.set(this.keyTransform(key), this.valueTransform(obj[key]));
                }
            }
        }
    }
    class StringKeyMap extends MyMap {
        valueTransform(value) {
            return value;
        }
        keyTransform(key) {
            return key;
        }
    }
    class RequestData {
        constructor(method, params, options, requestTimeoutExpected, withNotification, responseIsChunked) {
            this.method = method;
            this.params = params;
            this.options = options;
            this.requestTimeoutExpected = requestTimeoutExpected;
            this.withNotification = withNotification;
            this.responseIsChunked = responseIsChunked;
            this.response = new ResponseData();
        }
        static empty(identifier) {
            const requestData = new RequestData(null, null, null, null, null, null);
            requestData.identifier = identifier;
            return requestData;
        }
        newResponse(forceSend, fromRevival) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                const responseData = (_a = this.buildResponse) === null || _a === void 0 ? void 0 : _a.call(this, forceSend, fromRevival);
                if (responseData) {
                    const response = responseData.response.pipe(share());
                    this.response.resultSync.next(response);
                    return Promise.all([responseData.sent, toPromise$1(response.pipe(take(1)))]).then(([_, result]) => result);
                }
                else {
                    throw new Error(`Error on buildResponse - ${JSON.stringify(this.compact(), MapOrSet_toJSON)}`);
                }
            });
        }
        complete() {
            this.buildResponse = undefined;
            this.response.complete();
        }
        get executed() {
            return !!this.requestTime;
        }
        compact() {
            var _a;
            return {
                id: (_a = this.identifier) === null || _a === void 0 ? void 0 : _a.idRequest,
                method: this.method,
                options: {
                    timeoutExpected: this.requestTimeoutExpected,
                    timeout: this.options.timeout,
                    notification: this.withNotification,
                    chunked: this.responseIsChunked,
                },
            };
        }
        toJSON() {
            return {
                method: this.method,
                params: this.params,
                requestTimeoutExpected: this.requestTimeoutExpected,
                requestTimeout: this.options.timeout,
                withNotification: this.withNotification,
                responseIsChunked: this.responseIsChunked,
                identifier: this.identifier,
            };
        }
        static fromRequestData(requestData) {
            if (requestData) {
                if (requestData instanceof RequestData) {
                    return requestData;
                }
                else {
                    const _requestData = requestData;
                    const requestDataInstance = new RequestData(_requestData.method, _requestData.params, _requestData.options, _requestData.requestTimeoutExpected, _requestData.withNotification, _requestData.responseIsChunked);
                    requestDataInstance.identifier = new RequestIdentifier(_requestData.identifier.idRequest);
                    return requestDataInstance;
                }
            }
            else {
                return requestData;
            }
        }
    }
    class ResponseData extends Subject {
        constructor() {
            super();
            this.resultSync = new BehaviorSubject(null);
            [this.notification, this.result] = partition(this.asObservable(), (response) => responseIsNotification(response)).map((jsonRpcResponse) => jsonRpcResponse.pipe(map((response) => extractDataFromResponse(response))));
        }
        complete() {
            super.complete();
            this.resultSync.complete();
        }
    }
    class RequestIdentifier {
        constructor(idRequest) {
            this.idRequest = idRequest;
        }
        get idRequest() {
            return this._idRequest;
        }
        set idRequest(idRequest) {
            this._idRequest = idRequest;
            if (idRequest && idRequest > 0) {
                this._idNotification = -1 * idRequest;
            }
        }
        get idNotification() {
            return this._idNotification;
        }
        set idNotification(idNotification) {
            this._idNotification = idNotification;
        }
        toJSON() {
            return {
                idRequest: this.idRequest,
                idNotification: this.idNotification,
            };
        }
    }
    function responseIsNotification(response) {
        return response.id < 0;
    }
    function extractDataFromResponse(response) {
        if (response.error) {
            throw response.error.data;
        }
        else {
            return response.result;
        }
    }

    var RestoreSessionState;
    (function (RestoreSessionState) {
        RestoreSessionState["start"] = "start";
        RestoreSessionState["end"] = "end";
        RestoreSessionState["error"] = "error";
        RestoreSessionState["progress"] = "progress";
    })(RestoreSessionState || (RestoreSessionState = {}));
    var RestoreSessionPhaseState;
    (function (RestoreSessionPhaseState) {
        RestoreSessionPhaseState["start"] = "start";
        RestoreSessionPhaseState["end"] = "end";
        RestoreSessionPhaseState["error"] = "error";
    })(RestoreSessionPhaseState || (RestoreSessionPhaseState = {}));
    var RestoreSessionPhase;
    (function (RestoreSessionPhase) {
        RestoreSessionPhase["restartSessionId"] = "restartSessionId";
        RestoreSessionPhase["resendActiveNotification"] = "resendActiveNotification";
    })(RestoreSessionPhase || (RestoreSessionPhase = {}));
    class RestoreSessionEvent {
        constructor(state, data, error) {
            this.state = state;
            this.data = data;
            this.error = error;
            this.time = new Date();
        }
        set phase(phase) {
            this._phase = phase;
        }
        get phase() {
            return this._phase;
        }
        set phaseState(phaseState) {
            this._phaseState = phaseState;
        }
        get phaseState() {
            return this._phaseState;
        }
    }

    class JsonRpcWebsocket extends AbstractJsonRpcWebsocket {
        constructor(
        client,
        loginRequest, connectionEventSubject, retryOptions, heartbeatInterval, storageUrl) {
            super(client, connectionEventSubject, retryOptions, heartbeatInterval, storageUrl);
            this.client = client;
            this.loginRequest = loginRequest;
            this.stopOpenSocket = false;
            this.onOpenSubscription = Subscription.EMPTY;
            this.restoreSession = new JsonRpcWebsocketRestoreSession(() => {
                let revivalSessionTimeout = 90000;
                try {
                    const requestWithNotificationExecuted = Array.from(this.requestExecuted.values()).filter((request) => request.method && request.executed && request.withNotification);
                    const requestWithNotificationAverageTimeout = requestWithNotificationExecuted.length ? requestWithNotificationExecuted.reduce((totalTimeout, request) => totalTimeout + request.options.timeout, 0) / requestWithNotificationExecuted.length : 0;
                    revivalSessionTimeout = Math.ceil(Math.max(revivalSessionTimeout, requestWithNotificationAverageTimeout * 4));
                }
                catch (e) { }
                this.log.info(`set revival session timeout to ${revivalSessionTimeout} ms`);
                return revivalSessionTimeout;
            });
            this.restoreSession.event
                .pipe(filter((data) => (data ? data.state === RestoreSessionState.start : false)), concatMap(() => this.restoreSessionComplete), catchError(() => EMPTY), map((completeData) => {
                if (completeData === null || completeData === void 0 ? void 0 : completeData.activeNotificationManager) {
                    if (completeData === null || completeData === void 0 ? void 0 : completeData.activeNotificationManager.lowerPriorityNotification.length) {
                        this.log.info("restoreSession ended, start resend lower priority notification");
                        completeData.activeNotificationManager.resendLowerPriority().then(() => {
                            this.log.info("restoreSession - resend lower priority notification ended");
                        }, (err) => {
                            this.log.info("restoreSession - resend lower priority notification error", err);
                        });
                    }
                    else {
                        this.log.info("restoreSession ended with no lower priority notification to request");
                    }
                }
            }))
                .subscribe();
            this.restoreSession.event
                .pipe(tap((data) => {
                if (data) {
                    let message = `restoreSession ${data.state}`;
                    if (RestoreSessionState.progress === data.state) {
                        message += ` - ${data.phase} - ${data.phaseState}`;
                    }
                    if (data.error) {
                        this.log.error(message, data.error);
                    }
                    else {
                        data.data ? this.log.debug(message, data.data) : this.log.debug(message);
                    }
                }
            }))
                .subscribe();
        }
        get restoreSessionEvent() {
            return this.restoreSession.event;
        }
        get restoreSessionComplete() {
            var _a;
            return (_a = this.restoreSession.waitEnd()) !== null && _a !== void 0 ? _a : Promise.resolve();
        }
        waitSendRequest(requestData) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.restoreSession.inProgress && requestData.method !== "restartSessionId") {
                    this.log.debug(`Method '${requestData.method}' will be called after restore connection complete`);
                    yield this.restoreSessionComplete;
                }
            });
        }
        load() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.stopOpenSocket) {
                    throw new StopOpenSocket({
                        code: -10,
                        message: "Socket is blocked by other tab, use loginForce to force use this",
                        clazz: "",
                    });
                }
                else {
                    this.connect();
                }
            });
        }
        getRequestTimeout() {
            return this.client.options.requestTimeout;
        }
        getRequestTimeoutForMethod(method) {
            var _a;
            return this.client.options.mappedRequestTimeout ? (_a = this.client.options.mappedRequestTimeout[method]) !== null && _a !== void 0 ? _a : null : null;
        }
        webSocketConnect() {
            var _a;
            if (!this.firstConnect && ((_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.reconnecting)) {
                this.restoreSession.start();
            }
            super.webSocketConnect();
        }
        retryWait(event, retries) {
            return __awaiter(this, void 0, void 0, function* () {
                if ((event === null || event === void 0 ? void 0 : event.code) === 1006) {
                    try {
                        if (yield toPromise$1(this.loginRequest(30000))) {
                            this.log.info("revival accessToken complete, try to connect socket");
                        }
                        else {
                            throw new AuthorizationRequired({ clazz: "com.telenia.webapi.exception.AuthorizationRequiredException" });
                        }
                    }
                    catch (err) {
                        if (!(err instanceof NoRouteToHost)) {
                            this.log.warn(`error on login [code: ${err.code}, message: ${err.message}]`, err);
                        }
                        if (err instanceof AuthorizationRequired || err instanceof PasswordExpired || err instanceof UserNotEnabledOnMcs || err instanceof UserNotEnabled) {
                            switch (err === null || err === void 0 ? void 0 : err.code) {
                                case AuthorizationRequired.CODE:
                                case PasswordExpired.CODE:
                                case UserNotEnabledOnMcs.CODE:
                                case UserNotEnabled.CODE:
                                    this.onClose(Object.assign(Object.assign({}, event), { code: 4000 + (err === null || err === void 0 ? void 0 : err.code) }));
                                    return false;
                            }
                        }
                        throw err;
                    }
                }
                return true;
            });
        }
        onClose(event) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug("ws onClose");
                let resetSocket = true;
                let stopOpenSocket = true;
                let loginProfileStatus = null;
                switch (event.code - (event.code >= 4400 && event.code < 4500 ? 4000 : 0)) {
                    case AuthorizationRequired.CODE:
                        this.log.debug("ws closed because notlogged");
                        stopOpenSocket = false;
                        loginProfileStatus = LoginProfileStatus.SOCKET_NOTLOGGED;
                        break;
                    case PasswordExpired.CODE:
                        this.log.debug("ws closed because password expired");
                        stopOpenSocket = false;
                        (_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.disconnect();
                        loginProfileStatus = LoginProfileStatus.PASSWORD_EXPIRED;
                        break;
                    case 409:
                        this.log.debug("ws closed because other socket is open");
                        loginProfileStatus = LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE;
                        break;
                    case 499:
                        this.log.debug("ws closed because user force login on other socket");
                        loginProfileStatus = LoginProfileStatus.SOCKET_CLOSED_BY_USER;
                        break;
                    case UserNotEnabledOnMcs.CODE:
                        this.log.debug("ws closed because user not enabled on mcs");
                        loginProfileStatus = LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED_MCS;
                        break;
                    case UserNotEnabled.CODE:
                        this.log.debug("ws closed because user not enabled");
                        loginProfileStatus = LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED;
                        break;
                    default:
                        resetSocket = false;
                        stopOpenSocket = false;
                        this.firstConnect = false;
                        break;
                }
                if (stopOpenSocket) {
                    this.stopOpenSocket = true;
                }
                if (resetSocket) {
                    this.resetSocket();
                }
                if (loginProfileStatus) {
                    this.socketMessage.next({
                        id: -1,
                        result: { status: loginProfileStatus, logged: false, sessionId: this.client.sessionId, username: this.client.username, publicUsername: this.client.publicUsername },
                    });
                }
            });
        }
        onOpen() {
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug("ws onOpen");
                if (!this.firstConnect) {
                    this.restoreSession.start();
                    this.onOpenSubscription.unsubscribe();
                    yield asyncTimeout(200);
                    this.log.debug("Is not first connection, so run restartSessionId");
                    if (this.connected) {
                        this.onOpenSubscription.unsubscribe();
                        this.onOpenSubscription = defer(() => {
                            const completeData = { lastRequestIdResponse: NaN, lastRequestIdExpected: NaN, activeNotificationManager: undefined };
                            return new Observable((observer) => {
                                let onOpenSubscribed = true;
                                (() => __awaiter(this, void 0, void 0, function* () {
                                    try {
                                        let lastRequestId;
                                        this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.start);
                                        try {
                                            lastRequestId = yield toPromise$1(new RequestPromise("restartSessionId", []).withBlockRequestOnReconnect(false).execute(this.client).result);
                                            this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.end);
                                        }
                                        catch (err) {
                                            this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.error, err);
                                            throw err;
                                        }
                                        if (onOpenSubscribed) {
                                            completeData.lastRequestIdResponse = parseInt(lastRequestId);
                                            completeData.lastRequestIdExpected = Array.from(this.requestExecuted.values())
                                                .filter((request) => request && request.method && request.executed && request.withNotification)
                                                .reduce((lastRequestExpected, request) => (request.identifier.idRequest > lastRequestExpected ? request.identifier.idRequest : lastRequestExpected), completeData.lastRequestIdResponse);
                                            if (!isNaN(completeData.lastRequestIdResponse) && completeData.lastRequestIdResponse) {
                                                if (completeData.lastRequestIdResponse !== completeData.lastRequestIdExpected) {
                                                    const request = this.requestExecuted.get(completeData.lastRequestIdExpected);
                                                    this.log.warn(`restartSessionId MISMATCH DETECTED - response: ${completeData.lastRequestIdResponse} expected: ${completeData.lastRequestIdExpected} used by ${request === null || request === void 0 ? void 0 : request.method} at ${request === null || request === void 0 ? void 0 : request.requestTime}`);
                                                }
                                                this.currentIdRequest = completeData.lastRequestIdExpected;
                                            }
                                            else {
                                                if (onOpenSubscribed) {
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.start);
                                                    try {
                                                        completeData.activeNotificationManager = yield this.generateActiveNotificationManager();
                                                        yield completeData.activeNotificationManager.resendHigherPriority();
                                                        this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.end);
                                                    }
                                                    catch (err) {
                                                        this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.error, err);
                                                        throw err;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (err) {
                                        this.log.error("Error on restartSessionId and resendActiveNotification", err);
                                        throw err;
                                    }
                                }))()
                                    .then(() => {
                                    if (onOpenSubscribed)
                                        observer.complete();
                                })
                                    .catch((err) => {
                                    if (onOpenSubscribed)
                                        observer.error(err);
                                });
                                return () => {
                                    this.log.info("restore connection ended");
                                    onOpenSubscribed = false;
                                    this.onOpenSubscription = Subscription.EMPTY;
                                };
                            }).pipe(catchError((err) => {
                                this.log.error("restore connection error", err);
                                this.restoreSession.error(err);
                                return EMPTY;
                            }), finalize(() => {
                                var _a;
                                this.log.info("restore connection complete");
                                this.restoreSession.complete(completeData);
                                (_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.protocolReady();
                            }));
                        }).subscribe();
                    }
                }
            });
        }
        mapRequestExecuted(requestExecuted) {
            return __awaiter(this, void 0, void 0, function* () {
                return (requestExecuted !== null && requestExecuted !== void 0 ? requestExecuted : []).reduce((mappedRequest, element) => {
                    var _a, _b;
                    (((_b = (_a = this.client.options.connectionRevivalLowerPriorityMethos) === null || _a === void 0 ? void 0 : _a.indexOf(element.method)) !== null && _b !== void 0 ? _b : -1) > -1 ? mappedRequest.lower : mappedRequest.higher).push(element);
                    return mappedRequest;
                }, { higher: [], lower: [] });
            });
        }
        resetSocket() {
            var _a;
            this.stopCurrentRequestWithException(new SocketClosed({ code: -80, message: "Socket is closed, response is unavailable", clazz: "" }));
            (_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.disconnect();
            this.firstConnect = true;
            this.currentIdRequest = 1;
        }
        elaborateResponseFromRevival(request, response) {
            const _super = Object.create(null, {
                elaborateResponseFromRevival: { get: () => super.elaborateResponseFromRevival }
            });
            return __awaiter(this, void 0, void 0, function* () {
                if (request.method === "getUserDetail") {
                    const user = response;
                    if (user) {
                        const useProfileRequest = Array.from(this.requestExecuted.values()).find((r) => r.method === "useProfile");
                        if (useProfileRequest) {
                            const useProfileRequestParams = useProfileRequest.params;
                            try {
                                const useProfileAction = useProfileRequestParams[0];
                                useProfileAction.id = user.loggedProfileId;
                                useProfileAction.type = user.chosenDeviceTypeByClient;
                                useProfileAction.device = user.chosenDeviceByClient;
                            }
                            catch (e) { }
                        }
                    }
                }
                else {
                    _super.elaborateResponseFromRevival.call(this, request, response);
                }
            });
        }
    }
    class JsonRpcWebsocketRestoreSession {
        constructor( revivalTimeout) {
            this.revivalTimeout = revivalTimeout;
            this._event = new BehaviorSubject(null);
        }
        get event() {
            return this._event.asObservable();
        }
        start() {
            if (!this.onOpenRevival) {
                this.onOpenRevival = toPromise$1(defer(() => {
                    let completeDataValue;
                    return from(new Promise((onComplete, onError) => {
                        this.onComplete = onComplete;
                        this.onError = onError;
                    })).pipe(timeout(this.revivalTimeout()), tap((completeData) => (completeDataValue = completeData)), finalize(() => {
                        this.onOpenRevival = undefined;
                        this.onComplete = undefined;
                        this.onError = undefined;
                        if (this._event.value && this._event.value.state !== RestoreSessionState.error) {
                            this.notifyState(RestoreSessionState.end, completeDataValue);
                        }
                        this.notifyState(null);
                    }), catchError((e) => {
                        this.notifyState(RestoreSessionState.error, undefined, e);
                        if (e instanceof TimeoutError) {
                            throw TimeoutResponse.newInstance("Timeout has occurred on wait restore connection complete");
                        }
                        else {
                            throw e;
                        }
                    }));
                }));
                this.notifyState(RestoreSessionState.start);
            }
        }
        get inProgress() {
            return !!this.onOpenRevival;
        }
        notifyState(state, data, error) {
            try {
                this._event.next(state ? new RestoreSessionEvent(state, data, error) : null);
            }
            catch (e) { }
        }
        notifyProgress(phase, phaseState, error) {
            if (this.inProgress) {
                const event = new RestoreSessionEvent(RestoreSessionState.progress, error);
                event.phase = phase;
                event.phaseState = phaseState;
                try {
                    this._event.next(event);
                }
                catch (e) { }
            }
        }
        waitEnd() {
            if (this.inProgress) {
                return this.onOpenRevival;
            }
            return;
        }
        complete(data) {
            var _a;
            if (this.inProgress) {
                (_a = this.onComplete) === null || _a === void 0 ? void 0 : _a.call(this, data);
            }
        }
        error(err) {
            var _a;
            if (this.inProgress) {
                (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, err);
            }
        }
    }

    const b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    ((function (bin) {
        var t = {};
        for (var i = 0, l = bin.length; i < l; i++)
            t[bin.charAt(i)] = i;
        return t;
    }))(b64chars);
    function cb_utob(c) {
        if (c.length < 2) {
            var cc = c.charCodeAt(0);
            return cc < 0x80 ? c : cc < 0x800 ? String.fromCharCode(0xc0 | (cc >>> 6)) + String.fromCharCode(0x80 | (cc & 0x3f)) : String.fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + String.fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + String.fromCharCode(0x80 | (cc & 0x3f));
        }
        else {
            var cc = 0x10000 + (c.charCodeAt(0) - 0xd800) * 0x400 + (c.charCodeAt(1) - 0xdc00);
            return String.fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) + String.fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) + String.fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + String.fromCharCode(0x80 | (cc & 0x3f));
        }
    }
    const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
    function utob(u) {
        return u.replace(re_utob, cb_utob);
    }
    function cb_encode(ccc) {
        var padlen = [0, 2, 1][ccc.length % 3], ord = (ccc.charCodeAt(0) << 16) | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | (ccc.length > 2 ? ccc.charCodeAt(2) : 0), chars = [b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? "=" : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? "=" : b64chars.charAt(ord & 63)];
        return chars.join("");
    }
    const _btoa = (btoa !== null && btoa !== void 0 ? btoa : null)
        ? btoa
        : function (b) {
            return b.replace(/[\s\S]{1,3}/g, cb_encode);
        };
    function _encode(u) {
        var isUint8Array = Object.prototype.toString.call(u) === "[object Uint8Array]";
        return isUint8Array ? u.toString("base64") : _btoa(utob(String(u)));
    }
    function encode(u, urisafe) {
        return urisafe
            ? _encode(String(u))
                .replace(/[+\/]/g, function (m0) {
                return m0 == "+" ? "-" : "_";
            })
                .replace(/=/g, "")
            : _encode(u);
    }

    var JitsiMeetAPI$1 = {};

    var external_api_minExports = {};
    var external_api_min = {
      get exports(){ return external_api_minExports; },
      set exports(v){ external_api_minExports = v; },
    };

    (function (module, exports) {
    	!function(e,t){module.exports=t();}(self,(function(){return (()=>{var e={754:(e,t,n)=>{n.d(t,{default:()=>I});var r=n(620),i=n.n(r);class s extends r{constructor(){var e,t;super(...arguments),t={},(e="_storage")in this?Object.defineProperty(this,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):this[e]=t;}clear(){this._storage={};}get length(){return Object.keys(this._storage).length}getItem(e){return this._storage[e]}setItem(e,t){this._storage[e]=t;}removeItem(e){delete this._storage[e];}key(e){const t=Object.keys(this._storage);if(!(t.length<=e))return t[e]}serialize(){return JSON.stringify(this._storage)}}const o=new class extends r{constructor(){super();try{this._storage=window.localStorage,this._localStorageDisabled=!1;}catch(e){}this._storage||(console.warn("Local storage is disabled."),this._storage=new s,this._localStorageDisabled=!0);}isLocalStorageDisabled(){return this._localStorageDisabled}clear(){this._storage.clear(),this.emit("changed");}get length(){return this._storage.length}getItem(e){return this._storage.getItem(e)}setItem(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._storage.setItem(e,t),n||this.emit("changed");}removeItem(e){this._storage.removeItem(e),this.emit("changed");}key(e){return this._storage.key(e)}serialize(){if(this.isLocalStorageDisabled())return this._storage.serialize();const e=this._storage.length,t={};for(let n=0;n<e;n++){const e=this._storage.key(n);t[e]=this._storage.getItem(e);}return JSON.stringify(t)}};var a=n(571);function c(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";console.error(t,e),window.onerror&&window.onerror(t,null,null,null,e);}n(415);const l=["__proto__","constructor","prototype"];function d(e){const t=new RegExp("^([a-z][a-z0-9\\.\\+-]*:)+","gi"),n=t.exec(e);if(n){let r=n[n.length-1].toLowerCase();"http:"!==r&&"https:"!==r&&(r="https:"),(e=e.substring(t.lastIndex)).startsWith("//")&&(e=r+e);}return e}function u(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=[];for(const n in e)try{t.push(`${n}=${encodeURIComponent(JSON.stringify(e[n]))}`);}catch(e){console.warn(`Error encoding ${n}: ${e}`);}return t}function h(e){const t={toString:p};let n,r,i;if(e=e.replace(/\s/g,""),n=new RegExp("^([a-z][a-z0-9\\.\\+-]*:)","gi"),r=n.exec(e),r&&(t.protocol=r[1].toLowerCase(),e=e.substring(n.lastIndex)),n=new RegExp("^(//[^/?#]+)","gi"),r=n.exec(e),r){let i=r[1].substring(2);e=e.substring(n.lastIndex);const s=i.indexOf("@");-1!==s&&(i=i.substring(s+1)),t.host=i;const o=i.lastIndexOf(":");-1!==o&&(t.port=i.substring(o+1),i=i.substring(0,o)),t.hostname=i;}if(n=new RegExp("^([^?#]*)","gi"),r=n.exec(e),r&&(i=r[1],e=e.substring(n.lastIndex)),i?i.startsWith("/")||(i=`/${i}`):i="/",t.pathname=i,e.startsWith("?")){let n=e.indexOf("#",1);-1===n&&(n=e.length),t.search=e.substring(0,n),e=e.substring(n);}else t.search="";return t.hash=e.startsWith("#")?e:"",t}function p(e){const{hash:t,host:n,pathname:r,protocol:i,search:s}=e||this;let o="";return i&&(o+=i),n&&(o+=`//${n}`),o+=r||"/",s&&(o+=s),t&&(o+=t),o}function g(e){let t;t=e.serverURL&&e.room?new URL(e.room,e.serverURL).toString():e.room?e.room:e.url||"";const n=h(d(t));if(!n.protocol){let t=e.protocol||e.scheme;t&&(t.endsWith(":")||(t+=":"),n.protocol=t);}let{pathname:r}=n;if(!n.host){const t=e.domain||e.host||e.hostname;if(t){const{host:e,hostname:i,pathname:s,port:o}=h(d(`org.jitsi.meet://${t}`));e&&(n.host=e,n.hostname=i,n.port=o),"/"===r&&"/"!==s&&(r=s);}}const i=e.roomName||e.room;!i||!n.pathname.endsWith("/")&&n.pathname.endsWith(`/${i}`)||(r.endsWith("/")||(r+="/"),r+=i),n.pathname=r;const{jwt:s,lang:o}=e,a=new URLSearchParams(n.search);s&&a.set("jwt",s);const{defaultLanguage:c}=e.configOverwrite||{};(o||c)&&a.set("lang",o||c);const l=a.toString();l&&(n.search=`?${l}`);let{hash:p}=n;for(const t of ["config","interfaceConfig","devices","userInfo","appData"]){const n=u(e[`${t}Overwrite`]||e[t]||e[`${t}Override`]);if(n.length){let e=`${t}.${n.join(`&${t}.`)}`;p.length?e=`&${e}`:p="#",p+=e;}}return n.hash=p,n.toString()||void 0}const m={window:window.opener||window.parent},f="message";class v{constructor(){let{postisOptions:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.postis=function(e){var t,n=e.scope,r=e.window,i=e.windowForEventListening||window,s=e.allowedOrigin,o={},a=[],c={},l=!1,d="__ready__",u=function(e){var t;try{t=JSON.parse(e.data);}catch(e){return}if((!s||e.origin===s)&&t&&t.postis&&t.scope===n){var r=o[t.method];if(r)for(var i=0;i<r.length;i++)r[i].call(null,t.params);else c[t.method]=c[t.method]||[],c[t.method].push(t.params);}};i.addEventListener("message",u,!1);var h={listen:function(e,t){o[e]=o[e]||[],o[e].push(t);var n=c[e];if(n)for(var r=o[e],i=0;i<r.length;i++)for(var s=0;s<n.length;s++)r[i].call(null,n[s]);delete c[e];},send:function(e){var t=e.method;(l||e.method===d)&&r&&"function"==typeof r.postMessage?r.postMessage(JSON.stringify({postis:!0,scope:n,method:t,params:e.params}),"*"):a.push(e);},ready:function(e){l?e():setTimeout((function(){h.ready(e);}),50);},destroy:function(e){clearInterval(t),l=!1,i&&"function"==typeof i.removeEventListener&&i.removeEventListener("message",u),e&&e();}},p=+new Date+Math.random()+"";return t=setInterval((function(){h.send({method:d,params:p});}),50),h.listen(d,(function(e){if(e===p){clearInterval(t),l=!0;for(var n=0;n<a.length;n++)h.send(a[n]);a=[];}else h.send({method:d,params:e});})),h}({...m,...e}),this._receiveCallback=()=>{},this.postis.listen(f,(e=>this._receiveCallback(e)));}dispose(){this.postis.destroy();}send(e){this.postis.send({method:f,params:e});}setReceiveCallback(e){this._receiveCallback=e;}}const y="request",_="response";class b{constructor(){let{backend:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._listeners=new Map,this._requestID=0,this._responseHandlers=new Map,this._unprocessedMessages=new Set,this.addListener=this.on,e&&this.setBackend(e);}_disposeBackend(){this._backend&&(this._backend.dispose(),this._backend=null);}_onMessageReceived(e){if(e.type===_){const t=this._responseHandlers.get(e.id);t&&(t(e),this._responseHandlers.delete(e.id));}else e.type===y?this.emit("request",e.data,((t,n)=>{this._backend.send({type:_,error:n,id:e.id,result:t});})):this.emit("event",e.data);}dispose(){this._responseHandlers.clear(),this._unprocessedMessages.clear(),this.removeAllListeners(),this._disposeBackend();}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const i=this._listeners.get(e);let s=!1;return i&&i.size&&i.forEach((e=>{s=e(...n)||s;})),s||this._unprocessedMessages.add(n),s}on(e,t){let n=this._listeners.get(e);return n||(n=new Set,this._listeners.set(e,n)),n.add(t),this._unprocessedMessages.forEach((e=>{t(...e)&&this._unprocessedMessages.delete(e);})),this}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}removeListener(e,t){const n=this._listeners.get(e);return n&&n.delete(t),this}sendEvent(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._backend&&this._backend.send({type:"event",data:e});}sendRequest(e){if(!this._backend)return Promise.reject(new Error("No transport backend defined!"));this._requestID++;const t=this._requestID;return new Promise(((n,r)=>{this._responseHandlers.set(t,(e=>{let{error:t,result:i}=e;void 0!==i?n(i):r(void 0!==t?t:new Error("Unexpected response format!"));})),this._backend.send({type:y,data:e,id:t});}))}setBackend(e){this._disposeBackend(),this._backend=e,this._backend.setReceiveCallback(this._onMessageReceived.bind(this));}}(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"hash";const r="search"===n?e.search:e.hash,i={},s=r&&r.substr(1).split("&")||[];if("hash"===n&&1===s.length){const e=s[0];if(e.startsWith("/")&&1===e.split("&").length)return i}return s.forEach((e=>{const n=e.split("="),r=n[0];if(!r||r.split(".").some((e=>l.includes(e))))return;let s;try{if(s=n[1],!t){const e=decodeURIComponent(s).replace(/\\&/,"&");s="undefined"===e?void 0:a.parse(e);}}catch(e){return void c(e,`Failed to parse URL parameter value: ${String(s)}`)}i[r]=s;})),i})(window.location).jitsi_meet_external_api_id;(window.JitsiMeetJS||(window.JitsiMeetJS={}),window.JitsiMeetJS.app||(window.JitsiMeetJS.app={}),window.JitsiMeetJS.app).setExternalTransportBackend=e=>undefined.setBackend(e);var w=n(860);const L=n.n(w)().getLogger("modules/API/external/functions.js");function k(e,t){return e.sendRequest({type:"devices",name:"setDevice",device:t})}const x=["css/all.css","libs/alwaysontop.min.js"],C={addBreakoutRoom:"add-breakout-room",answerKnockingParticipant:"answer-knocking-participant",approveVideo:"approve-video",askToUnmute:"ask-to-unmute",autoAssignToBreakoutRooms:"auto-assign-to-breakout-rooms",avatarUrl:"avatar-url",cancelPrivateChat:"cancel-private-chat",closeBreakoutRoom:"close-breakout-room",displayName:"display-name",e2eeKey:"e2ee-key",email:"email",grantModerator:"grant-moderator",hangup:"video-hangup",initiatePrivateChat:"initiate-private-chat",joinBreakoutRoom:"join-breakout-room",localSubject:"local-subject",kickParticipant:"kick-participant",muteEveryone:"mute-everyone",overwriteConfig:"overwrite-config",overwriteNames:"overwrite-names",password:"password",pinParticipant:"pin-participant",rejectParticipant:"reject-participant",removeBreakoutRoom:"remove-breakout-room",resizeLargeVideo:"resize-large-video",sendChatMessage:"send-chat-message",sendEndpointTextMessage:"send-endpoint-text-message",sendParticipantToRoom:"send-participant-to-room",sendTones:"send-tones",setFollowMe:"set-follow-me",setLargeVideoParticipant:"set-large-video-participant",setMediaEncryptionKey:"set-media-encryption-key",setParticipantVolume:"set-participant-volume",setSubtitles:"set-subtitles",setTileView:"set-tile-view",setVideoQuality:"set-video-quality",startRecording:"start-recording",startShareVideo:"start-share-video",stopRecording:"stop-recording",stopShareVideo:"stop-share-video",subject:"subject",submitFeedback:"submit-feedback",toggleAudio:"toggle-audio",toggleCamera:"toggle-camera",toggleCameraMirror:"toggle-camera-mirror",toggleChat:"toggle-chat",toggleE2EE:"toggle-e2ee",toggleFilmStrip:"toggle-film-strip",toggleLobby:"toggle-lobby",toggleModeration:"toggle-moderation",toggleParticipantsPane:"toggle-participants-pane",toggleRaiseHand:"toggle-raise-hand",toggleShareAudio:"toggle-share-audio",toggleShareScreen:"toggle-share-screen",toggleSubtitles:"toggle-subtitles",toggleTileView:"toggle-tile-view",toggleVirtualBackgroundDialog:"toggle-virtual-background",toggleVideo:"toggle-video"},E={"avatar-changed":"avatarChanged","audio-availability-changed":"audioAvailabilityChanged","audio-mute-status-changed":"audioMuteStatusChanged","breakout-rooms-updated":"breakoutRoomsUpdated","browser-support":"browserSupport","camera-error":"cameraError","chat-updated":"chatUpdated","content-sharing-participants-changed":"contentSharingParticipantsChanged","data-channel-opened":"dataChannelOpened","device-list-changed":"deviceListChanged","display-name-change":"displayNameChange","email-change":"emailChange","error-occurred":"errorOccurred","endpoint-text-message-received":"endpointTextMessageReceived","face-landmark-detected":"faceLandmarkDetected","feedback-submitted":"feedbackSubmitted","feedback-prompt-displayed":"feedbackPromptDisplayed","filmstrip-display-changed":"filmstripDisplayChanged","iframe-dock-state-changed":"iframeDockStateChanged","incoming-message":"incomingMessage","knocking-participant":"knockingParticipant",log:"log","mic-error":"micError","moderation-participant-approved":"moderationParticipantApproved","moderation-participant-rejected":"moderationParticipantRejected","moderation-status-changed":"moderationStatusChanged","mouse-enter":"mouseEnter","mouse-leave":"mouseLeave","mouse-move":"mouseMove","outgoing-message":"outgoingMessage","participant-joined":"participantJoined","participant-kicked-out":"participantKickedOut","participant-left":"participantLeft","participant-role-changed":"participantRoleChanged","password-required":"passwordRequired","proxy-connection-event":"proxyConnectionEvent","raise-hand-updated":"raiseHandUpdated","recording-link-available":"recordingLinkAvailable","recording-status-changed":"recordingStatusChanged","video-ready-to-close":"readyToClose","video-conference-joined":"videoConferenceJoined","video-conference-left":"videoConferenceLeft","video-availability-changed":"videoAvailabilityChanged","video-mute-status-changed":"videoMuteStatusChanged","video-quality-changed":"videoQualityChanged","screen-sharing-status-changed":"screenSharingStatusChanged","dominant-speaker-changed":"dominantSpeakerChanged","subject-change":"subjectChange","suspend-detected":"suspendDetected","tile-view-changed":"tileViewChanged","toolbar-button-clicked":"toolbarButtonClicked"};let R=0;function O(e,t){e._numberOfParticipants+=t;}function S(e){let t;return "string"==typeof e&&null!==String(e).match(/([0-9]*\.?[0-9]+)(em|pt|px|%)$/)?t=e:"number"==typeof e&&(t=`${e}px`),t}class I extends(i()){constructor(e){super();for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];const{roomName:i="",width:s="100%",height:a="100%",parentNode:c=document.body,configOverwrite:l={},interfaceConfigOverwrite:d={},jwt:u,lang:h,onload:p,invitees:m,devices:f,userInfo:y,e2eeKey:_}=function(e){if(!e.length)return {};switch(typeof e[0]){case"string":case"undefined":{const[t,n,r,i,s,o,a,c,l]=e;return {roomName:t,width:n,height:r,parentNode:i,configOverwrite:s,interfaceConfigOverwrite:o,jwt:a,onload:c,lang:l}}case"object":return e[0];default:throw new Error("Can't parse the arguments!")}}(n),w=o.getItem("jitsiLocalStorage");this._parentNode=c,this._url=function(e){return g({...arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},url:`https://${e}/#jitsi_meet_external_api_id=${R}`})}(e,{configOverwrite:l,interfaceConfigOverwrite:d,jwt:u,lang:h,roomName:i,devices:f,userInfo:y,appData:{localStorageContent:w}}),this._createIFrame(a,s,p),this._transport=new b({backend:new v({postisOptions:{allowedOrigin:new URL(this._url).origin,scope:`jitsi_meet_external_api_${R}`,window:this._frame.contentWindow}})}),Array.isArray(m)&&m.length>0&&this.invite(m),this._tmpE2EEKey=_,this._isLargeVideoVisible=!0,this._numberOfParticipants=0,this._participants={},this._myUserID=void 0,this._onStageParticipant=void 0,this._setupListeners(),R++;}_createIFrame(e,t,n){const r=`jitsiConferenceFrame${R}`;this._frame=document.createElement("iframe"),this._frame.allow="camera; microphone; display-capture; autoplay; clipboard-write",this._frame.src=this._url,this._frame.name=r,this._frame.id=r,this._setSize(e,t),this._frame.setAttribute("allowFullScreen","true"),this._frame.style.border=0,n&&(this._frame.onload=n),this._frame=this._parentNode.appendChild(this._frame);}_getAlwaysOnTopResources(){const e=this._frame.contentWindow,t=e.document;let n="";const r=t.querySelector("base");if(r&&r.href)n=r.href;else {const{protocol:t,host:r}=e.location;n=`${t}//${r}`;}return x.map((e=>new URL(e,n).href))}_getFormattedDisplayName(e){const{formattedDisplayName:t}=this._participants[e]||{};return t}_getOnStageParticipant(){return this._onStageParticipant}_getLargeVideo(){const e=this.getIFrame();if(this._isLargeVideoVisible&&e&&e.contentWindow&&e.contentWindow.document)return e.contentWindow.document.getElementById("largeVideo")}_getParticipantVideo(e){const t=this.getIFrame();if(t&&t.contentWindow&&t.contentWindow.document)return void 0===e||e===this._myUserID?t.contentWindow.document.getElementById("localVideo_container"):t.contentWindow.document.querySelector(`#participant_${e} video`)}_setSize(e,t){const n=S(e),r=S(t);void 0!==n&&(this._height=e,this._frame.style.height=n),void 0!==r&&(this._width=t,this._frame.style.width=r);}_setupListeners(){this._transport.on("event",(e=>{let{name:t,...n}=e;const r=n.id;switch(t){case"video-conference-joined":void 0!==this._tmpE2EEKey&&(this.executeCommand(C.e2eeKey,this._tmpE2EEKey),this._tmpE2EEKey=void 0),this._myUserID=r,this._participants[r]={avatarURL:n.avatarURL};case"participant-joined":this._participants[r]=this._participants[r]||{},this._participants[r].displayName=n.displayName,this._participants[r].formattedDisplayName=n.formattedDisplayName,O(this,1);break;case"participant-left":O(this,-1),delete this._participants[r];break;case"display-name-change":{const e=this._participants[r];e&&(e.displayName=n.displayname,e.formattedDisplayName=n.formattedDisplayName);break}case"email-change":{const e=this._participants[r];e&&(e.email=n.email);break}case"avatar-changed":{const e=this._participants[r];e&&(e.avatarURL=n.avatarURL);break}case"on-stage-participant-changed":this._onStageParticipant=r,this.emit("largeVideoChanged");break;case"large-video-visibility-changed":this._isLargeVideoVisible=n.isVisible,this.emit("largeVideoChanged");break;case"video-conference-left":O(this,-1),delete this._participants[this._myUserID];break;case"video-quality-changed":this._videoQuality=n.videoQuality;break;case"local-storage-changed":return o.setItem("jitsiLocalStorage",n.localStorageContent),!0}const i=E[t];return !!i&&(this.emit(i,n),!0)}));}addEventListener(e,t){this.on(e,t);}addEventListeners(e){for(const t in e)this.addEventListener(t,e[t]);}captureLargeVideoScreenshot(){return this._transport.sendRequest({name:"capture-largevideo-screenshot"})}dispose(){this.emit("_willDispose"),this._transport.dispose(),this.removeAllListeners(),this._frame&&this._frame.parentNode&&this._frame.parentNode.removeChild(this._frame);}executeCommand(e){if(e in C){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this._transport.sendEvent({data:n,name:C[e]});}else console.error("Not supported command name.");}executeCommands(e){for(const t in e)this.executeCommand(t,e[t]);}getAvailableDevices(){return function(e){return e.sendRequest({type:"devices",name:"getAvailableDevices"}).catch((e=>(L.error(e),{})))}(this._transport)}getContentSharingParticipants(){return this._transport.sendRequest({name:"get-content-sharing-participants"})}getCurrentDevices(){return function(e){return e.sendRequest({type:"devices",name:"getCurrentDevices"}).catch((e=>(L.error(e),{})))}(this._transport)}getCustomAvatarBackgrounds(){return this._transport.sendRequest({name:"get-custom-avatar-backgrounds"})}getLivestreamUrl(){return this._transport.sendRequest({name:"get-livestream-url"})}getParticipantsInfo(){const e=Object.keys(this._participants),t=Object.values(this._participants);return t.forEach(((t,n)=>{t.participantId=e[n];})),t}getVideoQuality(){return this._videoQuality}isAudioAvailable(){return this._transport.sendRequest({name:"is-audio-available"})}isDeviceChangeAvailable(e){return function(e,t){return e.sendRequest({deviceType:t,type:"devices",name:"isDeviceChangeAvailable"})}(this._transport,e)}isDeviceListAvailable(){return function(e){return e.sendRequest({type:"devices",name:"isDeviceListAvailable"})}(this._transport)}isMultipleAudioInputSupported(){return function(e){return e.sendRequest({type:"devices",name:"isMultipleAudioInputSupported"})}(this._transport)}invite(e){return Array.isArray(e)&&0!==e.length?this._transport.sendRequest({name:"invite",invitees:e}):Promise.reject(new TypeError("Invalid Argument"))}isAudioMuted(){return this._transport.sendRequest({name:"is-audio-muted"})}isAudioDisabled(){return this._transport.sendRequest({name:"is-audio-disabled"})}isModerationOn(e){return this._transport.sendRequest({name:"is-moderation-on",mediaType:e})}isParticipantForceMuted(e,t){return this._transport.sendRequest({name:"is-participant-force-muted",participantId:e,mediaType:t})}isParticipantsPaneOpen(){return this._transport.sendRequest({name:"is-participants-pane-open"})}isSharingScreen(){return this._transport.sendRequest({name:"is-sharing-screen"})}isStartSilent(){return this._transport.sendRequest({name:"is-start-silent"})}getAvatarURL(e){const{avatarURL:t}=this._participants[e]||{};return t}getDeploymentInfo(){return this._transport.sendRequest({name:"deployment-info"})}getDisplayName(e){const{displayName:t}=this._participants[e]||{};return t}getEmail(e){const{email:t}=this._participants[e]||{};return t}getIFrame(){return this._frame}getNumberOfParticipants(){return this._numberOfParticipants}isVideoAvailable(){return this._transport.sendRequest({name:"is-video-available"})}isVideoMuted(){return this._transport.sendRequest({name:"is-video-muted"})}listBreakoutRooms(){return this._transport.sendRequest({name:"list-breakout-rooms"})}pinParticipant(e){this.executeCommand("pinParticipant",e);}removeEventListener(e){this.removeAllListeners(e);}removeEventListeners(e){e.forEach((e=>this.removeEventListener(e)));}resizeLargeVideo(e,t){e<=this._width&&t<=this._height&&this.executeCommand("resizeLargeVideo",e,t);}sendProxyConnectionEvent(e){this._transport.sendEvent({data:[e],name:"proxy-connection-event"});}setAudioInputDevice(e,t){return function(e,t,n){return k(e,{id:n,kind:"audioinput",label:t})}(this._transport,e,t)}setAudioOutputDevice(e,t){return function(e,t,n){return k(e,{id:n,kind:"audiooutput",label:t})}(this._transport,e,t)}setLargeVideoParticipant(e){this.executeCommand("setLargeVideoParticipant",e);}setVideoInputDevice(e,t){return function(e,t,n){return k(e,{id:n,kind:"videoinput",label:t})}(this._transport,e,t)}startRecording(e){this.executeCommand("startRecording",e);}stopRecording(e){this.executeCommand("stopRecording",e);}toggleE2EE(e){this.executeCommand("toggleE2EE",e);}async setMediaEncryptionKey(e){const{key:t,index:n}=e;if(t){const e=await crypto.subtle.exportKey("raw",t);this.executeCommand("setMediaEncryptionKey",JSON.stringify({exportedKey:Array.from(new Uint8Array(e)),index:n}));}else this.executeCommand("setMediaEncryptionKey",JSON.stringify({exportedKey:!1,index:n}));}}},872:(e,t,n)=>{e.exports=n(754).default;},571:(e,t)=>{const n=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/;t.parse=function(e){const r="object"==typeof(arguments.length<=1?void 0:arguments[1])&&(arguments.length<=1?void 0:arguments[1]),i=(arguments.length<=1?0:arguments.length-1)>1||!r?arguments.length<=1?void 0:arguments[1]:void 0,s=(arguments.length<=1?0:arguments.length-1)>1&&(arguments.length<=2?void 0:arguments[2])||r||{},o=JSON.parse(e,i);return "ignore"===s.protoAction?o:o&&"object"==typeof o&&e.match(n)?(t.scan(o,s),o):o},t.scan=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[e];for(;n.length;){const e=n;n=[];for(const r of e){if(Object.prototype.hasOwnProperty.call(r,"__proto__")){if("remove"!==t.protoAction)throw new SyntaxError("Object contains forbidden prototype property");delete r.__proto__;}for(const e in r){const t=r[e];t&&"object"==typeof t&&n.push(r[e]);}}}},t.safeParse=function(e,n){try{return t.parse(e,n)}catch(e){return null}};},369:(e,t,n)=>{var r=n(7);function i(e,t){this.logStorage=e,this.stringifyObjects=!(!t||!t.stringifyObjects)&&t.stringifyObjects,this.storeInterval=t&&t.storeInterval?t.storeInterval:3e4,this.maxEntryLength=t&&t.maxEntryLength?t.maxEntryLength:1e4,Object.keys(r.levels).forEach(function(e){this[r.levels[e]]=function(){this._log.apply(this,arguments);}.bind(this,e);}.bind(this)),this.storeLogsIntervalID=null,this.queue=[],this.totalLen=0,this.outputCache=[];}i.prototype.stringify=function(e){try{return JSON.stringify(e)}catch(e){return "[object with circular refs?]"}},i.prototype.formatLogMessage=function(e){for(var t="",n=1,i=arguments.length;n<i;n++){var s=arguments[n];!this.stringifyObjects&&e!==r.levels.ERROR||"object"!=typeof s||(s=this.stringify(s)),t+=s,n!==i-1&&(t+=" ");}return t.length?t:null},i.prototype._log=function(){var e=arguments[1],t=this.formatLogMessage.apply(this,arguments);if(t){var n=this.queue[this.queue.length-1],r=n&&n.text;r===t?n.count+=1:(this.queue.push({text:t,timestamp:e,count:1}),this.totalLen+=t.length);}this.totalLen>=this.maxEntryLength&&this._flush(!0,!0);},i.prototype.start=function(){this._reschedulePublishInterval();},i.prototype._reschedulePublishInterval=function(){this.storeLogsIntervalID&&(window.clearTimeout(this.storeLogsIntervalID),this.storeLogsIntervalID=null),this.storeLogsIntervalID=window.setTimeout(this._flush.bind(this,!1,!0),this.storeInterval);},i.prototype.flush=function(){this._flush(!1,!0);},i.prototype._flush=function(e,t){this.totalLen>0&&(this.logStorage.isReady()||e)&&(this.logStorage.isReady()?(this.outputCache.length&&(this.outputCache.forEach(function(e){this.logStorage.storeLogs(e);}.bind(this)),this.outputCache=[]),this.logStorage.storeLogs(this.queue)):this.outputCache.push(this.queue),this.queue=[],this.totalLen=0),t&&this._reschedulePublishInterval();},i.prototype.stop=function(){this._flush(!1,!1);},e.exports=i;},7:e=>{var t={trace:0,debug:1,info:2,log:3,warn:4,error:5};o.consoleTransport=console;var n=[o.consoleTransport];o.addGlobalTransport=function(e){-1===n.indexOf(e)&&n.push(e);},o.removeGlobalTransport=function(e){var t=n.indexOf(e);-1!==t&&n.splice(t,1);};var r={};function i(){var e={methodName:"",fileLocation:"",line:null,column:null},t=new Error,n=t.stack?t.stack.split("\n"):[];if(!n||n.length<3)return e;var r=null;return n[3]&&(r=n[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/)),!r||r.length<=4?(0===n[2].indexOf("log@")?e.methodName=n[3].substr(0,n[3].indexOf("@")):e.methodName=n[2].substr(0,n[2].indexOf("@")),e):(e.methodName=r[1],e.fileLocation=r[2],e.line=r[3],e.column=r[4],e)}function s(){var e=arguments[0],s=arguments[1],o=Array.prototype.slice.call(arguments,2);if(!(t[s]<e.level))for(var a=!(e.options.disableCallerInfo||r.disableCallerInfo)&&i(),c=n.concat(e.transports),l=0;l<c.length;l++){var d=c[l],u=d[s];if(u&&"function"==typeof u){var h=[];h.push((new Date).toISOString()),e.id&&h.push("["+e.id+"]"),a&&a.methodName.length>1&&h.push("<"+a.methodName+">: ");var p=h.concat(o);u.bind(d).apply(d,p);}}}function o(e,n,r,i){this.id=n,this.options=i||{},this.transports=r,this.transports||(this.transports=[]),this.level=t[e];for(var o=Object.keys(t),a=0;a<o.length;a++)this[o[a]]=s.bind(null,this,o[a]);}o.setGlobalOptions=function(e){r=e||{};},o.prototype.setLevel=function(e){this.level=t[e];},e.exports=o,o.levels={TRACE:"trace",DEBUG:"debug",INFO:"info",LOG:"log",WARN:"warn",ERROR:"error"};},860:(e,t,n)=>{var r=n(7),i=n(369),s={},o=[],a=r.levels.TRACE;e.exports={addGlobalTransport:function(e){r.addGlobalTransport(e);},removeGlobalTransport:function(e){r.removeGlobalTransport(e);},setGlobalOptions:function(e){r.setGlobalOptions(e);},getLogger:function(e,t,n){var i=new r(a,e,t,n);return e?(s[e]=s[e]||[],s[e].push(i)):o.push(i),i},setLogLevelById:function(e,t){for(var n=t?s[t]||[]:o,r=0;r<n.length;r++)n[r].setLevel(e);},setLogLevel:function(e){a=e;for(var t=0;t<o.length;t++)o[t].setLevel(e);for(var n in s){var r=s[n]||[];for(t=0;t<r.length;t++)r[t].setLevel(e);}},levels:r.levels,LogCollector:i};},415:e=>{function t(){return new DOMException("The request is not allowed","NotAllowedError")}e.exports=async function(e){try{await async function(e){if(!navigator.clipboard)throw t();return navigator.clipboard.writeText(e)}(e);}catch(n){try{await async function(e){const n=document.createElement("span");n.textContent=e,n.style.whiteSpace="pre",n.style.webkitUserSelect="auto",n.style.userSelect="all",document.body.appendChild(n);const r=window.getSelection(),i=window.document.createRange();r.removeAllRanges(),i.selectNode(n),r.addRange(i);let s=!1;try{s=window.document.execCommand("copy");}finally{r.removeAllRanges(),window.document.body.removeChild(n);}if(!s)throw t()}(e);}catch(e){throw e||n||t()}}};},620:e=>{var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this);}e.exports=s,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,s),r(n);}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments));}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,{once:!0});}(e,i);}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,n,r){var i,s,o,l;if(a(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=o.length,l=d,console&&console.warn&&console.warn(l);}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return [];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):g(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function g(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function m(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else {if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(s){r.once&&e.removeEventListener(t,i),n(s);}));}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e;}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0;},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return !1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return !1;if("function"==typeof c)r(c,this,t);else {var l=c.length,d=g(c,l);for(n=0;n<l;++n)r(d[n],this,t);}return !0},s.prototype.addListener=function(e,t){return l(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return l(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,s,o;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop();}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t);}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,s=Object.keys(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return "function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},s.prototype.listenerCount=p,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}return n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]});},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n(872)})()}));
    } (external_api_min));
    getDefaultExportFromCjs(external_api_minExports);

    Object.defineProperty(JitsiMeetAPI$1, "__esModule", { value: true });
    var JitsiMeetExternalAPI = JitsiMeetAPI$1.JitsiMeetExternalAPI = void 0;
    var JitsiMeetAPI = external_api_minExports;
    JitsiMeetExternalAPI = JitsiMeetAPI$1.JitsiMeetExternalAPI = JitsiMeetAPI;

    class Omnidesk {
        initJitsi(url, options) {
            this.methods = new JitsiMeetExternalAPI(url, options);
        }
        setDisplayName(name) {
            this.methods.executeCommand("displayName", name);
        }
        setPassword(password) {
            this.methods.executeCommand("password", password);
        }
        toggleLobby(enable) {
            this.methods.executeCommand("toggleLobby", enable);
        }
        sendTones(tones, duration, pause) {
            this.methods.executeCommand("sendTones", { tones, duration, pause });
        }
        subject(subject) {
            this.methods.executeCommand("subject", subject);
        }
        toggleAudio() {
            this.methods.executeCommand("toggleAudio");
        }
        toggleVideo() {
            this.methods.executeCommand("toggleVideo");
        }
        toggleFilmStrip() {
            this.methods.executeCommand("toggleFilmStrip");
        }
        toggleChat() {
            this.methods.executeCommand("toggleChat");
        }
        toggleShareScreen() {
            this.methods.executeCommand("toggleShareScreen");
        }
        toggleTileView() {
            this.methods.executeCommand("toggleTileView");
        }
        hangUp() {
            this.methods.executeCommand("hangup");
        }
        setEmail(email) {
            this.methods.executeCommand("email", email);
        }
        setAvatar(avatarUrl) {
            this.methods.executeCommand("avatarUrl", avatarUrl);
        }
        sendEndpointTextMessage(receiverParticipantId, text) {
            this.methods.executeCommand("sendEndpointTextMessage", receiverParticipantId, text);
        }
        setLargeVideoParticipant(participantId) {
            this.methods.executeCommand("setLargeVideoParticipant", participantId);
        }
        setVideoQuality(resolution) {
            this.methods.executeCommand("setVideoQuality", resolution);
        }
        muteEveryone() {
            this.methods.executeCommand("muteEveryone");
        }
        startRecording(recordingOptions) {
            this.methods.executeCommand("startRecording", recordingOptions);
        }
        stopRecording(mode) {
            this.methods.executeCommand("stopRecording", mode);
        }
        initiatePrivateChat(participantID) {
            this.methods.executeCommand("initiatePrivateChat", participantID);
        }
        cancelPrivateChat() {
            this.methods.executeCommand("cancelPrivateChat");
        }
        getContentSharingParticipants() {
            return this.methods.executeCommand("getContentSharingParticipants");
        }
        kickParticipant(participantId) {
            this.methods.executeCommand("kickParticipant", participantId);
        }
        overwriteConfig(config) {
            this.methods.executeCommand("overwriteConfig", config);
        }
        setTileView(enabled) {
            this.methods.executeCommand("setTileView", enabled);
        }
        toggleCamera() {
            this.methods.executeCommand("toggleCamera");
        }
        toggleCameraMirror() {
            this.methods.executeCommand("toggleCameraMirror");
        }
        toggleRaisedHand() {
            this.methods.executeCommand("toggleRaiseHand");
        }
        toggleVirtualBackgroundDialog() {
            this.methods.executeCommand("toggleVirtualBackgroundDialog");
        }
        setParticipantVolume(participantId, volume) {
            this.methods.executeCommand("setParticipantVolume", participantId, volume);
        }
        askToUnmute(participantId) {
            this.methods.executeCommand("askToUnmute", participantId);
        }
        captureLargeVideoScreenshot() {
            return this.methods.captureLargeVideoScreenshot();
        }
        getAvailableDevices() {
            return this.methods.getAvailableDevices();
        }
        getCurrentDevices() {
            return this.methods.getCurrentDevices();
        }
        getDeploymentInfo() {
            return this.methods.getDeploymentInfo();
        }
        getLivestreamUrl() {
            return this.methods.getLivestreamUrl();
        }
        getParticipantsInfo() {
            return this.methods.getParticipantsInfo();
        }
        getVideoQuality() {
            return this.methods.getVideoQuality();
        }
        isDeviceChangeAvailable(deviceType) {
            return this.methods.isDeviceChangeAvailable(deviceType);
        }
        isDeviceListAvailable() {
            return this.methods.isDeviceListAvailable();
        }
        isMultipleAudioInputSupported() {
            return this.methods.isMultipleAudioInputSupported();
        }
        pinParticipant(participantId) {
            this.methods.pinParticipant(participantId);
        }
        resizeLargeVideo(width, height) {
            this.methods.resizeLargeVideo(width, height);
        }
        setAudioInputDevice(deviceLabel, deviceId) {
            this.methods.setAudioInputDevice(deviceLabel, deviceId);
        }
        setAudioOutputDevice(deviceLabel, deviceId) {
            this.methods.setAudioOutputDevice(deviceLabel, deviceId);
        }
        setVideoInputDevice(deviceLabel, deviceId) {
            this.methods.setVideoInputDevice(deviceLabel, deviceId);
        }
        getNumberOfParticipants() {
            return this.methods.getNumberOfParticipants();
        }
        getAvatarURL(participantId) {
            return this.methods.getAvatarURL(participantId);
        }
        getDisplayName(participantId) {
            return this.methods.getDisplayName(participantId);
        }
        getEmail(participantId) {
            return this.methods.getEmail(participantId);
        }
        getIframe() {
            return this.methods.getIFrame();
        }
        isAudioDisabled() {
            return this.methods.isAudioDisabled();
        }
        isAudioMuted() {
            return this.methods.isAudioMuted();
        }
        isVideoMuted() {
            return this.methods.isVideoMuted();
        }
        isAudioAvailable() {
            return this.methods.isAudioAvailable();
        }
        isVideoAvailable() {
            return this.methods.isVideoAvailable();
        }
        isModerationOn(mediaType) {
            return this.methods.isModerationOn(mediaType);
        }
        isParticipantForceMuted(participantId, mediaType) {
            return this.methods.isParticipantForceMuted(participantId, mediaType);
        }
        isParticipantsPaneOpen() {
            return this.methods.isParticipantsPaneOpen();
        }
        isStartSilent() {
            return this.methods.isStartSilent();
        }
        listBreakoutRooms() {
            return this.methods.listBreakoutRooms();
        }
        dispose() {
            this.methods.dispose();
        }
        cameraErrorEvent(callback) {
            this.methods.addEventListener("cameraError", callback);
        }
        avatarChangedEvent(callback) {
            this.methods.addEventListener("avatarChanged", callback);
        }
        audioAvailabilityChangedEvent(callback) {
            this.methods.addEventListener("audioAvailabilityChanged", callback);
        }
        audioMuteStatusChangedEvent(callback) {
            this.methods.addEventListener("audioMuteStatusChanged", callback);
        }
        browserSupportEvent(callback) {
            this.methods.addEventListener("browserSupport", callback);
        }
        contentSharingParticipantsChangedEvent(callback) {
            this.methods.addEventListener("contentSharingParticipantsChanged", callback);
        }
        dataChannelOpenedtEvent(callback) {
            this.methods.addEventListener("dataChannelOpened", callback);
        }
        endpointTextMessageReceivedEvent(callback) {
            this.methods.addEventListener("endpointTextMessageReceived", callback);
        }
        faceLandmarkDetectedEvent(callback) {
            this.methods.addEventListener("faceLandmarkDetected", callback);
        }
        errorOccurredEvent(callback) {
            this.methods.addEventListener("errorOccurred", callback);
        }
        knockingParticipantEvent(callback) {
            this.methods.addEventListener("knockingParticipant", callback);
        }
        largeVideoChangedEvent(callback) {
            this.methods.addEventListener("largeVideoChanged", callback);
        }
        logEvent(callback) {
            this.methods.addEventListener("log", callback);
        }
        micErrorEvent(callback) {
            this.methods.addEventListener("micError", callback);
        }
        screenSharingStatusChangedEvent(callback) {
            this.methods.addEventListener("screenSharingStatusChanged", callback);
        }
        dominantSpeakerChangedEvent(callback) {
            this.methods.addEventListener("dominantSpeakerChanged", callback);
        }
        raiseHandUpdatedEvent(callback) {
            this.methods.addEventListener("raiseHandUpdated", callback);
        }
        tileViewChangedEvent(callback) {
            this.methods.addEventListener("tileViewChanged", callback);
        }
        chatUpdatedEvent(callback) {
            this.methods.addEventListener("chatUpdated", callback);
        }
        incomingMessageEvent(callback) {
            this.methods.addEventListener("incomingMessage", callback);
        }
        mouseEnterEvent(callback) {
            this.methods.addEventListener("mouseEnter", callback);
        }
        mouseLeaveEvent(callback) {
            this.methods.addEventListener("mouseLeave", callback);
        }
        mouseMoveEvent(callback) {
            this.methods.addEventListener("mouseMove", callback);
        }
        toolbarButtonClickedEvent(callback) {
            this.methods.addEventListener("toolbarButtonClicked", callback);
        }
        outgoingMessageEvent(callback) {
            this.methods.addEventListener("outgoingMessage", callback);
        }
        displayNameChangeEvent(callback) {
            this.methods.addEventListener("displayNameChange", callback);
        }
        deviceListChangedEvent(callback) {
            this.methods.addEventListener("deviceListChanged", callback);
        }
        emailChangeEvent(callback) {
            this.methods.addEventListener("emailChange", callback);
        }
        feedbackSubmittedEvent(callback) {
            this.methods.addEventListener("feedbackSubmitted", callback);
        }
        filmstripDisplayChangedEvent(callback) {
            this.methods.addEventListener("filmstripDisplayChanged", callback);
        }
        moderationStatusChangedEvent(callback) {
            this.methods.addEventListener("moderationStatusChanged", callback);
        }
        moderationParticipantApprovedEvent(callback) {
            this.methods.addEventListener("moderationParticipantApproved", callback);
        }
        moderationParticipantRejectedEvent(callback) {
            this.methods.addEventListener("moderationParticipantRejected", callback);
        }
        participantJoinedEvent(callback) {
            this.methods.addEventListener("participantJoined", callback);
        }
        participantKickedOutEvent(callback) {
            this.methods.addEventListener("participantKickedOut", callback);
        }
        participantLeftEvent(callback) {
            this.methods.addEventListener("participantLeft", callback);
        }
        participantRoleChangedEvent(callback) {
            this.methods.addEventListener("participantRoleChanged", callback);
        }
        passwordRequiredEvent(callback) {
            this.methods.addEventListener("passwordRequired", callback);
        }
        videoConferenceJoinedEvent(callback) {
            this.methods.addEventListener("videoConferenceJoined", callback);
        }
        videoConferenceLeftEvent(callback) {
            this.methods.addEventListener("videoConferenceLeft", callback);
        }
        videoAvailabilityChangedEvent(callback) {
            this.methods.addEventListener("videoAvailabilityChanged", callback);
        }
        videoMuteStatusChangedEvent(callback) {
            this.methods.addEventListener("videoMuteStatusChanged", callback);
        }
        videoQualityChangedEvent(callback) {
            this.methods.addEventListener("videoQualityChanged", callback);
        }
        readyToCloseEvent(callback) {
            this.methods.addEventListener("readyToClose", callback);
        }
        subjectChangeEvent(callback) {
            this.methods.addEventListener("subjectChange", callback);
        }
        suspendDetectedEvent(callback) {
            this.methods.addEventListener("suspendDetected", callback);
        }
        recordingStatusChangedEvent(callback) {
            this.methods.addEventListener("recordingStatusChanged", callback);
        }
        getJitsiMeetApi() {
            return this.methods;
        }
    }

    class WebapiClientServiceMethod extends MethodExecutor {
        constructor(
        client,
        channelNotification,
        commandNotification,
        disconnectOtherSocket,
        loginRequest,
        remeberMe,
        exitAfterLogout) {
            super(client);
            this.client = client;
            this.disconnectOtherSocket = disconnectOtherSocket;
            this.loginRequest = loginRequest;
            this.remeberMe = remeberMe;
            this.exitAfterLogout = exitAfterLogout;
            this.methodExecutor = new WebapiClientMethodExecutor(this);
            this.callInfoNotification = new NotificationManager(client, "callInfo", () => this.executeRequestPromiseUpdate(new RequestPromiseUpdate("startCallNotify", [])).response, channelNotification, (callInfo) => new ChannelEvent(channelIdToChannelType(callInfo.channelid), callInfo, "server"));
            this.commandNotification = new NotificationManager(client, "clientCommand", () => this.executeRequestPromiseUpdate(new RequestPromiseUpdate("startClientCommandNotify", [])).response, commandNotification, identity$1);
        }
        _loadTransport(request) {
            var _a;
            if (request && this.transport.isReconnecting() && ((_a = request.options.blockRequestOnReconnect) !== null && _a !== void 0 ? _a : !this.client.isRequestEnableUntilReconnect())) {
                throw new ReconnectingInProgress({
                    clazz: "",
                    code: -8,
                    message: "Recconnecting is in progress, please retry after connection is complete",
                });
            }
            super._loadTransport(request);
        }
        loginForce() {
            return __awaiter(this, void 0, void 0, function* () {
                this.disconnectOtherSocket();
                return this._loadTransport();
            });
        }
        loginCustom(customData, rememberMe, requestTimeout) {
            this.remeberMe(rememberMe);
            return toPromise$1(this.loginRequest(requestTimeout, LoginType.Custom, customData).pipe(tap((loginResult) => {
                if (loginResult.sessionId) {
                    try {
                        this._loadTransport();
                    }
                    catch (error) {
                        this.transport.emitErrorInternal(error, entityErrorResolver);
                    }
                }
            })));
        }
        loginByAccessToken(accessToken, rememberMe, requestTimeout) {
            this.remeberMe(rememberMe !== null && rememberMe !== void 0 ? rememberMe : false);
            return toPromise$1(this.loginRequest(requestTimeout, LoginType.AccessToken, accessToken).pipe(tap((loginResult) => {
                if (loginResult.sessionId) {
                    try {
                        this._loadTransport();
                    }
                    catch (error) {
                        this.transport.emitErrorInternal(error, entityErrorResolver);
                    }
                }
            })));
        }
        loginByJwtToken(jwtToken, rememberMe, requestTimeout) {
            this.remeberMe(rememberMe !== null && rememberMe !== void 0 ? rememberMe : false);
            return toPromise$1(this.loginRequest(requestTimeout, LoginType.JwtToken, jwtToken).pipe(tap((loginResult) => {
                if (loginResult.sessionId) {
                    try {
                        this._loadTransport();
                    }
                    catch (error) {
                        this.transport.emitErrorInternal(error, entityErrorResolver);
                    }
                }
            })));
        }
        login(username, password, rememberMe, requestTimeout) {
            this.remeberMe(rememberMe);
            return toPromise$1(this.loginRequest(requestTimeout, LoginType.Credential, username, password).pipe(tap((loginResult) => {
                if (loginResult.sessionId) {
                    try {
                        this._loadTransport();
                    }
                    catch (error) {
                        this.transport.emitErrorInternal(error, entityErrorResolver);
                    }
                }
            })));
        }
        logoutAndExit(action, requestTimeout) {
            return this.exitAfterLogout(this.methodExecutor.logout(action, requestTimeout));
        }
        startCallNotify(requestTimeout) {
            return this.callInfoNotification.start(requestTimeout);
        }
        stopCallNotify() {
            return this.callInfoNotification.stop();
        }
        startClientCommandNotify(requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.client.options.userAgent.isTVox()) {
                    if (this.commandNotification.started) {
                        return true;
                    }
                    else {
                        return this.commandNotification.start(requestTimeout);
                    }
                }
                else {
                    throw new Error("Only TVox is allowed to call startClientCommandNotify");
                }
            });
        }
        stopClientCommandNotify() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.commandNotification.started) {
                    return this.commandNotification.stop();
                }
                else {
                    return true;
                }
            });
        }
        get webrtcMethod() {
            if (!this.webrtcMethodInstance) {
                this.webrtcMethodInstance = {
                    startVideoEchoTest: ({ callId, media, webrtcField }, options) => {
                        return toPromise$1(new RequestPromise("startVideoEchoTest", [callId, MediaParam.toCallMedia(media), webrtcField]).withOptions(options).execute(this.client).result);
                    },
                    dial: ({ dialParam }, options) => __awaiter(this, void 0, void 0, function* () {
                        const result = yield toPromise$1(new RequestPromise("dial", [...new WebrtcDialParams(dialParam).toRequestParams(this.client.phoneManagerActive)]).withOptions(options).execute(this.client).result);
                        return result ? dialParam.webrtcFields.clientid : null;
                    }),
                    answer: ({ callId, media, webrtcField, customFields }, options) => {
                        return toPromise$1(new RequestPromise("answer", [callId, MediaParam.toCallMedia(media), webrtcField, customFields !== null && customFields !== void 0 ? customFields : null]).withOptions(options).execute(this.client).result);
                    },
                    hold: ({ callId }, options) => {
                        return toPromise$1(new RequestPromise("hold", [callId]).withOptions(options).execute(this.client).result);
                    },
                    unhold: ({ callId }, options) => {
                        return toPromise$1(new RequestPromise("unhold", [callId]).withOptions(options).execute(this.client).result);
                    },
                    attendedTransfer: ({ callId, heldCallId }, options) => {
                        return toPromise$1(new RequestPromise("attendedTransfer", [callId, heldCallId]).withOptions(options).execute(this.client).result);
                    },
                    blindTransfer: ({ callId, accessCode, number, data }, options) => {
                        return toPromise$1(new RequestPromise("blindTransfer", [callId, accessCode, number, data]).withOptions(options).execute(this.client).result);
                    },
                    sendDTMF: ({ callId, dtmf }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("sendDTMF", [callId, dtmf]).withOptions(options).execute(this.client).result);
                    }),
                    cancel: ({ callId }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("cancel", [callId]).withOptions(options).execute(this.client).result);
                    }),
                    createUserInteraction: ({ createUserInteraction }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("createUserInteraction", [createUserInteraction]).withOptions(options).execute(this.client).result);
                    }),
                    removeCallFromUserInteraction: ({ callId }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("removeCallFromUserInteraction", [callId]).withOptions(options).execute(this.client).result);
                    }),
                    updateWebRTCFields: ({ callId, media, webrtcField }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("updateWebRTCFields", [callId, MediaParam.toCallMedia(media), webrtcField]).withOptions(options).execute(this.client).result);
                    }),
                    getWebrtcConfiguration: ({}, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("getWebrtcConfiguration", []).withOptions(options).execute(this.client).result);
                    }),
                    setWebRTCAvailableMedia: ({ media }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("setWebRTCAvailableMedia", [MediaParam.toCallMedia(media)]).withOptions(options).execute(this.client).result);
                    }),
                    mute: ({ callId, media, fields }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("mute", [callId, MediaParam.toCallMedia(media), fields ? fields : null]).withOptions(options).execute(this.client).result);
                    }),
                    unmute: ({ callId, media, fields }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("unmute", [callId, MediaParam.toCallMedia(media), fields ? fields : null]).withOptions(options).execute(this.client).result);
                    }),
                    startVideoOnCall: ({ callId, fields }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("startVideoOnCall", [callId, fields ? fields : null]).withOptions(options).execute(this.client).result);
                    }),
                    stopVideoOnCall: ({ callId, fields }, options) => __awaiter(this, void 0, void 0, function* () {
                        return toPromise$1(new RequestPromise("stopVideoOnCall", [callId, fields ? fields : null]).withOptions(options).execute(this.client).result);
                    }),
                };
            }
            return this.webrtcMethodInstance;
        }
    }

    class WebapiClient {
        constructor(options) {
            this._forceOpenSocket = false;
            this._localStoreManager = new LocalStoreManager();
            this._loginProfileSubject = new BehaviorSubject({ status: LoginProfileStatus.UNKNOWN, logged: false });
            this._connectionEventSubject = new BehaviorSubject({ connected: false });
            this._webrtcControlMessageNotifier = new Subject();
            this._omnidesk = new Omnidesk();
            if (options === undefined) {
                throw new TypeError("WebapiClient - Not enough arguments on constructor");
            }
            this._instanceId = Array.from({ length: 10 }, () => Math.random().toString(36)[3]).join("");
            this._log = Log$1.create("", this.instanceId, new DefaultLogger(new WebapiClientLogConfig(options.logConfig)));
            this._log.info("Initialize new Client, configuration: ", options);
            try {
                this._options = new WebapiConfig(options);
            }
            catch (e) {
                this._log.fatal("Error in configuration", e);
                throw e;
            }
            this._log.info("Configuration used: ", this.options);
            this._logger = new WebapiClientLogger(this);
            this._log.client = this;
            this._initializeClient();
        }
        get methodsErrorResolver() {
            return exceptionInitializer;
        }
        get omnidesk() {
            return this._omnidesk;
        }
        get webrtc() {
            return this._webrtc;
        }
        set webrtc(webrtc) {
            if (webrtc) {
                if (!webrtc.client) {
                    this._log.debug("Attach WebRTCManager to client");
                }
                this._webrtc = webrtc;
                this._webrtc.attachToClient(this, this._serviceMethods.webrtcMethod);
                this._webrtc.initFromClient(this._webrtcControlMessageNotifier);
            }
            else {
                if (this._webrtc) {
                    this._log.debug("Disable and unlink WebRTCManager to client");
                    this._webrtc.stop();
                    this._webrtc = webrtc;
                }
            }
        }
        get instanceId() {
            return this._instanceId;
        }
        get phoneManagerActive() {
            return this._options.phoneManagerActive;
        }
        set phoneManagerActive(phoneManagerActive) {
            if (this._options.phoneManagerActive !== phoneManagerActive) {
                const previousValue = this._options.phoneManagerActive;
                this._options.phoneManagerActive = !!phoneManagerActive;
                this.notifyPhoneManagerActive().then((result) => {
                    if (!result) {
                        this._log.warn(`reset phoneManagerActive to '${previousValue}'`);
                        this._options.phoneManagerActive = previousValue;
                    }
                });
            }
        }
        get logger() {
            return this._logger;
        }
        get options() {
            return this._options;
        }
        get transport() {
            return this._transport;
        }
        get serviceMethods() {
            return this._serviceMethods;
        }
        get methods() {
            return this.serviceMethods.methodExecutor;
        }
        get loginProfile() {
            return this._loginProfileSubject.asObservable();
        }
        get loginProfileLoggedOnNewSession() {
            return this._loginProfileLoggedOnNewSession;
        }
        get connectionEvent() {
            return this._connectionEventSubject.asObservable();
        }
        get restoreSessionEvent() {
            return this._transport.restoreSessionEvent;
        }
        get channelNotification() {
            return this._channelNotification;
        }
        get callNotification() {
            return this._channelNotification.pipe(map((data) => data.callInfo));
        }
        get sessionId() {
            return this._sessionId;
        }
        get deviceId() {
            return this._deviceId;
        }
        get username() {
            return this._username;
        }
        get publicUsername() {
            return this._publicUsername;
        }
        get accessToken() {
            return this._getAccessToken(false);
        }
        _initializeClient() {
            const sessionAccessToken = this._getAccessToken(true);
            if (!this.options.rememberMe) {
                this.cleanAllCredential(false);
            }
            if (this.options.url.startsWith("ws")) {
                this.options.url = this.options.url.replace(new RegExp("^ws"), "http");
            }
            this._loginProfileSubject.pipe(skip(1)).subscribe((statusEvent) => {
                this._log.debug("Login profile status changed", statusEvent);
            });
            this._connectionEventSubject.subscribe((event) => {
                if (event.connected) {
                    this._forceOpenSocket = false;
                }
            });
            this._transport = new JsonRpcWebsocket(this, (timeout) => {
                var _a;
                const accessToken = (_a = this._getAccessToken()) !== null && _a !== void 0 ? _a : undefined;
                return accessToken
                    ? this._loginRequest(timeout, LoginType.AccessToken, accessToken)
                    : of({
                        accessToken: accessToken,
                        deviceId: this.deviceId,
                        sessionId: this.sessionId,
                        username: this.username,
                    });
            }, this._connectionEventSubject, this.options.retryOptions, this.options.heartbeatInterval, this.options.storageUrl);
            this.transport.loading = false;
            this._serviceMethods = new WebapiClientServiceMethod(this, this.handleChannelNotification(new Subject()), this.handleClientCommandNotification(new Subject()), () => {
                this._forceOpenSocket = true;
                this._transport.stopOpenSocket = false;
            }, (timeout, loginType, usernameOrAccessToken, password) => this._loginRequest(timeout, loginType, usernameOrAccessToken, password), (rememberMe) => {
                this.options.rememberMe = rememberMe ? true : false;
                if (!this.options.rememberMe) {
                    this._cleanAccessToken(false);
                }
            }, (logoutResponse) => __awaiter(this, void 0, void 0, function* () {
                let response = yield logoutResponse;
                if (response) {
                    this.cleanAllCredential(true);
                    this.disconnect();
                }
                return response;
            }));
            const loginProfileResult = this.transport.getResponseOf(1 );
            const loginProfileEvent = merge(loginProfileResult.result, loginProfileResult.notification).pipe(share());
            const loggedLoginProfile = loginProfileEvent.pipe(filter((event) => { var _a; return (_a = event.logged) !== null && _a !== void 0 ? _a : false; }));
            this._loginProfileLoggedOnNewSession = loggedLoginProfile.pipe(distinctUntilChanged((prev, curr) => {
                if (prev.sessionId === curr.sessionId) {
                    this._log.verbose(`SessionId not changed, ${curr.sessionId}`);
                    return true;
                }
                else {
                    this._log.info(`SessionId changed - previous ${prev.sessionId}, current ${curr.sessionId}`);
                    return false;
                }
            }), share());
            loginProfileEvent.subscribe((loginProfile) => this._handleLoginProfileEvent(loginProfile));
            this._updateLoginProfileSubject(loggedLoginProfile.pipe(take(1))).subscribe({
                error: (err) => {
                    this._log.error("Error on update loginProfile", err);
                },
            });
            merge(this._loginProfileLoggedOnNewSession.pipe(filter(() => !!!this._transport.isReconnecting()), map(() => "new session of loggeed user")), this._transport.restoreSessionEvent.pipe(filter((data) => (data ? data.phase === RestoreSessionPhase.resendActiveNotification && data.phaseState === RestoreSessionPhaseState.end : false)), concatMap(() => this._transport.restoreSessionComplete), catchError(() => EMPTY), map(() => "restore session ended with resending active notifications")))
                .pipe(concatMap((reason) => {
                if (reason) {
                    this._log.info(`call setPhoneManagerActive due ${reason}`);
                }
                return this.notifyPhoneManagerActive();
            }))
                .subscribe();
            const currentAccessToken = sessionAccessToken || this._getAccessToken();
            if (currentAccessToken) {
                if (this.options.selfManagedLogin) {
                    this._log.info(`Find stored accessToken ${currentAccessToken} and options.selfManagedLogin is true, try login`);
                    setTimeout(() => {
                        this.oneTimeLoginByAccessToken(currentAccessToken);
                    });
                }
                else {
                    this.cleanAllCredential(true);
                    this._log.info(`Find stored accessToken ${currentAccessToken} but options.selfManagedLogin is false, nothing to do`);
                }
            }
            else {
                this._updateLoginProfileSubject(throwError(() => new Error("Credential requested, wait login"))).subscribe({
                    error: () => {
                        this._log.info("Credential requested, wait login");
                    },
                });
            }
        }
        notifyPhoneManagerActive() {
            return __awaiter(this, void 0, void 0, function* () {
                let result = false;
                try {
                    result = yield this.methods.setPhoneManagerActive({ active: this.phoneManagerActive });
                }
                catch (e) {
                    this._log.error("error on setPhoneManagerActive", e);
                }
                if (this._options.userAgent.isTVox()) {
                    if (this.phoneManagerActive) {
                        try {
                            if (!(yield this._serviceMethods.startClientCommandNotify())) {
                                this._log.error(`unable to startClientCommandNotify, server response false`);
                            }
                        }
                        catch (err) {
                            this._log.error(`error on startClientCommandNotify`, err);
                        }
                    }
                    else {
                        try {
                            yield this._serviceMethods.stopClientCommandNotify();
                        }
                        catch (err) {
                            this._log.error(`error on stopClientCommandNotify`, err);
                        }
                    }
                }
                return result;
            });
        }
        handleChannelNotification(channelNotification) {
            this._channelNotification = merge(channelNotification, this._webrtcControlMessageNotifier.pipe(filter((webrtcControlMessage) => !webrtcControlMessage._isFromServer), map((webrtcControlMessage) => new ChannelEvent(webrtcControlMessage._realChannelType, buildCallInfoFromWebrtcControlMessage(webrtcControlMessage), "client")))).pipe(map((callInfo) => adjustCallInfoWithMediaInfo(callInfo, this.webrtc)), share());
            this._channelNotification
                .pipe(filter((channelEvent) => {
                if (channelEvent && channelEvent.callInfo && channelEvent.isGeneratedByServer()) {
                    switch (channelEvent.channel) {
                        case ChannelType.PhoneCall:
                        case ChannelType.CallBack:
                            const callInfo = channelEvent.callInfo;
                            return !!((callInfo.deviceType === ExtenType.WEBRTC && callInfo.device && !!this.webrtc) );
                        case ChannelType.Video:
                        case ChannelType.Omnidesk:
                            return true;
                        default:
                            return false;
                    }
                }
                else {
                    return false;
                }
            }), map((channelEvent) => buildWebrtcControlMessageFromChannelEvent(channelEvent, channelEvent.channel === ChannelType.Video ? { direction: CallDirection.inbound } : null)))
                .subscribe(this._webrtcControlMessageNotifier);
            return channelNotification;
        }
        handleClientCommandNotification(commandNotification) {
            const executeCommand = (command) => __awaiter(this, void 0, void 0, function* () {
                this._log.debug(`HandleClientCommand - Manage message ${command.id} - ${command.command}`);
                let result;
                try {
                    if (this.options.remoteCommandHandler) {
                        result = yield this.options.remoteCommandHandler(command);
                    }
                    else {
                        let commandIsForDevice = true, methodResult = true;
                        if (isDialCommand(command)) {
                            methodResult = !!(yield this.methods.dial(Object.assign(Object.assign({}, command), { channelId: channelIdToChannelType(command.channelId), media: buildMediaParam(command.media) })));
                        }
                        else if (isAnswerCommand(command)) {
                            methodResult = !!(yield this.methods.answerOnChannel(ChannelType.PhoneCall, command.callId, buildMediaParam(command.media)));
                        }
                        else if (isCancelCommand(command)) {
                            methodResult = !!(yield this.methods.cancel(command.callId));
                        }
                        else if (isHoldCommand(command)) {
                            methodResult = !!(yield this.methods.hold(command.callId));
                        }
                        else if (isUnholdCommand(command)) {
                            methodResult = !!(yield this.methods.unhold(command.callId));
                        }
                        else if (isAttendedTransferCommand(command)) {
                            methodResult = !!(yield this.methods.attendedTransfer(command.callId, command.heldCallId, buildMediaParam(command.media)));
                        }
                        else if (isBlindTransferCommand(command)) {
                            methodResult = !!(yield this.methods.blindTransfer(command.callId, command.accessCode, command.number, command.data || []));
                        }
                        else if (isSendDTMFCommand(command)) {
                            methodResult = !!(yield this.methods.sendDTMF(command.callId, command.dtmf, true));
                        }
                        else if (isDialATXferOnGenericDeviceCommand(command)) {
                            methodResult = !!(yield this.methods.dialATXferOnGenericDevice(command));
                        }
                        else if (isCancelTransferOnGenericDeviceCommand(command)) {
                            methodResult = !!(yield this.methods.cancelTransferOnGenericDevice(command));
                        }
                        else if (isSendFeedbackCommand(command)) {
                            commandIsForDevice = false;
                        }
                        else {
                            commandIsForDevice = false;
                        }
                        if (commandIsForDevice) {
                            result = methodResult ? { result: ClientCommandResult.OK } : { result: ClientCommandResult.FAILED, resultMessage: "false" };
                        }
                        else {
                            result = { result: ClientCommandResult.FAILED, resultMessage: "Not implemented" };
                        }
                    }
                }
                catch (e) {
                    this._log.error(`HandleClientCommand - Error on manage message ${command.id} - ${command.command}`, e);
                    result = { result: ClientCommandResult.FAILED, resultMessage: `error on execute ${command.command} command - ${e}` };
                }
                return { command, result };
            });
            const notifyCommandReceived = (commandNotification) => {
                return commandNotification.pipe(tap((command) => {
                    this._log.debug(`HandleClientCommand - Receiving message ${command.id}`, command);
                }), mergeMap((command) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        if (yield toPromise$1(this.methods.sendClientCommandResponse({ command: command.command, commandId: command.id, result: ClientCommandResult.RECEIVED }).result)) {
                            this._log.debug(`HandleClientCommand - server confirm RECEIVED ${command.id} - ${command.command}`);
                        }
                        else {
                            this._log.debug(`HandleClientCommand - server not confirm RECEIVED ${command.id} - ${command.command}`);
                        }
                    }
                    catch (e) {
                        this._log.warn(`HandleClientCommand - error on send command RECEIVED ${command.id} - ${command.command}`);
                    }
                    return command;
                })));
            };
            const commandNotified = commandNotification.asObservable();
            let commandWithResult;
            if (this.options.remoteCommandHandler) {
                commandWithResult = notifyCommandReceived(commandNotified).pipe(mergeMap(executeCommand));
            }
            else {
                const [phoneDeviceCommandNotified, otherCommandNotified] = partition(commandNotified, (command) => {
                    switch (command.command) {
                        case ClientCommandRequest.DIAL:
                        case ClientCommandRequest.ANSWER:
                        case ClientCommandRequest.HOLD:
                        case ClientCommandRequest.UNHOLD:
                        case ClientCommandRequest.CANCEL:
                        case ClientCommandRequest.ATTENDED_TRANSFER:
                        case ClientCommandRequest.BLIND_TRANSFER:
                        case ClientCommandRequest.SEND_DTMF:
                        case ClientCommandRequest.ATXFER_GENERIC_DEVICE:
                        case ClientCommandRequest.CANCEL_ON_TRANSFER_GENERIC_DEVICE:
                            return true;
                        default:
                            return false;
                    }
                });
                commandWithResult = merge(notifyCommandReceived(phoneDeviceCommandNotified).pipe(concatMap(executeCommand)),
                notifyCommandReceived(otherCommandNotified).pipe(mergeMap(executeCommand)));
            }
            commandWithResult.subscribe(({ command, result }) => __awaiter(this, void 0, void 0, function* () {
                if (!result || !result.result) {
                    result = { result: ClientCommandResult.FAILED, resultMessage: "Unknow result" };
                }
                try {
                    yield toPromise$1(this.methods.sendClientCommandResponse({ command: command.command, commandId: command.id, result: result.result, resultMessage: result.resultMessage }).result);
                }
                catch (e) { }
                this._log.debug(`HandleClientCommand - End manage message ${command.id} - ${command.command}`);
            }));
            return commandNotification;
        }
        _handleLoginProfileEvent(loginProfile) {
            if (loginProfile && (this.username == null || this.username === loginProfile.username)) {
                if (this.username === null && loginProfile.username) {
                    this._username = loginProfile.username;
                }
                if (loginProfile.publicUsername && this._publicUsername !== loginProfile.publicUsername) {
                    this._publicUsername = loginProfile.publicUsername;
                }
                switch (loginProfile.status) {
                    case LoginProfileStatus.REFRESH:
                        if (loginProfile.sessionId && loginProfile.sessionId !== this.sessionId) {
                            this._sessionId = loginProfile.sessionId;
                        }
                        if (loginProfile.accessToken && loginProfile.accessToken !== this._getAccessToken()) {
                            this._saveAccessToken(loginProfile.accessToken);
                            let lastStatus = this._loginProfileSubject.value;
                            this._loginProfileSubject.next(loginProfile);
                            this._loginProfileSubject.next(lastStatus);
                        }
                        break;
                    case LoginProfileStatus.NOTLOGGED:
                        this.transport.disconnect();
                        this._loginProfileSubject.next(loginProfile);
                        break;
                    case LoginProfileStatus.SOCKET_NOTLOGGED:
                    case LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE:
                    case LoginProfileStatus.SOCKET_CLOSED_BY_USER:
                        this.cleanAllCredential(false);
                        this._loginProfileSubject.next(loginProfile);
                        break;
                    case LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED_MCS:
                    case LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED:
                        this._loginProfileSubject.next(loginProfile);
                        break;
                    case LoginProfileStatus.PASSWORD_EXPIRED:
                        this.cleanAllCredential(true);
                        loginProfile.username = loginProfile.username || this.username || undefined;
                        this._loginProfileSubject.next(loginProfile);
                        break;
                    default:
                        if (loginProfile.sessionId && loginProfile.sessionId !== this.sessionId) {
                            this._sessionId = loginProfile.sessionId;
                        }
                        if (loginProfile.accessToken && loginProfile.accessToken !== this._getAccessToken()) {
                            this._saveAccessToken(loginProfile.accessToken);
                        }
                        let accessToken = this._getAccessToken();
                        if (loginProfile.status !== LoginProfileStatus.LOGGED && accessToken) {
                            this._serviceMethods.loginByAccessToken(accessToken, this.options.rememberMe);
                        }
                        else {
                            this._loginProfileSubject.next(loginProfile);
                        }
                        break;
                }
            }
        }
        _loginRequest(requestTimeout, loginType, usernameOrAccessToken, password) {
            let result = from(fetch(this.generateUrl(ServiceScope.login, { loginType, ignoreAccessToken: true, ignoreSessionId: loginType === LoginType.Credential }), {
                mode: "cors",
                credentials: "include",
                cache: "no-cache",
                method: "GET",
                headers: {
                    Authorization: loginType === LoginType.Credential ? "Basic " + encode(usernameOrAccessToken + ":" + password) : "Bearer " + usernameOrAccessToken,
                },
            }));
            if (requestTimeout) {
                result = result.pipe(timeout(requestTimeout));
            }
            return result.pipe(catchError((err) => {
                if (err instanceof TimeoutError) {
                    throw err;
                }
                else {
                    throw new NoRouteToHost({
                        clazz: "",
                        code: -3,
                        message: err.message,
                    });
                }
            }), switchMap((fetchResponse) => defer(() => __awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e, _f;
                if (fetchResponse.ok) {
                    const loginResponse = yield fetchResponse.text();
                    if (loginResponse) {
                        try {
                            let response = JSON.parse(loginResponse);
                            this._saveAccessToken(response.accessToken);
                            this._localStoreManager.deleteData("teleniaWebApiDeviceId");
                            this._deviceId = response.deviceId;
                            this._sessionId = response.sessionId;
                            this._username = response.username;
                            this._publicUsername = response.publicUsername;
                            return response;
                        }
                        catch (e) {
                            throw new WebAPI({
                                clazz: "",
                                code: -1,
                                message: "Login response is invalid",
                            });
                        }
                    }
                    else {
                        throw new WebAPI({
                            clazz: "",
                            code: -2,
                            message: "Login response without accessToken",
                        });
                    }
                }
                else {
                    switch (fetchResponse.status) {
                        case 403:
                            throw PasswordExpired.newInstance((_a = fetchResponse.headers.get("TeleniaUser")) !== null && _a !== void 0 ? _a : "", (_b = fetchResponse.headers.get("PublicTeleniaUser")) !== null && _b !== void 0 ? _b : "", "true" === fetchResponse.headers.get("TeleniaCheckSecurityEnabled"));
                        case 497:
                            throw UserNotEnabledOnMcs.newInstance((_c = fetchResponse.headers.get("TeleniaUser")) !== null && _c !== void 0 ? _c : "", (_d = fetchResponse.headers.get("PublicTeleniaUser")) !== null && _d !== void 0 ? _d : "");
                        case 498:
                            throw UserNotEnabled.newInstance((_e = fetchResponse.headers.get("TeleniaUser")) !== null && _e !== void 0 ? _e : "", (_f = fetchResponse.headers.get("PublicTeleniaUser")) !== null && _f !== void 0 ? _f : "");
                        default:
                            throw new AuthorizationRequired({
                                clazz: "com.telenia.webapi.exception.AuthorizationRequiredException",
                                sessionId: this.sessionId,
                                code: fetchResponse.status,
                                message: fetchResponse.statusText,
                            });
                    }
                }
            }))));
        }
        _updateLoginProfileSubject(loginPromise) {
            return loginPromise.pipe(tap((response) => {
                setTimeout(() => {
                    if (response) {
                        if (response.accessToken && response.accessToken !== this._getAccessToken()) {
                            this._saveAccessToken(response.accessToken);
                        }
                        this._loginProfileSubject.next(response);
                    }
                });
            }), catchError((err) => {
                if (!(err instanceof SocketClosed)) {
                    let newStatus = LoginProfileStatus.RETRY;
                    if (err instanceof StopOpenSocket) {
                        newStatus = LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE;
                    }
                    setTimeout(() => this._loginProfileSubject.next({ status: newStatus, logged: false }));
                }
                throw err;
            }));
        }
        _cleanAccessToken(clearCookie) {
            try {
                if (this._intervalShortCookies) {
                    clearInterval(this._intervalShortCookies);
                    this._intervalShortCookies = null;
                }
                this._localStoreManager.deleteData("teleniaWebApiAccessToken");
                if (clearCookie) {
                    this._log.info("Removing access token teleniaWebApiAccessToken");
                    this._saveAccessToken();
                }
            }
            catch (e) { }
        }
        _getAccessToken(sessionOnly) {
            let cookieAccessToken = null;
            if (!this._accessToken) {
                let sessionAccessToken = this._localStoreManager.getData(this._getSessionStorageAccessTokenKey("teleniaWebApiAccessToken"));
                if (sessionAccessToken) {
                    cookieAccessToken = sessionAccessToken;
                }
                else if (!sessionOnly) {
                    if (navigator.cookieEnabled) {
                        let currentCookie = parse_1(document.cookie);
                        if (currentCookie && currentCookie.teleniaWebApiAccessToken) {
                            cookieAccessToken = currentCookie.teleniaWebApiAccessToken;
                        }
                    }
                }
            }
            return this._accessToken ? this._accessToken : cookieAccessToken;
        }
        _getSessionStorageAccessTokenKey(prefix) {
            return prefix + (this.options.cookie_path ? ("/" + this.options.cookie_path.trim()).replace("//", ".").replace("/", ".") : "") || "";
        }
        _saveAccessToken(accessToken) {
            this._accessToken = accessToken;
            this._localStoreManager.saveSessionData(accessToken !== null && accessToken !== void 0 ? accessToken : "", this._getSessionStorageAccessTokenKey("teleniaWebApiAccessToken"));
            if (navigator.cookieEnabled) {
                let cookieOpt = {};
                if (this.options.cookie_path) {
                    cookieOpt.path = this.options.cookie_path;
                }
                if (accessToken) {
                    if (this.options.selfManagedLogin && this.options.rememberMe) {
                        cookieOpt.expires = new Date(new Date().getTime() + 2592000000);
                    }
                    else {
                        if (this.options.selfManagedLogin) {
                            cookieOpt.expires = new Date(new Date().getTime() + 60000);
                            if (!this._intervalShortCookies) {
                                this._intervalShortCookies = setInterval(() => {
                                    let currentAccessToken = this._getAccessToken();
                                    if (currentAccessToken) {
                                        this._saveAccessToken(currentAccessToken);
                                    }
                                }, 50000);
                            }
                        }
                        else {
                            cookieOpt.expires = new Date(0);
                        }
                    }
                }
                else {
                    cookieOpt.expires = new Date(0);
                }
                if (accessToken) {
                    if (this.options.rememberMe) {
                        this._log.debug("Save accessToken to teleniaWebApiAccessToken", cookieOpt);
                    }
                }
                else {
                    this._log.debug("Clear accessToken from teleniaWebApiAccessToken", cookieOpt);
                }
                document.cookie = serialize_1("teleniaWebApiAccessToken", accessToken !== null && accessToken !== void 0 ? accessToken : "", cookieOpt);
            }
        }
        isRequestEnableUntilReconnect() {
            return !!this.options.requestEnableUntilReconnect;
        }
        generateUrl(serviceScope, option) {
            var _a, _b;
            const { loginType, path, ignoreAccessToken, ignoreSessionId, ignoreDeviceId } = option !== null && option !== void 0 ? option : {};
            const sessionId = this.sessionId;
            const accessToken = this._getAccessToken();
            const deviceId = this.deviceId;
            const multisession = this.options.multisession;
            let url = this.options.url;
            switch (serviceScope) {
                case ServiceScope.websocket:
                    url = url.replace(new RegExp("^http", "i"), "ws");
                    url += path !== null && path !== void 0 ? path : "/ws/endpoint";
                    break;
                case ServiceScope.login:
                    let loginUrlPath = path;
                    if (!path) {
                        switch (loginType) {
                            case LoginType.JwtToken:
                                loginUrlPath = "/login_jwt";
                                break;
                            case LoginType.Custom:
                                loginUrlPath = "/login_custom";
                                break;
                            default:
                                loginUrlPath = "/login";
                                break;
                        }
                    }
                    url = url.replace(new RegExp("^ws", "i"), "http");
                    url += loginUrlPath;
                    break;
                case ServiceScope.upload:
                    url = url.replace(new RegExp("^ws", "i"), "http");
                    url += path !== null && path !== void 0 ? path : "/upload";
                    break;
            }
            const sessionParam = [];
            const sessionParams = (_a = this.options.sessionParams) !== null && _a !== void 0 ? _a : {};
            for (const key in sessionParams) {
                if ((key !== null && key !== void 0 ? key : false) && ((_b = sessionParams[key]) !== null && _b !== void 0 ? _b : false)) {
                    sessionParam.push(`${key.trim()}=${sessionParams[key].trim()}`);
                }
            }
            if (serviceScope !== ServiceScope.upload) {
                sessionParam.push(`agent=${this.options.userAgent.type.trim().toLowerCase()}__${LIB_VERSION$1}__${`${this.options.userAgent.version}`.trim()}`);
            }
            if (this._forceOpenSocket) {
                sessionParam.push("force=true");
            }
            if (multisession && serviceScope !== ServiceScope.upload) {
                sessionParam.push("multisession=true");
            }
            if (accessToken && !ignoreAccessToken) {
                sessionParam.push(`access_token=${accessToken}`);
            }
            if (deviceId && !ignoreDeviceId) {
                sessionParam.push(`deviceid=${deviceId}`);
            }
            if (sessionId && !ignoreSessionId) {
                sessionParam.push(`jsessionid=${sessionId}`);
            }
            if (sessionParam.length > 0) {
                url += ";" + sessionParam.map((p) => p.replace(";", "")).join(";");
            }
            return url;
        }
        disconnect() {
            let notLoggedEvent = Object.assign({}, this._loginProfileSubject.value);
            notLoggedEvent.status = LoginProfileStatus.NOTLOGGED;
            notLoggedEvent.logged = false;
            this._handleLoginProfileEvent(notLoggedEvent);
        }
        cleanAllCredential(clearPermanentData) {
            this._sessionId = undefined;
            this._cleanAccessToken(clearPermanentData);
        }
        oneTimeLoginByAccessToken(accessToken) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.oneTimeLoginByAccessTokenDone) {
                    this._log.warn(`oneTimeLoginByAccessToken was just called at ${this.oneTimeLoginByAccessTokenDone.toISOString()}, nothing to do`);
                    return false;
                }
                this.oneTimeLoginByAccessTokenDone = new Date();
                try {
                    return yield this._serviceMethods.loginByAccessToken(accessToken, this.options.rememberMe);
                }
                catch (err) {
                    this._log.error("Unable to login", err);
                    const errorLoginProfile = { status: LoginProfileStatus.RETRY, logged: false, username: this.username };
                    const error = exceptionInitializer(err);
                    if (error instanceof PasswordExpired) {
                        errorLoginProfile.status = LoginProfileStatus.PASSWORD_EXPIRED;
                        errorLoginProfile.username = error.username || errorLoginProfile.username;
                    }
                    this._log.error("Notify new status", errorLoginProfile);
                    this._loginProfileSubject.next(errorLoginProfile);
                    throw err;
                }
            });
        }
    }
    WebapiClient.version = LIB_VERSION$1;
    class WebapiClientLogger extends Logger {
        constructor(
        client) {
            super();
            this.client = client;
            const enableValue = this.config.prefix ? this.config.prefix + "*" : "*";
            let enabled = WebapiClientLogger.disableNamespace();
            if (enabled) {
                if (enabled !== "*" && this.config.prefix && enabled.indexOf(this.config.prefix) < 0) {
                    enabled += "," + enableValue;
                }
            }
            else {
                enabled = enableValue;
            }
            WebapiClientLogger.enableNamespace(enabled);
        }
        get config() {
            return this.client.options.logConfig;
        }
        get enabled() {
            return this.config.enabled;
        }
        set enabled(enabled) {
            this.config.enabled = enabled;
        }
        get objectToJson() {
            return this.config.objectToJson;
        }
        set objectToJson(objectToJson) {
            this.config.objectToJson = !!objectToJson;
        }
        set instanceIdLogged(instanceIdLogged) {
            this.config.instanceIdLogged = !!instanceIdLogged;
        }
        get instanceIdLogged() {
            return this.config.instanceIdLogged;
        }
        set logLevel(logLevel) {
            if (logLevel && logLevel >= LogLevel.Verbose && logLevel <= LogLevel.None) {
                this.config.logLevel = logLevel;
            }
        }
        get logLevel() {
            return this.enabled ? this.config.logLevel : LogLevel.None;
        }
        get prefix() {
            return this.config.prefix;
        }
        set prefix(prefix) {
            this.config.prefix = prefix;
        }
        get timestamp() {
            return this.config.timestamp;
        }
        set timestamp(timestamp) {
            this.config.timestamp = !!timestamp;
        }
        get storeLog() {
            var _a;
            return (_a = this.config.storage) === null || _a === void 0 ? void 0 : _a.store;
        }
        dumpStoredLog() {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                const dumpedLogRequest = (_b = (_a = this.config.storage) === null || _a === void 0 ? void 0 : _a.dump) === null || _b === void 0 ? void 0 : _b.call(_a);
                if (dumpedLogRequest) {
                    const dumpLogResponse = yield dumpedLogRequest;
                    if (dumpLogResponse) {
                        return dumpLogResponse;
                    }
                }
                return [];
            });
        }
        dumpStoredLogToIterable() {
            return __awaiter(this, void 0, void 0, function* () {
                return LogUtils.logEntryIterableToStringIterable(yield this.dumpStoredLog());
            });
        }
        dumpStoredLogToObservable() {
            return from(this.dumpStoredLog()).pipe(switchMap(from), LogUtils.logEntryToStringObservableOperator());
        }
        static enableNamespace(namespace) {
            browserExports.enable(namespace);
        }
        static disableNamespace() {
            return browserExports.disable();
        }
    }
    console.info(`WebAPIclient loaded version ${LIB_VERSION$1} - Browser ${JSON.stringify(browser)}`);

    class AbstractFileUploader {
        constructor(client, file, options) {
            this.file = file;
            this.fileUuid = (() => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)))();
            this.uploadDone = false;
            this.log = Log$1.of("uploader", client);
            this.options = options !== null && options !== void 0 ? options : {};
        }
        set options(options) {
            this._options = Object.assign({
                chunking: {
                    partSize: 2000000,
                },
                callbacks: {},
            }, (options !== null && options !== void 0 ? options : {}));
        }
        get options() {
            return this._options;
        }
        delete() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.uploadDone) {
                    const formData = new FormData();
                    formData.append("qqfilename", this.file.name);
                    formData.append("qquuid", this.fileUuid);
                    try {
                        yield this.doDeleteRequest(formData);
                    }
                    catch (error) {
                        this.log.error(`error on delete upload file - ${this.fileUuid} - ${this.file.name}`, error);
                        throw error;
                    }
                    this.uploadDone = false;
                    this.log.info(`upload file deleted - ${this.fileUuid} - ${this.file.name}`);
                }
                else {
                    this.log.warn(`unable to delete, file is not uploaded - ${this.fileUuid}`, { name: this.file.name });
                }
            });
        }
        upload() {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                this.log.debug(`start upload file - ${this.fileUuid}`, { name: this.file.name, size: this.file.size });
                const chunkSize = (_a = this.options.chunking) === null || _a === void 0 ? void 0 : _a.partSize;
                const totalParts = Math.ceil(this.file.size / chunkSize);
                let partIndex = 0;
                try {
                    for (let startByte = 0; startByte < (this.file.size ||  1); startByte += chunkSize) {
                        yield this.uploadChunk({
                            partIndex: ++partIndex,
                            totalParts,
                            startByte,
                            endByte: Math.min(this.file.size, startByte + chunkSize),
                        });
                    }
                    this.uploadDone = true;
                    this.log.info(`end upload file - ${this.fileUuid}`);
                }
                catch (e) {
                    this.log.error(`error on upload file - ${this.fileUuid}`, e);
                }
            });
        }
        uploadChunk(chunkData) {
            var _a, _b, _c, _d, _e;
            return __awaiter(this, void 0, void 0, function* () {
                const { partIndex, totalParts, startByte, endByte } = chunkData;
                const chunk = this.file.slice(startByte, endByte);
                const qqfile = `${partIndex}_${this.file.name}`;
                const chunkedRequest = totalParts > 1;
                const formData = new FormData();
                formData.append("qqfile", chunk, qqfile);
                formData.append("qqfilename", this.file.name);
                if (chunkedRequest) {
                    formData.append("qqpartindex", (partIndex - 1).toString());
                    formData.append("qqtotalparts", totalParts.toString());
                }
                formData.append("qqtotalfilesize", this.file.size.toString());
                formData.append("qquuid", this.fileUuid);
                if (chunkedRequest) {
                    yield ((_b = (_a = this.options.callbacks) === null || _a === void 0 ? void 0 : _a.onUploadChunk) === null || _b === void 0 ? void 0 : _b.call(_a, chunkData));
                    this.log.debug(`start upload chunk ${partIndex} - ${chunk.size} bytes - ${this.fileUuid}`);
                }
                const request = yield this.doUploadRequest(formData, ((_c = this.options.callbacks) === null || _c === void 0 ? void 0 : _c.onProgress)
                    ? (event) => {
                        if (event.lengthComputable) {
                            this.options.callbacks.onProgress(startByte + (event.loaded - (event.total - chunk.size)), this.file.size);
                        }
                    }
                    : noop$1);
                if (chunkedRequest) {
                    this.log.debug(`end upload chunk ${partIndex} - ${this.fileUuid}`);
                    (_e = (_d = this.options.callbacks) === null || _d === void 0 ? void 0 : _d.onUploadChunkSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, chunkData, request);
                }
            });
        }
    }

    class WebapiFileUploader extends AbstractFileUploader {
        constructor(client, file, options) {
            super(client, file, options);
            this.client = client;
        }
        doRequestWithXMLHttpRequest(method, formData, onProgress) {
            return new Promise((resolve, reject) => {
                if (!this.client.accessToken || !this.client.sessionId) {
                    reject(new Error("client not logged"));
                }
                const url = this.client.generateUrl(ServiceScope.upload, { ignoreDeviceId: true, ignoreSessionId: true, ignoreAccessToken: false });
                const xhr = new XMLHttpRequest();
                if ("withCredentials" in xhr) {
                    xhr.open(method, url, true);
                    xhr.withCredentials = true;
                }
                else {
                    reject(new Error("XMLHttpRequest CORS not enabled"));
                    return;
                }
                xhr.setRequestHeader("X-FINEUPLOADER-SESSION", this.client.sessionId);
                xhr.setRequestHeader("Authorization", `Bearer ${this.client.accessToken}`);
                xhr.upload.onprogress = onProgress;
                xhr.onload = () => {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(xhr);
                    }
                    else {
                        reject(new Error(`error on request: ${xhr.statusText}`));
                    }
                };
                xhr.onerror = () => {
                    reject(new Error("network error"));
                };
                xhr.send(formData);
            });
        }
        doUploadRequest(formData, onProgress) {
            return this.doRequestWithXMLHttpRequest("POST", formData, onProgress);
        }
        doDeleteRequest(formData) {
            return this.doRequestWithXMLHttpRequest("DELETE", formData, noop$1);
        }
    }

    function isString(value) {
        return typeof value === "string" || value instanceof String;
    }
    function toPromise(source) {
        return lastValueFrom(source, { defaultValue: undefined });
    }
    function emptyStringValue(value) {
        return value == null || value == "" ? undefined : value;
    }
    function isObject(value) {
        return value && typeof value === "object" && !Array.isArray(value);
    }
    function findIndexOfAtLeaseOneKey(itemKeys, source, item) {
        const itemToFind = item !== null && item !== void 0 ? item : {};
        return (source || []).findIndex((sourceItem) => itemKeys.find((key) => sourceItem.hasOwnProperty(key) && sourceItem[key] === itemToFind[key]));
    }
    function mergeArrays(attributesName, oldValue, newValue) {
        if (oldValue.length > 0 && typeof oldValue[0] === "object" && !Array.isArray(oldValue[0])) {
            const mergedArray = [...oldValue];
            newValue.forEach((newItem) => {
                const existingIndex = findIndexOfAtLeaseOneKey(["id", "code"], mergedArray, newItem);
                if (existingIndex > -1) {
                    mergedArray[existingIndex] = mergeGenericObject([...attributesName, `${existingIndex}`], mergedArray[existingIndex], newItem);
                }
                else {
                    mergedArray.push(newItem);
                }
            });
            return mergedArray;
        }
        return Array.from(new Set([...oldValue, ...newValue]));
    }
    function mergeGenericObject(attributeName = [], target, updates) {
        if (updates) {
            Object.keys(updates).forEach((key) => {
                const oldValue = target[key];
                const newValue = updates[key];
                const attributes = [...attributeName, key];
                if (Array.isArray(oldValue) && Array.isArray(newValue)) {
                    target[key] = mergeArrays(attributes, oldValue, newValue);
                }
                else if (isObject(oldValue) && isObject(newValue)) {
                    target[key] = mergeGenericObject(attributes, Object.assign({}, oldValue), newValue);
                }
                else {
                    target[key] = newValue;
                }
            });
        }
        return target;
    }
    function mergeObject(target, updates) {
        return mergeGenericObject([], target, updates);
    }
    function delayedChannelEventHandler(handler, delay) {
        let emissionTimer;
        let callInfo;
        let isEmitted = false;
        return (channelEvent, emitEvent) => __awaiter(this, void 0, void 0, function* () {
            if (isEmitted) {
                return handler(channelEvent, emitEvent);
            }
            else if (!emissionTimer) {
                emissionTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                    isEmitted = true;
                    try {
                        yield handler(callInfo ? new ChannelEvent(channelEvent.channel, callInfo, channelEvent.generatedBy) : channelEvent, emitEvent);
                    }
                    catch (e) { }
                    emissionTimer = undefined;
                    callInfo = undefined;
                }), delay);
                callInfo = channelEvent.callInfo;
            }
            else if (callInfo && callInfo !== channelEvent.callInfo && callInfo.state === channelEvent.callInfo.state) {
                callInfo = Object.assign(Object.assign({}, callInfo), channelEvent.callInfo);
            }
        });
    }
    class IndexedDBService {
        constructor(
        dbName,
        storeName,
        index) {
            this.dbName = dbName;
            this.storeName = storeName;
            this.index = index;
            this.db = null;
        }
        openDB() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.db) {
                    return this.db;
                }
                return new Promise((resolve, reject) => {
                    const request = indexedDB.open(this.dbName, 1);
                    request.onupgradeneeded = (event) => {
                        var _a;
                        const db = event.target.result;
                        if (db.objectStoreNames.contains(this.storeName)) {
                            const objectStore = (_a = event.target.transaction) === null || _a === void 0 ? void 0 : _a.objectStore(this.storeName);
                            if (this.index) {
                                if (objectStore && !objectStore.indexNames.contains(this.index)) {
                                    objectStore.createIndex(this.index, this.index, { unique: false });
                                }
                            }
                        }
                        else {
                            const objectStore = db.createObjectStore(this.storeName, { keyPath: "id", autoIncrement: true });
                            if (this.index) {
                                objectStore.createIndex(this.index, this.index, { unique: false });
                            }
                        }
                    };
                    request.onsuccess = (event) => {
                        this.db = event.target.result;
                        resolve(this.db);
                    };
                    request.onerror = (event) => {
                        reject(event.target.error);
                    };
                });
            });
        }
        addData(data) {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readwrite");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.add(data);
                    request.onsuccess = () => {
                        resolve(request.result);
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
        getData(id) {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readonly");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.get(id);
                    request.onsuccess = () => {
                        resolve(request.result);
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
        getAllData() {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readonly");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.getAll();
                    request.onsuccess = () => {
                        resolve(request.result);
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
        updateData(data) {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readwrite");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.put(data);
                    request.onsuccess = () => {
                        resolve();
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
        deleteData(id) {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readwrite");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.delete(id);
                    request.onsuccess = () => {
                        resolve();
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
        deletedData(canDelete) {
            return __awaiter(this, void 0, void 0, function* () {
                const db = yield this.openDB();
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(this.storeName, "readwrite");
                    const store = transaction.objectStore(this.storeName);
                    const request = store.openCursor();
                    request.onsuccess = (event) => {
                        const cursor = event.target.result;
                        if (cursor) {
                            const record = cursor.value;
                            try {
                                if (canDelete(record)) {
                                    store.delete(cursor.primaryKey);
                                }
                            }
                            catch (e) { }
                            cursor.continue();
                        }
                        else {
                            resolve();
                        }
                    };
                    request.onerror = () => {
                        reject(request.error);
                    };
                });
            });
        }
    }

    const logPrefix = "TVoxClientSdk";
    const DEFAULT_LOG_CONFIGURATOR = new DefaultLogger(new LogConfig({ prefix: logPrefix }));
    class Log {
        constructor(pkg, instanceId, config) {
            this.apiLog = Log$1.create(pkg, instanceId, config !== null && config !== void 0 ? config : DEFAULT_LOG_CONFIGURATOR);
        }
        static of(pkg, client) {
            return new Log(pkg, client === null || client === void 0 ? void 0 : client.api.instanceId, client === null || client === void 0 ? void 0 : client.api.logger);
        }
        get config() {
            return this.apiLog.config;
        }
        log() {
            return this.apiLog.log;
        }
        get verbose() {
            return this.apiLog.verbose;
        }
        get debug() {
            return this.apiLog.debug;
        }
        get info() {
            return this.apiLog.info;
        }
        get warn() {
            return this.apiLog.warn;
        }
        get error() {
            return this.apiLog.error;
        }
        get fatal() {
            return this.apiLog.fatal;
        }
    }
    class IndexedDBLogStore {
        constructor(config) {
            this.config = config;
            this.dbStore = new IndexedDBService("TVoxSDKLog", "log", "time");
            setInterval(() => {
                try {
                    this.deleteOlLogs();
                }
                catch (e) { }
            }, config.clearLogIntervalMillis);
        }
        deleteOlLogs() {
            return __awaiter(this, void 0, void 0, function* () {
                const oneHourAgo = new Date().getTime() - this.config.logRetentionMillis;
                this.dbStore.deletedData((logEntry) => logEntry.time.getTime() < oneHourAgo);
            });
        }
        store(logEntry) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.config.enabled) {
                    yield this.dbStore.addData(logEntry);
                }
            });
        }
        dump() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.dbStore.getAllData();
            });
        }
    }
    (function (Log) {
        (function (LogLevel) {
            LogLevel[LogLevel["Verbose"] = 1] = "Verbose";
            LogLevel[LogLevel["Debug"] = 2] = "Debug";
            LogLevel[LogLevel["Info"] = 3] = "Info";
            LogLevel[LogLevel["Warn"] = 4] = "Warn";
            LogLevel[LogLevel["Error"] = 5] = "Error";
            LogLevel[LogLevel["Fatal"] = 6] = "Fatal";
            LogLevel[LogLevel["None"] = 7] = "None";
        })(Log.LogLevel || (Log.LogLevel = {}));
        function toWebapiConfig(configuration) {
            return configuration
                ? new LogConfig({
                    enabled: configuration.enabled,
                    prefix: logPrefix,
                    timestamp: configuration.timestamp,
                    objectToJson: configuration.objectToJson,
                    logLevel: configuration.logLevel,
                    storage: configuration.storage,
                })
                : new LogConfig({ prefix: logPrefix });
        }
        Log.toWebapiConfig = toWebapiConfig;
        class Logger {
            constructor() { }
        }
        Log.Logger = Logger;
    })(Log || (Log = {}));

    var eventemitter3Exports = {};
    var eventemitter3 = {
      get exports(){ return eventemitter3Exports; },
      set exports(v){ eventemitter3Exports = v; },
    };

    (function (module) {
    	var has = Object.prototype.hasOwnProperty
    	  , prefix = '~';
    	function Events() {}
    	if (Object.create) {
    	  Events.prototype = Object.create(null);
    	  if (!new Events().__proto__) prefix = false;
    	}
    	function EE(fn, context, once) {
    	  this.fn = fn;
    	  this.context = context;
    	  this.once = once || false;
    	}
    	function addListener(emitter, event, fn, context, once) {
    	  if (typeof fn !== 'function') {
    	    throw new TypeError('The listener must be a function');
    	  }
    	  var listener = new EE(fn, context || emitter, once)
    	    , evt = prefix ? prefix + event : event;
    	  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
    	  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
    	  else emitter._events[evt] = [emitter._events[evt], listener];
    	  return emitter;
    	}
    	function clearEvent(emitter, evt) {
    	  if (--emitter._eventsCount === 0) emitter._events = new Events();
    	  else delete emitter._events[evt];
    	}
    	function EventEmitter() {
    	  this._events = new Events();
    	  this._eventsCount = 0;
    	}
    	EventEmitter.prototype.eventNames = function eventNames() {
    	  var names = []
    	    , events
    	    , name;
    	  if (this._eventsCount === 0) return names;
    	  for (name in (events = this._events)) {
    	    if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
    	  }
    	  if (Object.getOwnPropertySymbols) {
    	    return names.concat(Object.getOwnPropertySymbols(events));
    	  }
    	  return names;
    	};
    	EventEmitter.prototype.listeners = function listeners(event) {
    	  var evt = prefix ? prefix + event : event
    	    , handlers = this._events[evt];
    	  if (!handlers) return [];
    	  if (handlers.fn) return [handlers.fn];
    	  for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
    	    ee[i] = handlers[i].fn;
    	  }
    	  return ee;
    	};
    	EventEmitter.prototype.listenerCount = function listenerCount(event) {
    	  var evt = prefix ? prefix + event : event
    	    , listeners = this._events[evt];
    	  if (!listeners) return 0;
    	  if (listeners.fn) return 1;
    	  return listeners.length;
    	};
    	EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
    	  var evt = prefix ? prefix + event : event;
    	  if (!this._events[evt]) return false;
    	  var listeners = this._events[evt]
    	    , len = arguments.length
    	    , args
    	    , i;
    	  if (listeners.fn) {
    	    if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
    	    switch (len) {
    	      case 1: return listeners.fn.call(listeners.context), true;
    	      case 2: return listeners.fn.call(listeners.context, a1), true;
    	      case 3: return listeners.fn.call(listeners.context, a1, a2), true;
    	      case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
    	      case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
    	      case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
    	    }
    	    for (i = 1, args = new Array(len -1); i < len; i++) {
    	      args[i - 1] = arguments[i];
    	    }
    	    listeners.fn.apply(listeners.context, args);
    	  } else {
    	    var length = listeners.length
    	      , j;
    	    for (i = 0; i < length; i++) {
    	      if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
    	      switch (len) {
    	        case 1: listeners[i].fn.call(listeners[i].context); break;
    	        case 2: listeners[i].fn.call(listeners[i].context, a1); break;
    	        case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
    	        case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
    	        default:
    	          if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
    	            args[j - 1] = arguments[j];
    	          }
    	          listeners[i].fn.apply(listeners[i].context, args);
    	      }
    	    }
    	  }
    	  return true;
    	};
    	EventEmitter.prototype.on = function on(event, fn, context) {
    	  return addListener(this, event, fn, context, false);
    	};
    	EventEmitter.prototype.once = function once(event, fn, context) {
    	  return addListener(this, event, fn, context, true);
    	};
    	EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
    	  var evt = prefix ? prefix + event : event;
    	  if (!this._events[evt]) return this;
    	  if (!fn) {
    	    clearEvent(this, evt);
    	    return this;
    	  }
    	  var listeners = this._events[evt];
    	  if (listeners.fn) {
    	    if (
    	      listeners.fn === fn &&
    	      (!once || listeners.once) &&
    	      (!context || listeners.context === context)
    	    ) {
    	      clearEvent(this, evt);
    	    }
    	  } else {
    	    for (var i = 0, events = [], length = listeners.length; i < length; i++) {
    	      if (
    	        listeners[i].fn !== fn ||
    	        (once && !listeners[i].once) ||
    	        (context && listeners[i].context !== context)
    	      ) {
    	        events.push(listeners[i]);
    	      }
    	    }
    	    if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
    	    else clearEvent(this, evt);
    	  }
    	  return this;
    	};
    	EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
    	  var evt;
    	  if (event) {
    	    evt = prefix ? prefix + event : event;
    	    if (this._events[evt]) clearEvent(this, evt);
    	  } else {
    	    this._events = new Events();
    	    this._eventsCount = 0;
    	  }
    	  return this;
    	};
    	EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
    	EventEmitter.prototype.addListener = EventEmitter.prototype.on;
    	EventEmitter.prefixed = prefix;
    	EventEmitter.EventEmitter = EventEmitter;
    	{
    	  module.exports = EventEmitter;
    	}
    } (eventemitter3));
    var EventEmitter$1 = eventemitter3Exports;

    class EventEmitter extends eventemitter3Exports {
        constructor(
        pkg, client) {
            super();
            this.pkg = pkg;
            this._eventCounter = {};
            if (client) {
                this.init(client);
            }
        }
        init(client) {
            this.log = Log.of(this.pkg, client);
        }
        eventLogId() {
            return null;
        }
        markEvent(event) {
            var _a;
            const eventCounter = (_a = this._eventCounter[event]) !== null && _a !== void 0 ? _a : 0;
            this._eventCounter[event] = eventCounter + 1;
        }
        emitGracefully(event, logAtCounter, ...args) {
            var _a;
            const eventCounter = (_a = this._eventCounter[event]) !== null && _a !== void 0 ? _a : 0;
            if (eventCounter % logAtCounter > 0) {
                return this.emitSilent(event, ...args);
            }
            else {
                return this.emit(event, ...args);
            }
        }
        emitSilent(event, ...args) {
            this.markEvent(event);
            try {
                return super.emit(event, ...args);
            }
            catch (e) {
                return false;
            }
        }
        emit(event, ...args) {
            var _a;
            let logPrefix = "";
            try {
                const logId = (_a = this.eventLogId()) !== null && _a !== void 0 ? _a : logPrefix;
                logPrefix = logId == logPrefix ? logPrefix : `${logId} - `;
            }
            finally {
                try {
                    this.log.debug(`${logPrefix}emit event ${String(event)}`, ...args);
                }
                finally {
                    this.markEvent(event);
                    try {
                        return super.emit(event, ...args);
                    }
                    catch (e) {
                        this.log.error(`${logPrefix}error on handle event "${String(event)}"`, e);
                        return false;
                    }
                }
            }
        }
    }

    exports.C = void 0;
    (function (C) {
        (function (LineType) {
            LineType["SIP"] = "SIP";
            LineType["WEBRTC"] = "WEBRTC";
        })(C.LineType || (C.LineType = {}));
    })(exports.C || (exports.C = {}));

    class SearchResult extends EventEmitter {
    }
    SearchResult.data = "data";
    SearchResult.error = "error";
    SearchResult.complete = "complete";

    exports.CallHistory = void 0;
    (function (CallHistory) {
        CallHistory.PKG = "callhistory";
        class CallHistoryResult extends SearchResult {
            constructor(user, options) {
                super(`${CallHistory.PKG}`, user.client);
                this.options = options;
            }
        }
        CallHistory.CallHistoryResult = CallHistoryResult;
        (function (CallHistoryDevStatus) {
            CallHistoryDevStatus["TRASF"] = "TRASF";
            CallHistoryDevStatus["TRASF_CANCEL"] = "TRASF_CANCEL";
            CallHistoryDevStatus["TRASF_ANSWER"] = "TRASF_ANSWER";
            CallHistoryDevStatus["TRASF_VM"] = "TRASF_VM";
            CallHistoryDevStatus["TRASF_VM_NO"] = "TRASF_VM_NO";
            CallHistoryDevStatus["RETURN"] = "RETURN";
        })(CallHistory.CallHistoryDevStatus || (CallHistory.CallHistoryDevStatus = {}));
        (function (CallHistoryDialStatus) {
            CallHistoryDialStatus["CHANUNAVAIL"] = "CHANUNAVAIL";
            CallHistoryDialStatus["CONGESTION"] = "CONGESTION";
            CallHistoryDialStatus["NOANSWER"] = "NOANSWER";
            CallHistoryDialStatus["BUSY"] = "BUSY";
            CallHistoryDialStatus["ANSWER"] = "ANSWER";
            CallHistoryDialStatus["CANCEL"] = "CANCEL";
            CallHistoryDialStatus["ERROR"] = "ERROR";
            CallHistoryDialStatus["NON_PRESENTE"] = "NON_PRESENTE";
            CallHistoryDialStatus["ALWAYS"] = "ALWAYS";
            CallHistoryDialStatus["ENABLE_FROM_PHONE"] = "ENABLE_FROM_PHONE";
            CallHistoryDialStatus["PICKUPED"] = "PICKUPED";
            CallHistoryDialStatus["PICKUPER"] = "PICKUPER";
            CallHistoryDialStatus["TVOX_NO_PERMISSION"] = "TVOX_NO_PERMISSION";
            CallHistoryDialStatus["DONTCALL"] = "DONTCALL";
            CallHistoryDialStatus["REJECTED"] = "REJECTED";
        })(CallHistory.CallHistoryDialStatus || (CallHistory.CallHistoryDialStatus = {}));
        (function (TransportType) {
            TransportType["PHONE"] = "PHONE";
            TransportType["VOICEMAIL"] = "VOICEMAIL";
            TransportType["FAX"] = "FAX";
            TransportType["SMS"] = "SMS";
        })(CallHistory.TransportType || (CallHistory.TransportType = {}));
        (function (CallHistoryType) {
            CallHistoryType["INBOUND"] = "INBOUND";
            CallHistoryType["OUTBOUND"] = "OUTBOUND";
        })(CallHistory.CallHistoryType || (CallHistory.CallHistoryType = {}));
    })(exports.CallHistory || (exports.CallHistory = {}));

    class Profile extends EventEmitter {
        constructor(client, profile) {
            super(`${Profile.PKG}${profile.type.toLowerCase()}`, client);
            this.currentSkillsetsWithProfilesCache$ = new BehaviorSubject(null);
            this.client = client;
            this._label = profile.label;
            this.id = profile.id;
            this.type = profile.type;
        }
        mergeDetail(detail) {
            var _a;
            this.detail = mergeObject((_a = this.detail) !== null && _a !== void 0 ? _a : {}, detail);
        }
        static of(client, profile) {
            switch (profile.type) {
                case exports.ProfileType.UC:
                case exports.ProfileType.TQM:
                    return new Profile(client, profile);
                default:
                    return new ProfileAgent(client, profile);
            }
        }
        get label() {
            var _a, _b;
            return (_b = (_a = this.detail) === null || _a === void 0 ? void 0 : _a.label) !== null && _b !== void 0 ? _b : this._label;
        }
        getServiceByCode(code) {
            var _a, _b;
            return (_b = (_a = this.detail) === null || _a === void 0 ? void 0 : _a.services) === null || _b === void 0 ? void 0 : _b.find((service) => service.code === code);
        }
        get isInUse() {
            return !!this.useProfileSubscription;
        }
        get callRecording() {
            var _a;
            switch ((_a = this.detail) === null || _a === void 0 ? void 0 : _a.recConf) {
                case RegistrationConfiguration.ENABLED:
                    return Profile.CallRecording.ON_DEMAND;
                case RegistrationConfiguration.CUSTOMIZABLE:
                    return Profile.CallRecording.ON_DEMAND_WITH_NOTE;
                case RegistrationConfiguration.AUTO:
                    return Profile.CallRecording.AUTOMATIC;
                case RegistrationConfiguration.AUTO_CUSTOMIZABLE:
                    return Profile.CallRecording.AUTOMATIC_WITH_NOTE;
                case RegistrationConfiguration.ENABLED_ON_PHONE:
                    return Profile.CallRecording.ENABLED_ON_PHONE;
                case RegistrationConfiguration.DISABLED:
                default:
                    return Profile.CallRecording.DISABLED;
            }
        }
        checkProfileIsInUse() {
            if (!this.isInUse) {
                throw new Error("profile must before used with useProfile()");
            }
        }
        useProfile() {
            return this.client.user.useProfile(this);
        }
        useProfileDone(useProfileSubscription) {
            useProfileSubscription.add(() => {
                this.useProfileSubscription = undefined;
            });
            this.useProfileSubscription = useProfileSubscription;
        }
        userDetailUpdate(userDetail) { }
    }
    class ProfileAgent extends Profile {
        constructor(client, profile) {
            super(client, profile);
            this.serviceCallQueueSubscription = Subscription.EMPTY;
            this.totalCallOnQueue = 0;
            this.serviceCallOnQueue = new Map();
            this._status = UserStatus.NR;
        }
        get status() {
            return this._status;
        }
        calculateTotalCallOnQueue(serviceStatus, emitEvent) {
            const previousCallOnQueue = this.serviceCallOnQueue.get(serviceStatus.service);
            this.serviceCallOnQueue.set(serviceStatus.service, serviceStatus.callQueue);
            if (previousCallOnQueue) {
                this.totalCallOnQueue -= previousCallOnQueue;
            }
            this.totalCallOnQueue += serviceStatus.callQueue;
            if (emitEvent) {
                this.emit("call_on_queue", this.totalCallOnQueue);
            }
        }
        startNotifyServiceCallQueue() {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                this.checkProfileIsInUse();
                function callChannelOnly(serviceStatus) {
                    return ChannelType.PhoneCall === channelIdToChannelType(serviceStatus.channelId);
                }
                this.serviceCallQueueSubscription.unsubscribe();
                const getServicesCallQueue = this.client.api.methods.getServicesCallQueue();
                const result = getServicesCallQueue.resultSync.pipe(concatMap(identity$1), tap(() => {
                    this.serviceCallOnQueue.clear();
                    this.totalCallOnQueue = 0;
                }), share());
                const serviceCallQueueSubscription = result
                    .pipe(catchError((err) => {
                    return EMPTY;
                }))
                    .pipe(map((res) => res.data), filter(callChannelOnly), finalize(() => {
                    this.emit("call_on_queue", this.totalCallOnQueue);
                }))
                    .subscribe((serviceStatus) => {
                    this.emit("service_call_on_queue", serviceStatus.service, serviceStatus.callQueue);
                    this.calculateTotalCallOnQueue(serviceStatus);
                });
                serviceCallQueueSubscription.add(getServicesCallQueue.notification.pipe(filter(callChannelOnly)).subscribe((serviceStatus) => {
                    this.emit("service_call_on_queue", serviceStatus.service, serviceStatus.callQueue);
                    this.calculateTotalCallOnQueue(serviceStatus, true);
                }));
                yield toPromise(result.pipe(first()));
                (_a = this.useProfileSubscription) === null || _a === void 0 ? void 0 : _a.add(serviceCallQueueSubscription);
                serviceCallQueueSubscription.add(() => {
                    var _a;
                    (_a = this.useProfileSubscription) === null || _a === void 0 ? void 0 : _a.remove.bind(serviceCallQueueSubscription);
                    this.serviceCallOnQueue.clear();
                    this.totalCallOnQueue = 0;
                });
                this.serviceCallQueueSubscription = serviceCallQueueSubscription;
            });
        }
        stopNotifyServiceCallQueue() {
            return __awaiter(this, void 0, void 0, function* () {
                this.checkProfileIsInUse();
                this.serviceCallQueueSubscription.unsubscribe();
            });
        }
        setReady() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.client.api.methods.setUserStatusReady(channelTypeToId(ChannelType.PhoneCall));
            });
        }
        setNotReady() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.client.api.methods.setUserStatusNotReady(channelTypeToId(ChannelType.PhoneCall));
            });
        }
        getAllActivityCode() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.client.api.methods.getAllActivityCode();
            });
        }
        setActivityCode(action) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.client.api.methods.setActivityCode(action);
            });
        }
        getCurrentSkillsetsWithProfiles() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.currentSkillsetsWithProfilesCache$.value) {
                    const getCurrentSkillsetsWithProfilesRequest = this.client.api.methods.getCurrentSkillsetsWithProfiles();
                    const getCurrentSkillsetsWithProfilesResult$ = getCurrentSkillsetsWithProfilesRequest.notification.pipe(share(), catchError((err) => {
                        this.log.error("Error fetching skillsets with profiles:", err);
                        return EMPTY;
                    }), tap((data) => this.currentSkillsetsWithProfilesCache$.next(data)));
                    yield toPromise(getCurrentSkillsetsWithProfilesResult$.pipe(first()));
                }
                return toPromise(this.currentSkillsetsWithProfilesCache$.pipe(first()));
            });
        }
        userDetailUpdate(userDetail) {
            super.userDetailUpdate(userDetail);
            if (userDetail.statuses) {
                const userStatus = userDetail.statuses[channelTypeToId(ChannelType.PhoneCall)];
                if (userStatus) {
                    this._status = userStatus;
                    this.emit("status_changed", userStatus);
                }
            }
        }
    }
    ProfileAgent.call_on_queue = "call_on_queue";
    ProfileAgent.service_call_on_queue = "service_call_on_queue";
    exports.ProfileType = void 0;
    (function (ProfileType) {
        ProfileType["UC"] = "UC";
        ProfileType["AG"] = "AG";
        ProfileType["AG_EXTERNAL"] = "AG_EXTERNAL";
        ProfileType["AG_REMOTE"] = "AG_REMOTE";
        ProfileType["TQM"] = "TQM";
    })(exports.ProfileType || (exports.ProfileType = {}));
    (function (Profile) {
        Profile.PKG = "profile";
        (function (CallRecording) {
            CallRecording["DISABLED"] = "DISABLED";
            CallRecording["ON_DEMAND"] = "ON_DEMAND";
            CallRecording["ON_DEMAND_WITH_NOTE"] = "ON_DEMAND_WITH_NOTE";
            CallRecording["AUTOMATIC"] = "AUTOMATIC";
            CallRecording["AUTOMATIC_WITH_NOTE"] = "AUTOMATIC_WITH_NOTE";
            CallRecording["ENABLED_ON_PHONE"] = "ENABLED_ON_PHONE";
        })(Profile.CallRecording || (Profile.CallRecording = {}));
    })(Profile || (Profile = {}));

    class User extends EventEmitter {
        constructor(
        _client) {
            super(User.PKG, _client);
            this._client = _client;
            this._state = User.State.NOTLOGGED;
            this.info = {};
            this._loadUserProfileInProgress = false;
            this.getUserDetailSubscription = Subscription.EMPTY;
            this.availableProfile = [];
            this.useProfileChain = Promise.resolve();
            this.useProfileSubscription = Subscription.EMPTY;
            this._statusMonitor = new UserStatusMonitor(this, null, this.requestUserStatus.bind(this));
            this.handleEvents();
        }
        get state() {
            return this._state;
        }
        set state(status) {
            this._state = status;
        }
        get statusMonitor() {
            return this._statusMonitor;
        }
        get client() {
            return this._client;
        }
        requestUserStatus() {
            return __awaiter(this, void 0, void 0, function* () {
                yield this.client.canDoRequest();
                if (this.info.userId) {
                    return this.client.api.methods.getUserContactStatus(this.info.userId);
                }
                else {
                    throw "username to request contact status is unavailable";
                }
            });
        }
        handleEvents() {
            this.client.on("ready", () => (this._loadUserProfileInProgress = false));
            this.client.api.loginProfile.subscribe((data) => __awaiter(this, void 0, void 0, function* () {
                const prevstate = this.state;
                this.state = data.logged ? User.State.LOGGED : User.State.NOTLOGGED;
                this.info.userId = data.username;
                this.info.username = data.publicUsername;
                this.info.name = data.name;
                this.info.surname = data.surname;
                switch (data.status) {
                    case LoginProfileStatus.SOCKET_CLOSED_BY_USER:
                    case LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED:
                    case LoginProfileStatus.SOCKET_CLOSED_USER_NOT_ENABLED_MCS:
                        if (prevstate === User.State.LOGGED) {
                            this.client.emit("logged_out", this);
                        }
                        break;
                    default:
                        switch (this.client.state) {
                            case Client.ClientState.LOGIN_REQUIRED:
                                if (data.logged && prevstate !== this.state) {
                                    this.client.emit("logged_in", this, this.client.loginData);
                                    this.initializeApiAfterLogin();
                                }
                                break;
                            case Client.ClientState.LOGIN_IN_PROGRESS:
                                if (data.logged) {
                                    if (prevstate !== this.state) {
                                        this.client.emit("logged_in", this, this.client.loginData);
                                        this.initializeApiAfterLogin();
                                    }
                                }
                                else if (data.status === LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE) {
                                    setTimeout(() => {
                                        this.client.api.serviceMethods.loginForce();
                                    });
                                }
                                break;
                            case Client.ClientState.READY:
                                if (this.state === User.State.NOTLOGGED) {
                                    this.client.emit("logged_out", this);
                                }
                                break;
                        }
                        break;
                }
            }));
            this.client.on("logged_out", () => {
                this.statusMonitor.stop();
            });
        }
        initializeApiAfterLogin() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._loadUserProfileInProgress) {
                    this._loadUserProfileInProgress = true;
                    let userDetailChain = Promise.resolve();
                    this.getUserDetailSubscription.unsubscribe();
                    const request = this.client.api.methods.getUserDetail();
                    this.getUserDetailSubscription = request.resultSync
                        .pipe(concatMap(identity$1), catchError((err) => EMPTY), concatMap((userDetail) => {
                        userDetailChain = userDetailChain
                            .then(() => __awaiter(this, void 0, void 0, function* () {
                            yield this.loadUserDetail(userDetail);
                            yield this.client.api.serviceMethods.startCallNotify();
                            this.client.state = Client.ClientState.READY;
                            this.client.emit("ready");
                        }))
                            .catch(() => { });
                        return userDetailChain;
                    }))
                        .subscribe();
                    this.getUserDetailSubscription.add(request.notification
                        .pipe(concatMap((userDetail) => {
                        userDetailChain = userDetailChain
                            .then(() => __awaiter(this, void 0, void 0, function* () {
                            yield this.client.phone.initFromApiDataUpdate(userDetail);
                            yield this.loadUserDetailUpdate(userDetail);
                        }))
                            .catch(() => { });
                        return userDetailChain;
                    }))
                        .subscribe());
                }
            });
        }
        loadDefaultConfiguration(loggedProfileId) {
            var _a, _b, _c;
            if (!loggedProfileId && this.info.profile) {
                loggedProfileId = this.info.profile.id;
            }
            if (loggedProfileId) {
                this.defaultProfile = this.availableProfile.find((p) => p.id === loggedProfileId);
            }
            if (!this.defaultProfile) {
                this.defaultProfile = ((_a = this.availableProfile) === null || _a === void 0 ? void 0 : _a.length) === 1 ? this.availableProfile[0] : (_c = (_b = this.availableProfile.find((p) => p.type === exports.ProfileType.UC)) !== null && _b !== void 0 ? _b : this.availableProfile.find((p) => p.type === exports.ProfileType.AG)) !== null && _c !== void 0 ? _c : this.availableProfile[0];
            }
        }
        loadUserDetail(userDetail) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (userDetail.profiles) {
                    const availableProfile = userDetail.profiles
                        .filter((p) => p.clientLoginEnable)
                        .map((profile) => Profile.of(this.client, profile))
                        .filter((p) => p != null);
                    this.availableProfile.forEach((p, index, data) => {
                        if (!availableProfile.find((ps) => ps.id === p.id)) {
                            data.splice(index, 1);
                            this.emit("profile_removed", p);
                        }
                    });
                    availableProfile
                        .filter((p) => !this.availableProfile.find((ps) => ps.id === p.id))
                        .forEach((p) => {
                        this.availableProfile.push(p);
                        this.emit("profile_added", p);
                    });
                }
                else {
                    this.availableProfile.length = 0;
                }
                this.loadDefaultConfiguration(userDetail.loggedProfileId);
                yield this.client.phone.initFromApiData(userDetail);
                yield this.useProfile();
                (_a = this.info.profile) === null || _a === void 0 ? void 0 : _a.userDetailUpdate(userDetail);
                return userDetail;
            });
        }
        loadUserDetailUpdate(userDetail) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                let isProfileAdded;
                let isProfileRemoved;
                if (userDetail.profiles && userDetail.profiles.length) {
                    userDetail.profiles.forEach((profile) => {
                        const fromAvailableDevice = this.availableProfile.find((p) => p.id === profile.id);
                        if (fromAvailableDevice) {
                            if (profile.deleted) {
                                this.availableProfile.splice(this.availableProfile.indexOf(fromAvailableDevice), 1);
                                isProfileRemoved = true;
                                this.emit("profile_removed", fromAvailableDevice);
                            }
                        }
                        else {
                            const profileAdded = Profile.of(this.client, profile);
                            this.availableProfile.push(profileAdded);
                            isProfileAdded = true;
                            this.emit("profile_added", profileAdded);
                        }
                    });
                }
                this.loadDefaultConfiguration(userDetail.loggedProfileId);
                if (isProfileAdded || isProfileRemoved) {
                    yield this.useProfile();
                }
                (_a = this.info.profile) === null || _a === void 0 ? void 0 : _a.userDetailUpdate(userDetail);
            });
        }
        useProfile(profile) {
            return __awaiter(this, void 0, void 0, function* () {
                const result = this.useProfileChain
                    .catch((err) => null)
                    .then(() => __awaiter(this, void 0, void 0, function* () {
                    if (profile && this.info.profile && this.info.profile.id !== profile.id) {
                        yield this.useProfileInternal(profile);
                    }
                    else {
                        if (!this.info.profile || (this.info.profile && !this.availableProfile.find((p) => { var _a; return p.id === ((_a = this.info.profile) === null || _a === void 0 ? void 0 : _a.id); }))) {
                            yield this.useProfileInternal(profile);
                        }
                    }
                }));
                this.useProfileChain = result;
                return result;
            });
        }
        useProfileInternal(profile) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.availableProfile.length) {
                    if (profile) {
                        profile = this.availableProfile.find((p) => p.id === (profile === null || profile === void 0 ? void 0 : profile.id));
                    }
                    if (!profile) {
                        profile = this.defaultProfile;
                    }
                    if (profile) {
                        this.useProfileSubscription.unsubscribe();
                        let useProfileRequest;
                        if (this.client.phone.device) {
                            useProfileRequest = this.client.api.methods.useProfile({
                                id: profile.id,
                                type: this.client.phone.device.type === exports.C.LineType.SIP ? ExtenType.SIP : ExtenType.WEBRTC,
                                device: this.client.phone.device.exten,
                                forceChangeProfile: false,
                                forceUseDevice: false,
                            });
                        }
                        else {
                            useProfileRequest = this.client.api.methods.useProfile({
                                id: profile.id,
                                type: null,
                                device: null,
                                forceChangeProfile: false,
                                forceUseDevice: false,
                            });
                        }
                        const useProfileResult = useProfileRequest.resultSync.pipe(concatMap(identity$1), share());
                        this.useProfileSubscription = useProfileResult
                            .pipe(catchError((err) => {
                            this.info.profile = undefined;
                            this._state = User.State.ERROR_NO_PROFILE;
                            return EMPTY;
                        }))
                            .subscribe((profileDetail) => {
                            if (profile) {
                                profile.detail = {};
                                profile.mergeDetail(profileDetail);
                            }
                        });
                        this.useProfileSubscription.add(useProfileRequest.notification.subscribe((profileDetail) => {
                            profile === null || profile === void 0 ? void 0 : profile.mergeDetail(profileDetail);
                        }));
                        yield toPromise(useProfileResult.pipe(first()));
                        profile.useProfileDone(this.useProfileSubscription);
                        this.emit("profile_selected", profile);
                        this._state = User.State.LOGGED;
                    }
                    else {
                        this._state = User.State.ERROR_NO_PROFILE;
                        this.emit("error_no_profile");
                    }
                    this.info.profile = profile;
                }
                else {
                    this._state = User.State.ERROR_NO_PROFILE_AVAILABLE;
                    this.info.profile = undefined;
                    this.emit("error_no_profile_available");
                }
            });
        }
        searchContact(options) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                yield this.client.canDoRequest();
                const addressbooktype = options.type ? (options.type === Contact.Type.INTERNAL ? AddressBookType.INTERNAL : options.type === Contact.Type.EXTERNAL ? AddressBookType.EXTERNAL : options.type === Contact.Type.PERSONAL ? AddressBookType.PERSONAL : null) : null;
                const mode = options.searchMethods === "contains" ? AddressBookSearchMode.LIKE : AddressBookSearchMode.START_WITH;
                const type = AddressBookFieldType.NONE;
                const fields = [
                    { exclusive: false, key: AddressBookFieldKey.TEL, mode, type, value: [options.toSearch] },
                    { exclusive: true, key: AddressBookFieldKey.N, mode, type, value: [options.toSearch] },
                ];
                if (addressbooktype && addressbooktype !== AddressBookType.INTERNAL) {
                    fields.push({ exclusive: true, key: AddressBookFieldKey.ORG, mode, type, value: [options.toSearch] });
                }
                const response = new Contact.SearchContactResult(this, options);
                const request = this.client.api.methods.searchUsersExtended(addressbooktype, fields, false, (_a = options.pageNumber) !== null && _a !== void 0 ? _a : 1, (_b = options.pageSize) !== null && _b !== void 0 ? _b : 20);
                request.result.subscribe({
                    next: (data) => {
                        response.emit("data", Contact.from(this.client, data.data), data.i, data.tot);
                    },
                    error: (err) => {
                        response.emit("error", err);
                    },
                    complete: () => {
                        response.emit("complete");
                        request.stopNotification();
                    },
                });
                return response;
            });
        }
        getContact(id) {
            return __awaiter(this, void 0, void 0, function* () {
                yield this.client.canDoRequest();
                return Contact.from(this.client, yield this.client.api.methods.getAddressBookContactByUuid(id));
            });
        }
        getUserContactStatus(username) {
            return __awaiter(this, void 0, void 0, function* () {
                const getUserContactStatusRequest = this.client.api.methods.getUserContactStatus(username);
                return toPromise(getUserContactStatusRequest.result.pipe(catchError((err) => {
                    this.log.error(`Error fetching users ${username} contact status with error: `, err);
                    return EMPTY;
                }), finalize(() => __awaiter(this, void 0, void 0, function* () {
                    try {
                        yield getUserContactStatusRequest.stopNotification();
                    }
                    catch (err) {
                        this.log.error(`Error stopNotification of users ${username} contact status with error: `, err);
                    }
                }))));
            });
        }
        getCallHistory(options) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                yield this.client.canDoRequest();
                const response = new exports.CallHistory.CallHistoryResult(this, options);
                this.client.api.methods
                    .searchUserCallHistoryItems(null, [
                    { transportType: TransportType.SMS },
                    { transportType: TransportType.FAX },
                    { transportType: TransportType.VOICEMAIL },
                ], null, null, null, null, null, null, null, (_a = options.pageNumber) !== null && _a !== void 0 ? _a : 1,
                (_b = options.pageSize) !== null && _b !== void 0 ? _b : 100)
                    .result.subscribe({
                    next: (element) => {
                        response.emit("data", element.data, element.i, element.tot);
                    },
                    error: (err) => {
                        response.emit("error", err);
                    },
                    complete: () => {
                        response.emit("complete");
                    },
                });
                return response;
            });
        }
    }
    User.error_no_profile = "error_no_profile";
    User.error_no_profile_available = "error_no_profile_available";
    User.profile_selected = "profile_selected";
    User.profile_removed = "profile_removed";
    User.profile_added = "profile_added";
    (function (User) {
        User.PKG = "user";
        (function (State) {
            State["LOGGED"] = "LOGGED";
            State["NOTLOGGED"] = "NOTLOGGED";
            State["ERROR_NO_PROFILE_AVAILABLE"] = "ERROR_NO_PROFILE_AVAILABLE";
            State["ERROR_NO_PROFILE"] = "ERROR_NO_PROFILE";
        })(User.State || (User.State = {}));
    })(User || (User = {}));
    class UserStatusMonitor extends EventEmitter {
        constructor(user,
        monitoredUserId,
        doRequest) {
            super(`${User.PKG}:status`, user.client);
            this.monitoredUserId = monitoredUserId;
            this.doRequest = doRequest;
            this.requestSubscription = Subscription.EMPTY;
            this._lastValue = new UserStatusMonitor.Value(null);
            this._started = false;
        }
        eventLogId() {
            return this.monitoredUserId;
        }
        start() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._started) {
                    this._started = true;
                    try {
                        const request = yield this.doRequest();
                        this.requestSubscription = merge(request.resultSync.pipe(concatMap(identity$1), catchError((err) => EMPTY)), request.notification)
                            .pipe(map((contactStatus) => new UserStatusMonitor.Value(contactStatus)))
                            .subscribe((userStatusValue) => {
                            if (userStatusValue.phoneChannelStatus && (!this._lastValue.phoneChannelStatus || !this._lastValue.phoneChannelStatus.equals(userStatusValue.phoneChannelStatus))) {
                                this._lastValue.phoneChannelStatus = userStatusValue.phoneChannelStatus;
                                this.emit("phone_status_changed", userStatusValue.phoneChannelStatus);
                            }
                            if (userStatusValue.presenceStatus && (!this._lastValue.presenceStatus || !this._lastValue.presenceStatus.equals(userStatusValue.presenceStatus))) {
                                this._lastValue.presenceStatus = userStatusValue.presenceStatus;
                                this.emit("presence_status_changed", userStatusValue.presenceStatus);
                            }
                        });
                    }
                    catch (e) {
                        this._started = false;
                        throw e;
                    }
                }
            });
        }
        stop() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this._started) {
                    try {
                        this.requestSubscription.unsubscribe();
                        this.requestSubscription = Subscription.EMPTY;
                    }
                    finally {
                        this._lastValue = new UserStatusMonitor.Value(null);
                        this._started = false;
                    }
                }
            });
        }
        get phoneChannelStatus() {
            return this._lastValue.phoneChannelStatus;
        }
        get presenceStatus() {
            return this._lastValue.presenceStatus;
        }
    }
    UserStatusMonitor.phone_status_changed = "phone_status_changed";
    UserStatusMonitor.presence_status_changed = "presence_status_changed";
    (function (UserStatusMonitor) {
        let PhoneStatusValue;
        (function (PhoneStatusValue) {
            PhoneStatusValue["BOOKED"] = "BOOKED";
            PhoneStatusValue["BUSY"] = "BUSY";
            PhoneStatusValue["NOTLOGGED"] = "NOTLOGGED";
            PhoneStatusValue["NR"] = "NR";
            PhoneStatusValue["NR_BUSY"] = "NR_BUSY";
            PhoneStatusValue["READY"] = "READY";
            PhoneStatusValue["WNR"] = "WNR";
        })(PhoneStatusValue = UserStatusMonitor.PhoneStatusValue || (UserStatusMonitor.PhoneStatusValue = {}));
        let PresenceStatusValue;
        (function (PresenceStatusValue) {
            PresenceStatusValue["CHAT"] = "CHAT";
            PresenceStatusValue["AVAILABLE"] = "AVAILABLE";
            PresenceStatusValue["AWAY"] = "AWAY";
            PresenceStatusValue["XA"] = "XA";
            PresenceStatusValue["DND"] = "DND";
            PresenceStatusValue["UNAVAILABLE"] = "UNAVAILABLE";
        })(PresenceStatusValue = UserStatusMonitor.PresenceStatusValue || (UserStatusMonitor.PresenceStatusValue = {}));
        class PhoneChannelStatus {
            constructor(status,
            started,
            dnCallIn,
            dnCallOut,
            activityCode,
            activityCodeLevel2) {
                this.status = status;
                this.started = started;
                this.dnCallIn = dnCallIn;
                this.dnCallOut = dnCallOut;
                this.activityCode = activityCode;
                this.activityCodeLevel2 = activityCodeLevel2;
            }
            get timeInStateMillis() {
                return new Date().getTime() - this.started.getTime();
            }
            equals(status) {
                return (this.status === status.status &&
                    this.started === status.started &&
                    this.dnCallIn === status.dnCallIn &&
                    this.dnCallOut === status.dnCallOut &&
                    this.activityCode === status.activityCode &&
                    this.activityCodeLevel2 === status.activityCodeLevel2);
            }
        }
        UserStatusMonitor.PhoneChannelStatus = PhoneChannelStatus;
        class PresenceStatus {
            constructor(status, message, until) {
                this.status = status;
                this.message = message;
                this.until = until;
            }
            equals(status) {
                return (this.status === status.status &&
                    this.message === status.message &&
                    this.until === status.until);
            }
        }
        UserStatusMonitor.PresenceStatus = PresenceStatus;
        class Value {
            constructor(userContact) {
                if (!userContact) {
                    return;
                }
                const now = new Date();
                const systemTime = userContact.systemTime ? new Date(userContact.systemTime) : undefined;
                if (userContact.status && userContact.timeInState) {
                    const phoneStatusValue = PhoneStatusValue[userContact.status.toUpperCase()];
                    if (phoneStatusValue) {
                        let phoneStatusStarted;
                        const timeInState = new Date(userContact.timeInState);
                        if (systemTime) {
                            const systemTimeInStateDuration = systemTime.getTime() - timeInState.getTime();
                            phoneStatusStarted = new Date(now.getTime() - (systemTimeInStateDuration < 0 ? 0 : systemTimeInStateDuration));
                        }
                        else {
                            phoneStatusStarted = timeInState;
                        }
                        this.phoneChannelStatus = new PhoneChannelStatus(phoneStatusValue, phoneStatusStarted, emptyStringValue(userContact.dnCallIn), emptyStringValue(userContact.dnCallOut), emptyStringValue(userContact.activityCode), emptyStringValue(userContact.activityCodeLevel2));
                    }
                }
                if (userContact.presenceStatus) {
                    const presenceStatusValue = PresenceStatusValue[userContact.presenceStatus.toUpperCase()];
                    if (presenceStatusValue) {
                        let presenceStatusUntil = undefined;
                        if (userContact.presenceStatusUntil) {
                            const presenceStatusUntilValue = new Date(userContact.presenceStatusUntil);
                            if (presenceStatusUntilValue.getTime() == 0) {
                                if (systemTime) {
                                    const presenceStatusDuration = systemTime.getTime() + presenceStatusUntilValue.getTime();
                                    presenceStatusUntil = new Date(now.getTime() + presenceStatusDuration);
                                }
                                else {
                                    presenceStatusUntil = presenceStatusUntilValue;
                                }
                            }
                        }
                        this.presenceStatus = new PresenceStatus(presenceStatusValue, emptyStringValue(userContact.presenceMessage), presenceStatusUntil);
                    }
                }
            }
        }
        UserStatusMonitor.Value = Value;
    })(UserStatusMonitor || (UserStatusMonitor = {}));

    class Contact {
        constructor(
        data, type, subtype = null) {
            this.data = data;
            this.type = type;
            this.subtype = subtype;
            this.id = data.id;
        }
        static from(client, data) {
            if (isUserContact(data)) {
                return new InternalUserContact(client, data);
            }
            else if (isServiceContact(data)) {
                return new InternalServiceContact(data);
            }
            else if (isShortNumberContact(data)) {
                return new InternalShortNumberContact(data);
            }
            else if (isExternalContact(data)) {
                return new ExternalItemContact(data);
            }
            else if (isExternalOrganizationContact(data)) {
                return new ExternalOrganizationContact(data);
            }
            else if (isPersonalContact(data)) {
                return new PersonalContact(data);
            }
            else {
                return null;
            }
        }
        get addressBookContactType() {
            return this.data.type;
        }
    }
    function isContact(contact) {
        return contact instanceof Contact;
    }
    class InternalUserContact extends Contact {
        constructor(
        client, data) {
            super(data, Contact.Type.INTERNAL, Contact.InternalSubType.USER);
            this.client = client;
            this.data = data;
        }
        get statusMonitor() {
            if (!this._statusMonitor) {
                this._statusMonitor = new UserStatusMonitor(this.client.user, this.data.username, () => __awaiter(this, void 0, void 0, function* () {
                    yield this.client.canDoRequest();
                    if (this.data.username) {
                        return this.client.api.methods.getUserContactStatus(this.data.username);
                    }
                    else {
                        throw "username to request contact status is unavailable";
                    }
                }));
            }
            return this._statusMonitor;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.INTERNAL && contact.subtype === Contact.InternalSubType.USER;
        }
    }
    class InternalServiceContact extends Contact {
        constructor(data) {
            super(data, Contact.Type.INTERNAL, Contact.InternalSubType.SERVICE);
            this.data = data;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.INTERNAL && contact.subtype === Contact.InternalSubType.SERVICE;
        }
    }
    class InternalShortNumberContact extends Contact {
        constructor(data) {
            super(data, Contact.Type.INTERNAL, Contact.InternalSubType.SHORT_NUMBER);
            this.data = data;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.INTERNAL && contact.subtype === Contact.InternalSubType.SHORT_NUMBER;
        }
    }
    class ExternalItemContact extends Contact {
        constructor(data) {
            super(data, Contact.Type.EXTERNAL);
            this.data = data;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.EXTERNAL && contact.subtype === null;
        }
    }
    class ExternalOrganizationContact extends Contact {
        constructor(data) {
            super(data, Contact.Type.EXTERNAL, Contact.ExternalSubType.ORGANIZATION);
            this.data = data;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.EXTERNAL && contact.subtype === Contact.ExternalSubType.ORGANIZATION;
        }
    }
    class PersonalContact extends Contact {
        constructor(data) {
            super(data, Contact.Type.PERSONAL);
            this.data = data;
        }
        static check(contact) {
            return contact && contact.type === Contact.Type.PERSONAL;
        }
    }
    (function (Contact) {
        Contact.PKG = "contact";
        class SearchContactResult extends SearchResult {
            constructor(user, requestOptions) {
                super(`${Contact.PKG}:search`, user.client);
                this.requestOptions = requestOptions;
            }
        }
        Contact.SearchContactResult = SearchContactResult;
        (function (Type) {
            Type["INTERNAL"] = "INTERNAL";
            Type["EXTERNAL"] = "EXTERNAL";
            Type["PERSONAL"] = "PERSONAL";
        })(Contact.Type || (Contact.Type = {}));
        (function (InternalSubType) {
            InternalSubType["SERVICE"] = "SERVICE";
            InternalSubType["USER"] = "USER";
            InternalSubType["SHORT_NUMBER"] = "SHORT_NUMBER";
        })(Contact.InternalSubType || (Contact.InternalSubType = {}));
        (function (ExternalSubType) {
            ExternalSubType["ORGANIZATION"] = "ORGANIZATION";
        })(Contact.ExternalSubType || (Contact.ExternalSubType = {}));
        (function (AddressBookContactAddressType) {
            AddressBookContactAddressType["MAIN"] = "MAIN";
            AddressBookContactAddressType["OTHER"] = "OTHER";
        })(Contact.AddressBookContactAddressType || (Contact.AddressBookContactAddressType = {}));
        (function (AddressBookContactMailType) {
            AddressBookContactMailType["INTERNET_WORK"] = "INTERNET_WORK";
            AddressBookContactMailType["INTERNET_HOME"] = "INTERNET_HOME";
        })(Contact.AddressBookContactMailType || (Contact.AddressBookContactMailType = {}));
        (function (AddressBookContactNumberType) {
            AddressBookContactNumberType["FAX"] = "FAX";
            AddressBookContactNumberType["HOME"] = "HOME";
            AddressBookContactNumberType["CELL"] = "CELL";
            AddressBookContactNumberType["WORK"] = "WORK";
            AddressBookContactNumberType["CELL_WORK"] = "CELL_WORK";
            AddressBookContactNumberType["FAX_WORK"] = "FAX_WORK";
            AddressBookContactNumberType["FAX_HOME"] = "FAX_HOME";
            AddressBookContactNumberType["CELL_HOME"] = "CELL_HOME";
            AddressBookContactNumberType["MAIN"] = "MAIN";
            AddressBookContactNumberType["OTHER"] = "OTHER";
        })(Contact.AddressBookContactNumberType || (Contact.AddressBookContactNumberType = {}));
        (function (AddressBookContactWebType) {
            AddressBookContactWebType["WORK"] = "WORK";
            AddressBookContactWebType["HOME"] = "HOME";
        })(Contact.AddressBookContactWebType || (Contact.AddressBookContactWebType = {}));
    })(Contact || (Contact = {}));

    let Call$1 = class Call extends EventEmitter {
        constructor(
        _device, callId, direction) {
            super(`${Call.PKG}${_device.type.toLowerCase()}`, _device.client);
            this._device = _device;
            this.callId = callId;
            this.direction = direction;
            this._lastChannelEvent = null;
            this._hold = false;
            this._delayIdleEventFromServer = delayedChannelEventHandler((channelEvent, emitEvent) => this.updateFromApi(channelEvent, emitEvent, true), 150);
            this.lookup = new Call.Lookup(this);
            this.detail = new Call.Detail(this);
            this.recording = new Call.Recording(this);
        }
        get device() {
            return this._device;
        }
        get id() {
            return this.detail.id;
        }
        get startTime() {
            return this.detail.startTime;
        }
        get endTime() {
            return this.detail.endTime;
        }
        get duration() {
            return this.detail.duration;
        }
        get service() {
            return this.detail.service;
        }
        get callData() {
            return this.detail.callData;
        }
        get features() {
            return this._features ? this._features : [];
        }
        get lastUpdateMessageDate() {
            if (this._lastChannelEventTime) {
                return new Date(this._lastChannelEventTime);
            }
            else {
                return null;
            }
        }
        get lastChannelEvent() {
            return this._lastChannelEvent;
        }
        eventLogId() {
            return this.callId;
        }
        updateFromApi(channelEvent, emitEvent, isDelayed) {
            return __awaiter(this, void 0, void 0, function* () {
                const previouseFeatures = [...this.features];
                this._lastChannelEvent = channelEvent;
                const callInfo = channelEvent.callInfo;
                if (callInfo.time) {
                    this._lastChannelEventTime = callInfo.time;
                }
                if (callInfo.features) {
                    this._features = callInfo.features;
                }
                const newFeatures = this.features;
                if (previouseFeatures.length !== newFeatures.length || previouseFeatures.find((f) => newFeatures.indexOf(f) < 0) || newFeatures.find((f) => previouseFeatures.indexOf(f) < 0)) {
                    this.featureChange(newFeatures, previouseFeatures, emitEvent);
                }
                yield this.recording.updateFromApi(channelEvent, emitEvent, isDelayed);
                yield this.lookup.updateFromApi(channelEvent, emitEvent, isDelayed);
                yield this.detail.updateFromApi(channelEvent, emitEvent, isDelayed);
            });
        }
        hasFeature(feature) {
            var _a, _b, _c;
            return ((_c = (_b = (_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.features) === null || _b === void 0 ? void 0 : _b.indexOf(feature)) !== null && _c !== void 0 ? _c : -1) > -1;
        }
        setCallData(data) {
            return __awaiter(this, void 0, void 0, function* () {
                const result = yield this.device.client.api.methods.setCallData(this.callId, data);
                if (result) {
                    this.detail.callData = data;
                }
                return result;
            });
        }
        hold() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.isOnHold()) {
                    const response = yield this.device.client.api.methods.hold(this.callId);
                    if (response) {
                        this._hold = true;
                    }
                    else {
                        this._hold = false;
                    }
                    return response;
                }
                return false;
            });
        }
        unhold() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.isOnHold()) {
                    const response = yield this.device.client.api.methods.unhold(this.callId);
                    if (response) {
                        this._hold = false;
                    }
                    else {
                        this._hold = true;
                    }
                    return response;
                }
                else {
                    return false;
                }
            });
        }
    };
    (function (Call) {
        Call.PKG = "call";
        (function (Direction) {
            Direction["INBOUND"] = "inbound";
            Direction["OUTBOUND"] = "outbound";
        })(Call.Direction || (Call.Direction = {}));
        (function (CallFeature) {
            CallFeature["ACCEPT"] = "ACCEPT";
            CallFeature["ANSWER"] = "ANSWER";
            CallFeature["CANCEL"] = "CANCEL";
            CallFeature["CONFERENCE"] = "CONFERENCE";
            CallFeature["DIAL"] = "DIAL";
            CallFeature["HOLD"] = "HOLD";
            CallFeature["UNHOLD"] = "UNHOLD";
            CallFeature["GENERATE_DTMF"] = "GENERATE_DTMF";
            CallFeature["MONITOR_START"] = "MONITOR_START";
            CallFeature["MONITOR_STOP"] = "MONITOR_STOP";
            CallFeature["SETCALLDATA"] = "SETCALLDATA";
            CallFeature["TRANSFER_BLIND"] = "TRANSFER_BLIND";
            CallFeature["TRANSFER_ATTENDED"] = "TRANSFER_ATTENDED";
            CallFeature["REJECT"] = "REJECT";
            CallFeature["DIAL_ATXFER"] = "DIAL_ATXFER";
            CallFeature["ATXFER_CANCEL"] = "ATXFER_CANCEL";
        })(Call.CallFeature || (Call.CallFeature = {}));
        let AutomaticCallRecordingType;
        (function (AutomaticCallRecordingType) {
            AutomaticCallRecordingType["DISABLED"] = "DISABLED";
            AutomaticCallRecordingType["AUTOMATIC_BY_SERVICE"] = "AUTOMATIC_BY_SERVICE";
            AutomaticCallRecordingType["AUTOMATIC_BY_USER"] = "AUTOMATIC_BY_USER";
        })(AutomaticCallRecordingType = Call.AutomaticCallRecordingType || (Call.AutomaticCallRecordingType = {}));
        class Lookup extends EventEmitter {
            constructor(
            _call) {
                super(`${Call.PKG}${_call.device.type.toLowerCase()}:lookup`, _call.device.client);
                this._call = _call;
                this._status = "progress";
                this.display = {};
            }
            get device() {
                return this._call.device;
            }
            get contact() {
                return this._contact;
            }
            get status() {
                return this._status;
            }
            get result() {
                return this._result;
            }
            eventLogId() {
                return this._call.callId;
            }
            updateFromApi(channelEvent, emitEvent, isDelayed) {
                var _a;
                return __awaiter(this, void 0, void 0, function* () {
                    let emitDisplay = false;
                    const callInfo = channelEvent.callInfo;
                    if (this.display.company != callInfo.lookup_display_company) {
                        this.display.company = callInfo.lookup_display_company;
                        emitDisplay = true;
                    }
                    if (this.display.name != callInfo.lookup_display_name) {
                        this.display.name = callInfo.lookup_display_name;
                        emitDisplay = true;
                    }
                    const lookup_display_number = callInfo.lookup_display_number || callInfo.remoteNumber;
                    if (this.display.number != lookup_display_number && !!lookup_display_number) {
                        this.display.number = lookup_display_number;
                        emitDisplay = true;
                    }
                    if (emitDisplay && emitEvent) {
                        this.emit("update_display", this.display, this);
                    }
                    let emitUpdateContact, resetContact = false;
                    if (callInfo.lookup_addressbook_type) {
                        const contact = Contact.from(this.device.client, { type: callInfo.lookup_addressbook_type, id: callInfo.lookup_addressbook_uid, username: callInfo.lookup_addressbook_username, photo: callInfo.lookup_addressbook_photo });
                        if (contact) {
                            this._contact = contact;
                            emitUpdateContact = true;
                        }
                        else {
                            resetContact = true;
                        }
                    }
                    else {
                        resetContact = true;
                    }
                    if (resetContact) {
                        emitUpdateContact = this._contact !== undefined;
                        this._contact = undefined;
                    }
                    if (emitUpdateContact && emitEvent) {
                        this.emit("update_contact", (_a = this.contact) !== null && _a !== void 0 ? _a : null, this);
                    }
                    if (callInfo.lookup_finished) {
                        this._status = "end";
                        this._result = callInfo.lookup_display_result;
                        if (emitEvent) {
                            this.emit("end");
                        }
                    }
                });
            }
        }
        Lookup.update_contact = "update_contact";
        Lookup.update_display = "update_display";
        Lookup.end = "end";
        Call.Lookup = Lookup;
        (function (LookupResult) {
            LookupResult["SUCCESS"] = "SUCCESS";
            LookupResult["MULTIPLE"] = "MULTIPLE";
            LookupResult["ERROR"] = "ERROR";
            LookupResult["NONE"] = "NONE";
        })(Call.LookupResult || (Call.LookupResult = {}));
        class Recording extends EventEmitter {
            constructor(
            _call) {
                super(`${Call.PKG}${_call.device.type.toLowerCase()}:recording`, _call.device.client);
                this._call = _call;
                this._automaticType = Call.AutomaticCallRecordingType.DISABLED;
                this._ondemandrecordingRequested = false;
                this._ondemandrecordingStarted = false;
            }
            updateFromApi(channelEvent, emitEvent, isDelayed) {
                return __awaiter(this, void 0, void 0, function* () {
                    const callInfo = channelEvent.callInfo;
                    if (callInfo.state === CallState.IDLE) {
                        if (this._ondemandrecordingStarted) {
                            callInfo.smartrec_type = RecType.ondemand_stop;
                        }
                        else if (this._ondemandrecordingRequested) {
                            callInfo.smartrec_type = RecType.error;
                        }
                        else {
                            callInfo.smartrec_type = undefined;
                        }
                    }
                    else {
                        if (!this._note_table) {
                            this._note_table = callInfo.smartrec_table;
                        }
                        if (!this._note_key) {
                            this._note_key = callInfo.smartrec_key;
                        }
                        if (this._automaticType === Call.AutomaticCallRecordingType.DISABLED) {
                            switch (callInfo.smartrec_type) {
                                case RecType.service:
                                    this._automaticType = Call.AutomaticCallRecordingType.AUTOMATIC_BY_SERVICE;
                                    break;
                                case RecType.automatic:
                                    this._automaticType = Call.AutomaticCallRecordingType.AUTOMATIC_BY_USER;
                                    break;
                            }
                            if (this._automaticType !== Call.AutomaticCallRecordingType.DISABLED) {
                                if (emitEvent) {
                                    this.emit("automatic_type_change", this._automaticType);
                                }
                            }
                        }
                    }
                    switch (callInfo.smartrec_type) {
                        case RecType.ondemand_start:
                            this._ondemandrecordingRequested = true;
                            this._ondemandrecordingStarted = true;
                            if (emitEvent) {
                                this.emit("on_demand_start");
                            }
                            break;
                        case RecType.ondemand_stop:
                            this._ondemandrecordingRequested = false;
                            this._ondemandrecordingStarted = false;
                            if (emitEvent) {
                                this.emit("on_demand_stop");
                            }
                            break;
                        case RecType.error:
                            this._ondemandrecordingRequested = false;
                            this._ondemandrecordingStarted = false;
                            if (emitEvent) {
                                this.emit("on_demand_error");
                            }
                            break;
                    }
                });
            }
            get onDemandEnabled() {
                return this.getOnDemandEnabledComponent().isEnabled();
            }
            get automaticEnabled() {
                return this._automaticType !== AutomaticCallRecordingType.DISABLED;
            }
            get automaticType() {
                return this._automaticType;
            }
            getOnDemandEnabledComponent() {
                var _a, _b;
                const byProfileConfiguration = ((_a = this._call.device.client.user.info.profile) === null || _a === void 0 ? void 0 : _a.callRecording) === Profile.CallRecording.ON_DEMAND || ((_b = this._call.device.client.user.info.profile) === null || _b === void 0 ? void 0 : _b.callRecording) === Profile.CallRecording.ON_DEMAND_WITH_NOTE;
                const byCallFeature = this._call.features.includes(Call.CallFeature.MONITOR_START) || this._call.features.includes(Call.CallFeature.MONITOR_STOP);
                return { isEnabled: () => byProfileConfiguration && byCallFeature, component: { byProfileConfiguration, byCallFeature } };
            }
            onDemandRecordingStarted() {
                return this._ondemandrecordingRequested && this._ondemandrecordingStarted;
            }
            get addNoteEnabled() {
                var _a;
                let addNoteEnabled = false;
                switch ((_a = this._call.device.client.user.info.profile) === null || _a === void 0 ? void 0 : _a.callRecording) {
                    case Profile.CallRecording.ON_DEMAND_WITH_NOTE:
                        if (this._ondemandrecordingRequested) {
                            addNoteEnabled = true;
                        }
                        break;
                    case Profile.CallRecording.AUTOMATIC_WITH_NOTE:
                        addNoteEnabled = true;
                        break;
                }
                return addNoteEnabled;
            }
            addNote(note, additionalData) {
                var _a;
                return __awaiter(this, void 0, void 0, function* () {
                    if (this.addNoteEnabled) {
                        if (this._note_table && this._note_key) {
                            const response = yield this._call.device.client.api.methods.updateCallRecordingNote(this._note_table, this._note_key, note, additionalData !== null && additionalData !== void 0 ? additionalData : "");
                            return response;
                        }
                        else {
                            throw new Error("add note error, missing some required value from server");
                        }
                    }
                    else if (((_a = this._call.device.client.user.info.profile) === null || _a === void 0 ? void 0 : _a.callRecording) === Profile.CallRecording.ON_DEMAND_WITH_NOTE && !this._ondemandrecordingRequested) {
                        throw new Error("add note to on demand recording is unavailable, call startRecord() first");
                    }
                    else {
                        throw new Error("add note to call recording is not enabled on user profile");
                    }
                });
            }
            startRecord() {
                return __awaiter(this, void 0, void 0, function* () {
                    if (this._ondemandrecordingRequested) {
                        return false;
                    }
                    const onDemandEnabledComponent = this.getOnDemandEnabledComponent();
                    if (onDemandEnabledComponent.isEnabled()) {
                        const response = yield this._call.device.client.api.methods.startRecord(this._call.callId);
                        if (response) {
                            this._ondemandrecordingRequested = true;
                        }
                        return response;
                    }
                    else {
                        if (!onDemandEnabledComponent.component.byProfileConfiguration) {
                            throw new Error("startRecord error, on demand recording is not enabled on user profile");
                        }
                        if (!onDemandEnabledComponent.component.byCallFeature) {
                            throw new Error("startRecord error, on demand recording is not enabled on call feature");
                        }
                        return false;
                    }
                });
            }
            stopRecord() {
                return __awaiter(this, void 0, void 0, function* () {
                    if (this._ondemandrecordingRequested) {
                        const response = yield this._call.device.client.api.methods.stopRecord(this._call.callId);
                        if (response) {
                            this._ondemandrecordingRequested = false;
                        }
                        return response;
                    }
                    else {
                        return false;
                    }
                });
            }
        }
        Recording.automatic_type_change = "automatic_type_set";
        Recording.on_demand_start = "on_demand_start";
        Recording.on_demand_stop = "on_demand_stop";
        Recording.on_demand_error = "on_demand_error";
        Call.Recording = Recording;
        class Detail extends EventEmitter {
            constructor(
            _call) {
                super(`${Call.PKG}${_call.device.type.toLowerCase()}:detail`, _call.device.client);
                this._call = _call;
                this._startTime = new Date();
            }
            get device() {
                return this._call.device;
            }
            get rawInfo() {
                return this._rawInfo;
            }
            get id() {
                return this._uniqueId || this._call.callId;
            }
            get startTime() {
                return this._startTime;
            }
            get endTime() {
                return this._endTime;
            }
            set endTime(endTime) {
                this._endTime = endTime;
            }
            get duration() {
                return this._duration;
            }
            set duration(duration) {
                this._duration = duration;
            }
            get remoteNumber() {
                return this._remoteNumber;
            }
            get service() {
                return this._service;
            }
            get callData() {
                return this._callData;
            }
            set callData(callData) {
                this._callData = callData;
            }
            get popupInfo() {
                return this._popupInfo;
            }
            get skillset() {
                var _a;
                return (_a = this._rawInfo) === null || _a === void 0 ? void 0 : _a.skillset;
            }
            get ivrLabel() {
                var _a;
                return (_a = this._rawInfo) === null || _a === void 0 ? void 0 : _a.ivr_label;
            }
            get outboundCampaignId() {
                var _a;
                return (_a = this._rawInfo) === null || _a === void 0 ? void 0 : _a.campagna;
            }
            get outboundListId() {
                var _a;
                return (_a = this._rawInfo) === null || _a === void 0 ? void 0 : _a.lista;
            }
            eventLogId() {
                return this._call.callId;
            }
            updateFromApi(channelEvent, emitEvent, isDelayed) {
                var _a, _b, _c, _d, _e, _f;
                return __awaiter(this, void 0, void 0, function* () {
                    let detailChanged = false;
                    const callInfo = channelEvent.callInfo;
                    if (callInfo.calldata !== undefined) {
                        detailChanged = detailChanged || this._callData !== callInfo.calldata;
                        this._callData = callInfo.calldata;
                    }
                    if (callInfo.cdrid && this._uniqueId !== callInfo.cdrid) {
                        detailChanged = detailChanged || this._uniqueId !== callInfo.cdrid;
                        this._uniqueId = callInfo.cdrid;
                    }
                    if (callInfo.duration && this._duration !== callInfo.duration) {
                        detailChanged = detailChanged || this._duration !== callInfo.duration;
                        this._duration = callInfo.duration;
                    }
                    if (callInfo.service) {
                        detailChanged = detailChanged || ((_a = this._service) === null || _a === void 0 ? void 0 : _a.code) !== callInfo.service;
                        this._service = {
                            code: callInfo.service,
                            description: (_d = (_c = (_b = this.device.client.user.info.profile) === null || _b === void 0 ? void 0 : _b.getServiceByCode(callInfo.service)) === null || _c === void 0 ? void 0 : _c.description) !== null && _d !== void 0 ? _d : callInfo.service,
                        };
                    }
                    if (callInfo.start) {
                        try {
                            const startDate = new Date(callInfo.start);
                            detailChanged = detailChanged || this._startTime !== startDate;
                            this._startTime = startDate;
                        }
                        catch (e) { }
                    }
                    if (callInfo.remoteNumber !== undefined) {
                        detailChanged = detailChanged || this._remoteNumber !== callInfo.remoteNumber;
                        this._remoteNumber = callInfo.remoteNumber;
                    }
                    if (callInfo.database && callInfo.database["0"] != null && ChannelType.Omnidesk !== channelIdToChannelType(callInfo.channelid)) {
                        this._rawInfo = callInfo.database["0"];
                    }
                    const popupinfo = (_f = (_e = this._rawInfo) === null || _e === void 0 ? void 0 : _e.popupinfo) !== null && _f !== void 0 ? _f : null;
                    if (popupinfo) {
                        if (!this._popupInfo) {
                            this._popupInfo = {};
                        }
                        try {
                            const popupinfoData = popupinfo.split("|");
                            if (popupinfoData && popupinfoData.length) {
                                popupinfoData.forEach((element) => {
                                    if (element !== "_") {
                                        const elData = element.split("=");
                                        const variableName = elData.splice(0, 1)[0];
                                        const variableValue = elData.join("=");
                                        detailChanged = detailChanged || this._popupInfo[variableName] !== variableValue;
                                        this._popupInfo[variableName] = variableValue;
                                    }
                                });
                            }
                        }
                        catch (_g) { }
                    }
                    if (detailChanged && emitEvent) {
                        this.emit("update_detail");
                    }
                });
            }
        }
        Detail.update_detail = "update_detail";
        Call.Detail = Detail;
    })(Call$1 || (Call$1 = {}));

    class CallSip extends Call$1 {
        constructor(device, callId, direction) {
            super(device, callId, direction);
            this.type = exports.C.LineType.SIP;
        }
        get callSipForTransferInstance() {
            return this._callSipForTransferInstance;
        }
        updateFromApi(channelEvent, emitEvent, isDelayed) {
            const _super = Object.create(null, {
                updateFromApi: { get: () => super.updateFromApi }
            });
            var _a, _b, _c, _d, _e;
            return __awaiter(this, void 0, void 0, function* () {
                const callInfo = channelEvent.callInfo;
                let eventToEmit;
                if (callInfo.state === CallState.IDLE) {
                    if (channelEvent.isGeneratedByServer()) {
                        if (isDelayed) {
                            if (!this.detail.endTime) {
                                try {
                                    this.detail.endTime = new Date((_a = callInfo.time) !== null && _a !== void 0 ? _a : new Date());
                                }
                                catch (e) {
                                    this.detail.endTime = new Date();
                                }
                            }
                            if (((_b = callInfo.duration) !== null && _b !== void 0 ? _b : -1) >= 0) {
                                this.detail.duration = callInfo.duration;
                            }
                            (_c = this.callSipForTransferInstance) === null || _c === void 0 ? void 0 : _c.setEnded(emitEvent);
                            eventToEmit = "ended";
                        }
                        else {
                            yield this._delayIdleEventFromServer(channelEvent, emitEvent);
                        }
                    }
                    else {
                        eventToEmit = "ended_request";
                    }
                }
                else {
                    if (!this._lastChannelEvent) {
                        yield _super.updateFromApi.call(this, channelEvent, emitEvent, isDelayed);
                        eventToEmit = "connecting";
                    }
                    else if (((_d = this._lastChannelEvent) === null || _d === void 0 ? void 0 : _d.callInfo.state) === callInfo.state) {
                        eventToEmit = "progress";
                    }
                    else if (callInfo.state === CallState.CONNECTED) {
                        (_e = this.callSipForTransferInstance) === null || _e === void 0 ? void 0 : _e.setEnded(emitEvent);
                        eventToEmit = "accepted";
                    }
                }
                if (this._lastChannelEvent !== channelEvent) {
                    yield _super.updateFromApi.call(this, channelEvent, emitEvent, isDelayed);
                }
                if (emitEvent && eventToEmit) {
                    this.emit(eventToEmit);
                }
            });
        }
        featureChange(features, previousFeatures, emitEvent = true) {
            if (emitEvent) {
                this.emit("change_features", features, previousFeatures);
            }
        }
        isInProgress() {
            var _a, _b;
            return ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.NEW_INBOUND || ((_b = this._lastChannelEvent) === null || _b === void 0 ? void 0 : _b.callInfo.state) === CallState.NEW_OUTBOUND;
        }
        isEstablished() {
            var _a;
            return !this.isInProgress() && ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) !== CallState.IDLE;
        }
        isEnded() {
            var _a;
            return ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.IDLE;
        }
        isOnHold() {
            var _a, _b;
            return this._hold || ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.HOLD || ((_b = this._lastChannelEvent) === null || _b === void 0 ? void 0 : _b.callInfo.state) === CallState.HOLD_PENDING_SIP;
        }
        answer() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.device.client.api.methods.answerOnChannel(ChannelType.PhoneCall, this.callId, null);
            });
        }
        terminate() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.hasFeature(Call$1.CallFeature.ATXFER_CANCEL)) {
                    if (this._callSipForTransferInstance) {
                        return this._callSipForTransferInstance.terminate();
                    }
                    else {
                        if (yield this.device.client.api.methods.cancelTransferOnGenericDevice({ callId: this.callId })) {
                            return this.device.client.api.methods.cancel(this.callId);
                        }
                        else {
                            return false;
                        }
                    }
                }
                else {
                    return this.device.client.api.methods.cancel(this.callId);
                }
            });
        }
        sendDTMF(tone) {
            return __awaiter(this, void 0, void 0, function* () {
                const response = yield this.device.client.api.methods.sendDTMF(this.callId, `${tone}`, true);
                this.emit("newDTMF", tone);
                return response;
            });
        }
        hold() {
            const _super = Object.create(null, {
                hold: { get: () => super.hold }
            });
            return __awaiter(this, void 0, void 0, function* () {
                const holdIsDone = yield _super.hold.call(this);
                if (holdIsDone) {
                    this.emit("hold");
                }
                return holdIsDone;
            });
        }
        unhold() {
            const _super = Object.create(null, {
                unhold: { get: () => super.unhold }
            });
            return __awaiter(this, void 0, void 0, function* () {
                const unholdIsDone = yield _super.unhold.call(this);
                if (unholdIsDone) {
                    this.emit("unhold");
                }
                return unholdIsDone;
            });
        }
        isDialForTransferEnabled() {
            return this.hasFeature(Call$1.CallFeature.DIAL_ATXFER);
        }
        dialForTransfer(phoneNumber, param) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (this._callSipForTransferInstance) {
                    throw new Error("cannot call dialForTransfer, another call is ongoing");
                }
                else {
                    if (this.isDialForTransferEnabled()) {
                        const dialData = [param === null || param === void 0 ? void 0 : param.note1, param === null || param === void 0 ? void 0 : param.note2].filter((note) => (note !== null && note !== void 0 ? note : null) !== null);
                        const dialATXferOnGenericDeviceDone = yield this.device.client.api.methods.dialATXferOnGenericDevice({
                            callId: this.callId,
                            number: phoneNumber,
                            access_code: param === null || param === void 0 ? void 0 : param.accessCode,
                            service: param === null || param === void 0 ? void 0 : param.serviceCode,
                            uid: (_a = param === null || param === void 0 ? void 0 : param.contact) === null || _a === void 0 ? void 0 : _a.id,
                            data: dialData.length ? dialData : undefined,
                        });
                        if (dialATXferOnGenericDeviceDone) {
                            const callSipForTransferInstance = new CallSipForTransfer(this.device, this).on("ended", (_callSipForTransferInstance) => {
                                this._callSipForTransferInstance = undefined;
                            });
                            this._callSipForTransferInstance = callSipForTransferInstance;
                            this.emit("new_call_for_transfer", callSipForTransferInstance);
                            return callSipForTransferInstance;
                        }
                        else {
                            throw new Error("dialForTransfer return false");
                        }
                    }
                    else {
                        throw new Error("cannot call dialForTransfer");
                    }
                }
            });
        }
        transferToNumber(number) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.transfer(number);
            });
        }
        transferToCall(call) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.transfer(call);
            });
        }
        transfer(target) {
            return __awaiter(this, void 0, void 0, function* () {
                if (isString(target)) {
                    return this.device.client.api.methods.blindTransfer(this.callId, null, target, null);
                }
                else if (target instanceof CallSip) {
                    return this.device.client.api.methods.attendedTransfer(this.callId, target.callId, null);
                }
                else {
                    throw "invalid target for transfer";
                }
            });
        }
    }
    CallSip.connecting = "connecting";
    CallSip.progress = "progress";
    CallSip.accepted = "accepted";
    CallSip.ended = "ended";
    CallSip.ended_request = "ended_request";
    CallSip.newDTMF = "newDTMF";
    CallSip.hold = "hold";
    CallSip.unhold = "unhold";
    CallSip.change_features = "change_features";
    CallSip.new_call_for_transfer = "new_call_for_transfer";
    class CallSipForTransfer extends EventEmitter {
        constructor(
        device,
        _callSip) {
            super(`${Call$1.PKG}sip:transfer`, device.client);
            this.device = device;
            this._callSip = _callSip;
            this._ended = false;
        }
        eventLogId() {
            return this._callSip.callId;
        }
        setEnded(emitEvent = true) {
            if (!this._ended) {
                this._ended = true;
                if (emitEvent) {
                    this.emit("ended", this);
                }
            }
        }
        isEnded() {
            return this._ended;
        }
        get callSip() {
            return this._callSip;
        }
        transfer() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this._ended) {
                    throw new Error("transfer not allowed, this instance is ended");
                }
                else {
                    if (this.callSip.hasFeature(Call$1.CallFeature.CANCEL)) {
                        if (yield this.device.client.api.methods.cancel(this.callSip.callId)) {
                            this.setEnded();
                            return true;
                        }
                        else {
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
            });
        }
        terminate() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this._ended) {
                    throw new Error("terminate not allowed, this instance is ended");
                }
                else {
                    if (this.callSip.hasFeature(Call$1.CallFeature.ATXFER_CANCEL)) {
                        if (yield this.device.client.api.methods.cancelTransferOnGenericDevice({ callId: this.callSip.callId })) {
                            this.setEnded();
                            return true;
                        }
                        else {
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
            });
        }
    }
    CallSipForTransfer.ended = "ended";

    class CallWebrtc extends Call$1 {
        constructor(device, id, direction) {
            super(device, id, direction);
            this.type = exports.C.LineType.WEBRTC;
            this._connectionManager = new CallWebrtc.ConnectionManager(this);
        }
        get nativeCall() {
            var _a;
            if (!this._nativeCall) {
                this._nativeCall = (_a = this.device.client.api.webrtc) === null || _a === void 0 ? void 0 : _a.retriveCall(this.callId);
            }
            return this._nativeCall;
        }
        get connectionManager() {
            return this._connectionManager;
        }
        updateFromApi(channelEvent, emitEvent, isDelayed) {
            const _super = Object.create(null, {
                updateFromApi: { get: () => super.updateFromApi }
            });
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function* () {
                const callInfo = channelEvent.callInfo;
                let eventToEmit;
                if (callInfo.state === CallState.IDLE) {
                    if (channelEvent.isGeneratedByServer()) {
                        if (isDelayed) {
                            if (!this.detail.endTime) {
                                try {
                                    this.detail.endTime = new Date((_a = callInfo.time) !== null && _a !== void 0 ? _a : new Date());
                                }
                                catch (e) {
                                    this.detail.endTime = new Date();
                                }
                            }
                            if (((_b = callInfo.duration) !== null && _b !== void 0 ? _b : -1) >= 0) {
                                this.detail.duration = callInfo.duration;
                            }
                            eventToEmit = "ended";
                        }
                        else {
                            yield this._delayIdleEventFromServer(channelEvent, emitEvent);
                        }
                    }
                    else {
                        eventToEmit = "ended_request";
                    }
                }
                else {
                    if (!this._lastChannelEvent) {
                        yield _super.updateFromApi.call(this, channelEvent, emitEvent, isDelayed);
                        eventToEmit = "connecting";
                    }
                    else if (((_c = this._lastChannelEvent) === null || _c === void 0 ? void 0 : _c.callInfo.state) === callInfo.state) {
                        eventToEmit = "progress";
                    }
                    else if (callInfo.state === CallState.CONNECTED) {
                        eventToEmit = "accepted";
                    }
                }
                if (this._lastChannelEvent !== channelEvent) {
                    yield _super.updateFromApi.call(this, channelEvent, emitEvent, isDelayed);
                }
                if (emitEvent && eventToEmit) {
                    this.emit(eventToEmit);
                }
            });
        }
        featureChange(features, previousFeatures, emitEvent = true) {
            if (emitEvent) {
                this.emit("change_features", features, previousFeatures);
            }
        }
        isInProgress() {
            var _a, _b;
            return ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.NEW_INBOUND || ((_b = this._lastChannelEvent) === null || _b === void 0 ? void 0 : _b.callInfo.state) === CallState.NEW_OUTBOUND;
        }
        isEstablished() {
            var _a;
            return !this.isInProgress() && ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) !== CallState.IDLE;
        }
        isEnded() {
            var _a;
            return ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.IDLE;
        }
        isOnHold() {
            var _a;
            return this._hold || ((_a = this._lastChannelEvent) === null || _a === void 0 ? void 0 : _a.callInfo.state) === CallState.HOLD;
        }
        answerAudio(customFields) {
            return this.answer({ audio: true }, customFields);
        }
        answerVideo(customFields, videoContainer) {
            return this.answer({ audio: true, video: true }, customFields, videoContainer);
        }
        answer(media, customFields, videoContainer) {
            var _a, _b, _c;
            const mediaToAnswer = (_c = media !== null && media !== void 0 ? media : (_b = (_a = this.device.client.api.webrtc) === null || _a === void 0 ? void 0 : _a.retriveCall(this.callId)) === null || _b === void 0 ? void 0 : _b.remoteCallMedia) !== null && _c !== void 0 ? _c : { audio: true };
            return this.device.client.api.methods.answerOnChannel(ChannelType.PhoneCall, this.callId, mediaToAnswer, customFields, videoContainer);
        }
        terminate() {
            return this.device.client.api.methods.cancel(this.callId);
        }
        sendDTMF(tone, playTone = true) {
            return this.device.client.api.methods.sendDTMF(this.callId, `${tone}`, playTone);
        }
        hold() {
            const _super = Object.create(null, {
                hold: { get: () => super.hold }
            });
            return __awaiter(this, void 0, void 0, function* () {
                const holdIsDone = yield _super.hold.call(this);
                if (holdIsDone) {
                    this.emit("hold");
                }
                return holdIsDone;
            });
        }
        unhold() {
            const _super = Object.create(null, {
                unhold: { get: () => super.unhold }
            });
            return __awaiter(this, void 0, void 0, function* () {
                const unholdIsDone = yield _super.unhold.call(this);
                if (unholdIsDone) {
                    this.emit("unhold");
                }
                return unholdIsDone;
            });
        }
        transferToNunber(number, accessCode, data) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.transfer({ number, accessCode, data });
            });
        }
        transferToCall(target) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.transfer(target);
            });
        }
        transfer(target) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                if (isTargetNumber(target)) {
                    return this.device.client.api.methods.blindTransfer(this.callId, (_a = target.accessCode) !== null && _a !== void 0 ? _a : null, target.number, (_b = target.data) !== null && _b !== void 0 ? _b : null);
                }
                else if (target instanceof CallWebrtc || target instanceof CallSip) {
                    return this.device.client.api.methods.attendedTransfer(this.callId, target.callId, null);
                }
                else {
                    throw "invalid target for transfer";
                }
            });
        }
        mute(options) {
            return this.device.client.api.methods.mute(this.callId, options);
        }
        unmute(options) {
            return this.device.client.api.methods.unmute(this.callId, options);
        }
    }
    CallWebrtc.connecting = "connecting";
    CallWebrtc.progress = "progress";
    CallWebrtc.accepted = "accepted";
    CallWebrtc.ended = "ended";
    CallWebrtc.ended_request = "ended_request";
    CallWebrtc.newDTMF = "newDTMF";
    CallWebrtc.hold = "hold";
    CallWebrtc.unhold = "unhold";
    function isTargetNumber(target) {
        return target.hasOwnProperty("number") && isString(target.number);
    }
    (function (CallWebrtc) {
        class ConnectionManager extends EventEmitter {
            constructor(
            call) {
                super(`${Call$1.PKG}webrtc`, call.device.client);
                this.call = call;
                this._subscriptions = {};
                call.on("ended", () => {
                    var _a;
                    for (const key in this._subscriptions) {
                        (_a = this._subscriptions[key]) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                    }
                    this._subscriptions = {};
                });
                this._subscriptions.state = this.call.device.client.api.webrtc.callConnectionState.pipe(filter((state) => state.callId === this.call.callId)).subscribe((state) => {
                    if (state.error) {
                        this.emit("connection_error", state.error);
                    }
                    else {
                        this.emit("state", state.connectionState);
                    }
                });
            }
            eventLogId() {
                return this.call.callId;
            }
            get _call() {
                return this.call.device.client.api.webrtc.retriveCall(this.call.callId);
            }
            startLocalAudioLevel() {
                this.stopLocalAudioLevel();
                this._subscriptions.localAudioLevel = this._call.getLocalAudioLevel().subscribe((level) => {
                    this.emitSilent("local_audio_level", level);
                });
            }
            stopLocalAudioLevel() {
                var _a;
                (_a = this._subscriptions.localAudioLevel) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                this._subscriptions.localAudioLevel = undefined;
            }
            startRemoteAudioLevel() {
                var _a;
                this.stopRemoteAudioLevel();
                this._subscriptions.remoteAudioLevel = (_a = this._call) === null || _a === void 0 ? void 0 : _a.getRemoteAudioLevel().subscribe((level) => {
                    this.emitSilent("remote_audio_level", level);
                });
            }
            stopRemoteAudioLevel() {
                var _a;
                (_a = this._subscriptions.remoteAudioLevel) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                this._subscriptions.remoteAudioLevel = undefined;
            }
            startConnectionStats() {
                var _a;
                this.stopConnectionStats();
                this._subscriptions.connectionStats = (_a = this._call) === null || _a === void 0 ? void 0 : _a.getConnectionStats().subscribe((stats) => {
                    this.emitGracefully("stats", 10, stats);
                });
            }
            stopConnectionStats() {
                var _a;
                (_a = this._subscriptions.connectionStats) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                this._subscriptions.connectionStats = undefined;
                this._eventCounter["stats"] = undefined;
            }
        }
        CallWebrtc.ConnectionManager = ConnectionManager;
        (function (ConnectionManager) {
            (function (State) {
                State["New"] = "new";
                State["Initializing"] = "initializing";
                State["Connecting"] = "connecting";
                State["Connected"] = "connected";
                State["Failing"] = "failing";
                State["Failed"] = "failed";
                State["Closing"] = "closing";
                State["Closed"] = "closed";
            })(ConnectionManager.State || (ConnectionManager.State = {}));
        })(ConnectionManager = CallWebrtc.ConnectionManager || (CallWebrtc.ConnectionManager = {}));
    })(CallWebrtc || (CallWebrtc = {}));

    class DeviceSip {
        constructor(
        _phone,
        label,
        exten) {
            this._phone = _phone;
            this.label = label;
            this.exten = exten;
            this.type = exports.C.LineType.SIP;
        }
        get client() {
            return this._phone.client;
        }
        get phone() {
            return this._phone;
        }
        dial(phoneNumber, dialParamValue) {
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function* () {
                const contactIdentifier = {
                    type: AddressBookContactType.UNKNOWN,
                    value: phoneNumber,
                };
                const param = dialParamValue;
                if (param === null || param === void 0 ? void 0 : param.contactIdentifier) {
                    Object.assign(contactIdentifier, param.contactIdentifier);
                }
                const dialParam = {
                    fromDeviceType: ExtenType.SIP,
                    fromDevice: this.exten,
                    media: { audio: true },
                    accessCode: param === null || param === void 0 ? void 0 : param.accessCode,
                    privateCall: param === null || param === void 0 ? void 0 : param.privateCall,
                    serviceCode: param === null || param === void 0 ? void 0 : param.serviceCode,
                    note1: param === null || param === void 0 ? void 0 : param.note1,
                    note2: param === null || param === void 0 ? void 0 : param.note2,
                    channelId: ChannelType.PhoneCall,
                    contact: contactIdentifier,
                };
                if (param === null || param === void 0 ? void 0 : param.contact) {
                    contactIdentifier.uid = param.contact.id;
                    contactIdentifier.type = (_a = param.contact.addressBookContactType) !== null && _a !== void 0 ? _a : contactIdentifier.type;
                    if (InternalUserContact.check(param.contact)) {
                        const contactIdentifierWithUser = contactIdentifier;
                        contactIdentifierWithUser.username = param.contact.data.username;
                        contactIdentifierWithUser.surname = param.contact.data.surname;
                        contactIdentifierWithUser.name = param.contact.data.name;
                    }
                }
                if ((_c = (_b = dialParam.contact) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : null) {
                    try {
                        const response = yield this.client.api.methods.dial(dialParam);
                        if (!response) {
                            throw "Unable to dial, server response is empty";
                        }
                    }
                    catch (e) {
                        if (e instanceof DeviceRequestFailed) {
                            throw "TVox Client not logged";
                        }
                        else {
                            throw e;
                        }
                    }
                }
                else {
                    throw "Unable to dial, phoneNumber is empty";
                }
            });
        }
    }

    class LocalMediaConfigurationConstraints {
        constructor(config, prefix) {
            if (!config)
                return;
            loadConfig(prefix, LocalMediaConfigurationConstraints.CHECK_OPTIONS, this, config);
        }
    }
    LocalMediaConfigurationConstraints.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            bandwidth: numberCheck,
            constraints: objectCheck,
        },
    };

    class LocalMediaConfiguration {
        constructor(config, prefix) {
            this.audio = new LocalMediaConfigurationConstraints({ bandwidth: 32, constraints: {} });
            this.video = new LocalMediaConfigurationConstraints({
                bandwidth: 256,
                constraints: {
                    width: {
                        ideal: 1280,
                        max: 1280,
                        min: 320,
                    },
                    height: {
                        ideal: 720,
                        max: 720,
                        min: 180,
                    },
                    frameRate: 30,
                },
            });
            if (!config)
                return;
            loadConfig(prefix, LocalMediaConfiguration.CHECK_OPTIONS, this, config);
        }
    }
    LocalMediaConfiguration.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            audio: (config, prefix) => {
                const value = objectCheck(config);
                return value ? new LocalMediaConfigurationConstraints(value, arrayConcat(prefix, ["audio"])) : value;
            },
            video: (config, prefix) => {
                const value = objectCheck(config);
                return value ? new LocalMediaConfigurationConstraints(objectCheck(config), arrayConcat(prefix, ["video"])) : value;
            },
        },
    };

    class RemoteMediaConfiguration {
        constructor(config, prefix) {
            const localMediaConfiguration = new LocalMediaConfiguration();
            this.audio = { bandwidth: localMediaConfiguration.audio.bandwidth };
            this.video = { bandwidth: localMediaConfiguration.video.bandwidth };
            if (!config)
                return;
            loadConfig(prefix, RemoteMediaConfiguration.CHECK_OPTIONS, this, config);
        }
    }
    RemoteMediaConfiguration.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            audio: (options, prefix) => {
                for (let opt in options) {
                    if (opt != "bandwidth") {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, ["audio"]).join("."), options[opt], new Error(`${opt} is not valid remote media audio options`));
                    }
                }
                let value = options.bandwidth ? numberCheck(options.bandwidth) : null;
                return value ? options : value;
            },
            video: (options, prefix) => {
                for (let opt in options) {
                    if (opt != "bandwidth") {
                        throw ConfigurationError.newInstance(arrayConcat(prefix, ["video"]).join("."), options[opt], new Error(`${opt} is not valid remote media video options`));
                    }
                }
                let value = options.bandwidth ? numberCheck(options.bandwidth) : null;
                return value ? options : value;
            },
        },
    };

    class MediaConfiguration {
        constructor(config, prefix) {
            this.local = new LocalMediaConfiguration();
            this.remote = new RemoteMediaConfiguration();
            this.audioLevelUpdateIntervalInMS = 50;
            if (!config)
                return;
            loadConfig(prefix, MediaConfiguration.CHECK_OPTIONS, this, config);
        }
    }
    MediaConfiguration.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            local: (config, prefix) => {
                const value = objectCheck(config);
                return value ? new LocalMediaConfiguration(config, arrayConcat(prefix, ["local"])) : value;
            },
            remote: (config, prefix) => {
                const value = objectCheck(config);
                return value ? new RemoteMediaConfiguration(value, arrayConcat(prefix, ["remote"])) : value;
            },
            audioLevelUpdateIntervalInMS: numberCheck,
        },
    };

    class WebrtcConfig {
        constructor(options, prefix) {
            this.enabled = false;
            this.enabledOnChannel = [ChannelType.PhoneCall, ChannelType.Video, ChannelType.CallBack];
            this.trickleIcePolicy = TrickleIcePolicy.FullTrickle;
            this.iceGatherPolicy = [Candidate.Type.Host, Candidate.Type.Srflx, Candidate.Type.Relay];
            this.selfManagedDeviceActivity = false;
            this.customUseDeviceHistoryStore = null;
            this.audioDeviceInput = null;
            this.videoDeviceInput = null;
            this.audioDeviceOutput = null;
            this.audioDeviceSignalOutput = null;
            this.audioDeviceNotificationOutput = null;
            this.videoStreamInOffer = true;
            this.immediateRingback = false;
            this.connectionTimeout = 7200000;
            this.deadStreamTimeout = 7200000;
            this.mediaConfiguration = new MediaConfiguration();
            this.notifyAvailableMedia = false;
            this.notifyMediaFeature = true;
            this.mediaSignal = new WebRTCMediaSignal();
            if (!options)
                return;
            loadConfig(prefix, WebrtcConfig.CHECK_OPTIONS, this, options);
        }
    }
    WebrtcConfig.CHECK_OPTIONS = {
        mandatory: {},
        optional: {
            enabled: booleanCheck,
            selfManagedDeviceActivity: booleanCheck,
            customUseDeviceHistoryStore: (store) => {
                const value = objectCheck(store);
                if (value) {
                    if (!(functionCheck(value.get) && functionCheck(value.set))) {
                        return undefined;
                    }
                }
                return value;
            },
            enabledOnChannel: (channels) => {
                if (channels) {
                    if (Array.isArray(channels)) {
                        for (let i = 0; i < channels.length; i++) {
                            if (channelTypeToId(channels[i]) === null) {
                                return undefined;
                            }
                        }
                    }
                    else {
                        return undefined;
                    }
                }
                return channels;
            },
            iceServers: (iceServers) => (Array.isArray(iceServers) ? iceServers : undefined),
            trickleIcePolicy: (trickleIcePolicy) => {
                const value = stringCheck(trickleIcePolicy);
                switch (value.trim().toLowerCase()) {
                    case TrickleIcePolicy.FullTrickle.toLowerCase():
                        return TrickleIcePolicy.FullTrickle;
                    case TrickleIcePolicy.HalfTrickle.toLowerCase():
                        return TrickleIcePolicy.HalfTrickle;
                    case TrickleIcePolicy.NotSupported.toLowerCase():
                        return TrickleIcePolicy.NotSupported;
                    default:
                        return undefined;
                }
            },
            iceGatherPolicy: (iceGatherPolicy) => {
                const value = objectCheck(iceGatherPolicy);
                if (value && value.length) {
                    const mappedValue = value
                        .filter((item, pos, self) => self.indexOf(item) == pos)
                        .map((item) => item.trim().toLowerCase())
                        .filter((item) => item === Candidate.Type.Host || item === Candidate.Type.Srflx || item === Candidate.Type.Relay);
                    return mappedValue.length ? mappedValue : undefined;
                }
                else {
                    return undefined;
                }
            },
            audioDeviceInput: (device) => {
                const value = objectCheck(device);
                if (value && value.hasOwnProperty("deviceId")) {
                    return value;
                }
                else {
                    return undefined;
                }
            },
            videoDeviceInput: (device) => {
                const value = objectCheck(device);
                if (value && value.hasOwnProperty("deviceId")) {
                    return value;
                }
                else {
                    return undefined;
                }
            },
            audioDeviceOutput: (device) => {
                const value = objectCheck(device);
                if (value && value.hasOwnProperty("deviceId")) {
                    return value;
                }
                else {
                    return undefined;
                }
            },
            audioDeviceSignalOutput: (device) => {
                const value = objectCheck(device);
                if (value && value.hasOwnProperty("deviceId")) {
                    return value;
                }
                else {
                    return undefined;
                }
            },
            audioDeviceNotificationOutput: (device) => {
                const value = objectCheck(device);
                if (value && value.hasOwnProperty("deviceId")) {
                    return value;
                }
                else {
                    return undefined;
                }
            },
            videoStreamInOffer: booleanCheck,
            immediateRingback: booleanCheck,
            connectionTimeout: numberCheck,
            deadStreamTimeout: numberCheck,
            mediaConfiguration: (mediaConfiguration, prefix) => {
                const value = objectCheck(mediaConfiguration);
                return value ? new MediaConfiguration(value, arrayConcat(prefix, ["mediaConfiguration"])) : value;
            },
            notifyAvailableMedia: booleanCheck,
            notifyMediaFeature: booleanCheck,
            mediaSignal: (mediaSignal, prefix) => {
                const value = objectCheck(mediaSignal);
                return value ? new WebRTCMediaSignal(value, arrayConcat(prefix, ["mediaSignal"])) : value;
            },
        },
    };
    var TrickleIcePolicy;
    (function (TrickleIcePolicy) {
        TrickleIcePolicy["NotSupported"] = "NotSupported";
        TrickleIcePolicy["FullTrickle"] = "FullTrickle";
        TrickleIcePolicy["HalfTrickle"] = "HalfTrickle";
    })(TrickleIcePolicy || (TrickleIcePolicy = {}));

    class Call {
        constructor(_manager, _callConnectionState, _callId, _channelType, _isOffer, state, realState) {
            this._manager = _manager;
            this._callId = _callId;
            this._channelType = _channelType;
            this._isOffer = _isOffer;
            this._dialParams = null;
            this._signalingState = null;
            this._isRealState = false;
            this._callIsOnServer = new BehaviorSubject(false);
            this._localDescription = null;
            this._remoteDescription = null;
            this._remoteWebrtcfield = null;
            this._autoanswer = false;
            this._closedLocal = false;
            this._device = null;
            this._mediaOwnerId = "";
            this._connectionActionQueue = Promise.resolve();
            this._connectionActionQueueId = 0;
            this.controlMessageNotifier = new Subject();
            this._log = Log$1.of("webrtc:call", _manager.client);
            this._deviceIsApp = false;
            this._toneSignalEnabled = this.managedCall;
            this._connectionStates = [];
            this._localCandidateToSend = [];
            this._localDescriptionToSend = null;
            this._remoteMedia = new RemoteMedia();
            this._localCallMedia = new MediaParamImpl();
            this._remoteCallMedia = new MediaParamImpl();
            this._waitForAnswer = true;
            this._waitIceCandidateBeforeUpdate = false;
            this._remoteWebrtcfield = null;
            this._updateFields = new Subject();
            this._connectionState = new Subject();
            this._connectionStats = new MonitorStats(this);
            this._localAudioLevel = new MonitorAudioLevel("local", this);
            this._remoteAudioLevel = new MonitorAudioLevel("remote", this);
            if (_callConnectionState) {
                this._connectionState
                    .pipe(map((connectionState) => {
                    return {
                        callId: this._callId,
                        connectionState,
                    };
                }))
                    .subscribe((data) => _callConnectionState === null || _callConnectionState === void 0 ? void 0 : _callConnectionState.next(data));
            }
            this.setSignalingState(state, realState, false);
            this._controlMessageSubscription = this.controlMessageNotifier
                .pipe(tap((controlMessage) => {
                this._lastControlMessage = controlMessage;
                if (!this._device && controlMessage.device && controlMessage.deviceType === ExtenType.WEBRTC) {
                    this._device = controlMessage.device;
                }
            }), concatMap((controlMessage) => this._manager.manageControlMessage(controlMessage, true)))
                .subscribe();
            this._updateFields
                .pipe(debounceTime(10), throttle((action) => toPromise$1(this.updateWebRTCFields(action.sendUpdate)), { leading: false, trailing: true }), catchError((err) => {
                this._log.error("Error on updateWebRTCFields", err);
                return of(false);
            }))
                .subscribe();
            this._mediaEnabled = false;
        }
        canDoAction() {
            return this.managedCall && !this.callIsForApp && this.mediaOwnedByCurrentInstance;
        }
        get callIsForApp() {
            return this.channelType === ChannelType.PhoneCall && this._deviceIsApp;
        }
        get managedCall() {
            return this._manager.client.phoneManagerActive;
        }
        get mediaOwnedByCurrentInstance() {
            return this._mediaOwnerId === this._manager.client.instanceId;
        }
        set mediaOwnerId(mediaOwnerId) {
            this._mediaOwnerId = mediaOwnerId;
        }
        get manager() {
            return this._manager;
        }
        get layoutManager() {
            return this._layoutManager;
        }
        get remoteMedia() {
            return this._remoteMedia;
        }
        get remoteDescription() {
            var _a;
            return (_a = this._remoteDescription) !== null && _a !== void 0 ? _a : null;
        }
        get localDescription() {
            var _a;
            return (_a = this._localDescription) !== null && _a !== void 0 ? _a : null;
        }
        get channelType() {
            return this._channelType;
        }
        get dialParams() {
            return this._dialParams;
        }
        set dialParams(params) {
            this._dialParams = params;
            if (params && params.params.fromDevice) {
                this._deviceIsApp = params.isForApp();
                if (this.callIsForApp || !this.managedCall) {
                    this._toneSignalEnabled = false;
                }
            }
        }
        set mediaEnabled(mediaEnabled) {
            this._mediaEnabled = mediaEnabled;
        }
        set remoteWebrtcfield(webrtcfield) {
            this._remoteWebrtcfield = webrtcfield;
        }
        get callId() {
            return this._callId;
        }
        get deviceIsApp() {
            return this._deviceIsApp;
        }
        get remoteCallMedia() {
            return this._remoteCallMedia;
        }
        get localCallMedia() {
            return this._localCallMedia;
        }
        get localMedia() {
            return this._localMedia;
        }
        get connection() {
            return this._connection;
        }
        get waitForAnswer() {
            return this._waitForAnswer;
        }
        set waitForAnswer(waitForAnswer) {
            this._waitForAnswer = waitForAnswer;
        }
        get signalingState() {
            return this._signalingState;
        }
        get realState() {
            return this._isRealState;
        }
        get autoanswer() {
            return this._autoanswer;
        }
        get isOffer() {
            return this._isOffer;
        }
        get videoContainer() {
            var _a;
            return (_a = this.layoutManager) === null || _a === void 0 ? void 0 : _a.container;
        }
        set videoContainer(videoContainer) {
            var _a;
            if (this.mediaOwnedByCurrentInstance && videoContainer && (!this._layoutManager || videoContainer !== this._layoutManager.container.parentElement)) {
                (_a = this._layoutManager) === null || _a === void 0 ? void 0 : _a.dispose();
                this._layoutManager = new LayoutManager(videoContainer);
                this._layoutManager.localMedia = this.localMedia;
                this._layoutManager.remoteMedia = this.remoteMedia;
            }
        }
        get toneSignalEnabled() {
            return this._toneSignalEnabled;
        }
        set toneSignalEnabled(toneSignalEnabled) {
            this._toneSignalEnabled = toneSignalEnabled;
        }
        connectionActionQueue(action) {
            return __awaiter(this, void 0, void 0, function* () {
                const logPrefix = `connection queue - ${this.callId} - ${this._connectionActionQueueId++} -`;
                this._log.debug(`${logPrefix} request to execute action`);
                const result = this._connectionActionQueue
                    .then(() => __awaiter(this, void 0, void 0, function* () {
                    this._log.debug(`${logPrefix} execute action`);
                    return action();
                }))
                    .then((result) => {
                    this._log.debug(`${logPrefix} action ended`);
                    return result;
                });
                this._connectionActionQueue = result.catch((err) => {
                    this._log.debug(`${logPrefix} action error`, err);
                });
                return result;
            });
        }
        setSignalingState(state, realState, notifyState) {
            this._signalingState = state;
            if (realState === true || realState === false) {
                this._isRealState = realState;
                if (realState) {
                    this._callIsOnServer.next(true);
                }
            }
            if (this.managedCall && !this.callIsForApp && notifyState) {
                this.notifyConnectionState();
            }
        }
        markAsClosedLocal() {
            this._closedLocal = true;
        }
        isClosedLocal() {
            return this._closedLocal;
        }
        getLocalAudioLevel() {
            return this.canDoAction() ? this._localAudioLevel.start() : EMPTY;
        }
        getRemoteAudioLevel() {
            return this.canDoAction() ? this._remoteAudioLevel.start() : EMPTY;
        }
        getLocalVideoFrame() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.managedCall) {
                    throw new Error("Unmanaged call");
                }
                else if (this.callIsForApp) {
                    throw new Error("Device is App");
                }
                else {
                    if (this.mediaOwnedByCurrentInstance) {
                        try {
                            if (this._localMedia) {
                                return this._localMedia.grabVideoFrame();
                            }
                            else {
                                throw new Error("Local media is not available");
                            }
                        }
                        catch (e) {
                            throw new Error("Local media has not video");
                        }
                    }
                    else {
                        throw new Error("Media is not owned");
                    }
                }
            });
        }
        getRemoteVideoFrame() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.managedCall) {
                    throw new Error("Unmanaged call");
                }
                else if (this.callIsForApp) {
                    throw new Error("Device is App");
                }
                else {
                    if (this.mediaOwnedByCurrentInstance) {
                        try {
                            if (this._remoteMedia) {
                                return this._remoteMedia.grabVideoFrame();
                            }
                            else {
                                throw new Error("Remote media is not available");
                            }
                        }
                        catch (e) {
                            throw new Error("Remote media has not video");
                        }
                    }
                    else {
                        throw new Error("Media is not owned");
                    }
                }
            });
        }
        generateLocalWebRTCField() {
            let localSessionDescription = null;
            let localCandidate = null;
            if (this.canDoAction()) {
                const lastCandidate = this._connection && (this._connection.trickleIcePolicy === Connection.TrickleIcePolicy.NotSupported || this._connection.iceGatheringState === Connection.IceGatheringState.Complete);
                if (this._localDescriptionToSend) {
                    localSessionDescription = new WebRTCFieldSession(this._isOffer, this._localDescriptionToSend);
                }
                if (this._localCandidateToSend.length > 0 || lastCandidate) {
                    localCandidate = new WebRTCFieldCandidate([...this._localCandidateToSend], lastCandidate);
                }
            }
            return new WebRTCField(null, localSessionDescription, localCandidate, null, null);
        }
        localDescriptionIsNotified() {
            this._localDescriptionToSend = null;
        }
        initTlinkConnection() {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.managedCall || this.callIsForApp || !this._mediaEnabled || !this.mediaOwnedByCurrentInstance) {
                    return this;
                }
                else {
                    yield this.createTlinkConnection();
                    yield this.updateRemoteWebrtcFields();
                    if (this.sessionDescriptionChange(this._remoteDescription, (_b = (_a = this._connection) === null || _a === void 0 ? void 0 : _a.remoteDescription) !== null && _b !== void 0 ? _b : null)) {
                        yield this._connection.setRemoteDescription(this._remoteDescription);
                    }
                    yield this.createAndSetLocalDescription(false);
                    yield this.notifyConnectionState();
                    if (this._signalingState === CallState.CONNECTED && this._connectionStateConnected) {
                        this._connectionState.next(this._connectionStateConnected);
                        delete this._connectionStateConnected;
                    }
                    return this;
                }
            });
        }
        tryAutoanswer() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.managedCall && !this.callIsForApp && this._remoteWebrtcfield && this._remoteWebrtcfield.autoanswer && !this._autoanswer) {
                    let answerAfter = this._remoteWebrtcfield.autoanswer.after;
                    let mediaOfAnswer = this._remoteWebrtcfield.autoanswer.media;
                    if (answerAfter != null && mediaOfAnswer && Object.keys(mediaOfAnswer).length) {
                        let video = mediaOfAnswer.video;
                        this._autoanswer = true;
                        this._log.info(`Call ${this._callId} is in autoanswer, answer after ${answerAfter} with media ${Array.from(MediaParam.toCallMedia(mediaOfAnswer)).join("-")}`);
                        try {
                            let devices = yield toPromise$1(this._manager.device.status.pipe(timeout(100), first()));
                            video = video && !!devices.devices.videoInput && !!devices.devices.videoInput.length;
                        }
                        catch (e) {
                            this._log.error("error on getMediaDeviceStatus for autoanswer", e);
                        }
                        setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                            if (this._signalingState === CallState.NEW_INBOUND) {
                                this._log.info(`Call ${this._callId} autoanswer start`);
                                try {
                                    const answerResult = this._manager.methods.answer(this._channelType, this._callId, new MediaParamImpl(Object.assign(Object.assign({}, mediaOfAnswer), { video })));
                                    if (answerResult) {
                                        yield toPromise$1(answerResult.result);
                                    }
                                    this._log.info(`Call ${this._callId} - autoanswer end`);
                                }
                                catch (err) {
                                    this._log.info(`Call ${this._callId} - autoanswer failed`, err);
                                }
                            }
                            else {
                                this._log.info(`Call ${this._callId} - cannot start autoanswer, call state is ${this._signalingState}, expected NEW_INBOUND`);
                            }
                        }), 200 + (answerAfter < 0 ? 0 : answerAfter) * 1000);
                    }
                    else {
                        this._log.info(`Call ${this._callId} is in autoanswer but 'after' and 'media' is not set`);
                    }
                    delete this._remoteWebrtcfield.autoanswer;
                }
            });
        }
        sendDTMF(dtmf, playTone, dtmfDuration = this._manager.options.mediaSignal.dtmfDuration, dtmfInterToneGap = this._manager.options.mediaSignal.dtmfInterToneGap) {
            return __awaiter(this, void 0, void 0, function* () {
                if (playTone) {
                    yield this._manager.phoneSignal.playDTMF(this.callId, dtmf, dtmfDuration, dtmfInterToneGap);
                }
                if (this.connection) {
                    try {
                        this.connection.insertDTMF(dtmf, dtmfDuration, dtmfInterToneGap);
                        return true;
                    }
                    catch (err) {
                        this._log.debug("Call non support dtmf mode rfc2833, notify with action");
                        return false;
                    }
                }
                else {
                    return false;
                }
            });
        }
        isTrickleIcePolicyOneOf(...policyToCheck) {
            if (policyToCheck) {
                while (policyToCheck.length) {
                    if (this._manager.trickleIcePolicy === policyToCheck.pop()) {
                        return true;
                    }
                }
            }
            return false;
        }
        retriveCallMediaFromSessionDescription(sessionDescription) {
            const mediaParam = new MediaParamImpl();
            if (sessionDescription) {
                if (sessionDescription.hasAudio()) {
                    mediaParam.audio = true;
                }
                if (sessionDescription.hasVideo()) {
                    mediaParam.video = true;
                }
                if (sessionDescription.hasData()) {
                    mediaParam.data = true;
                }
            }
            return mediaParam;
        }
        signallingWebRTCFields(sendUpdate) {
            if (this.mediaOwnedByCurrentInstance) {
                this._updateFields.next({ sendUpdate });
            }
        }
        updateWebRTCFields(sendUpdate, requestTimeout) {
            if (this.canDoAction()) {
                if ((sendUpdate || !this._waitIceCandidateBeforeUpdate) && !this._waitForAnswer && (this._manager.trickleIcePolicy == Connection.TrickleIcePolicy.FullTrickle || this._signalingState === CallState.CONNECTED)) {
                    return this._callIsOnServer.asObservable().pipe(filter((onServer) => onServer), take(1), timeout(5000), map(() => this.generateLocalWebRTCField()), switchMap((webrtcField) => {
                        if (webrtcField.candidate || webrtcField.sessionDescription) {
                            const result = this._manager.methods.updateWebRTCFields(this._callId, this._localCallMedia, webrtcField, requestTimeout).result;
                            this._localDescriptionToSend = null;
                            this._localCandidateToSend.length = 0;
                            return result;
                        }
                        else {
                            return of(false);
                        }
                    }));
                }
                else {
                    return of(false);
                }
            }
            else {
                return of(false);
            }
        }
        sessionDescriptionChange(from, to) {
            var _a, _b, _c, _d;
            return from && to && ((_a = from.sdp.origin) === null || _a === void 0 ? void 0 : _a.sessionVersion) === ((_b = from.sdp.origin) === null || _b === void 0 ? void 0 : _b.sessionVersion) && ((_c = from.sdp.version) === null || _c === void 0 ? void 0 : _c.toString()) !== ((_d = to.sdp.version) === null || _d === void 0 ? void 0 : _d.toString());
        }
        createOfferOptions() {
            return __awaiter(this, void 0, void 0, function* () {
                return this._offerOptions;
            });
        }
        createAnswerOption() {
            return __awaiter(this, void 0, void 0, function* () {
                return this._answerOptions;
            });
        }
        createAndSetLocalDescription(force) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (this._mediaEnabled && this.mediaOwnedByCurrentInstance && this._connection && (force || !this._localDescription)) {
                    let createOffer = false;
                    let createAnswer = false;
                    if (this._isOffer && SessionDescription.Type.Offer === ((_a = this._remoteDescription) === null || _a === void 0 ? void 0 : _a.getType())) {
                        this._isOffer = false;
                    }
                    if (this._isOffer) {
                        createOffer = true;
                    }
                    else if (this._remoteDescription) {
                        createAnswer = true;
                    }
                    if (createOffer || createAnswer) {
                        let sessionDescription = null;
                        try {
                            sessionDescription = yield (createOffer ? this._connection.createOffer(yield this.createOfferOptions()) : this._connection.createAnswer(yield this.createAnswerOption()));
                        }
                        catch (e) {
                            this._log.warn(`error on ${createOffer ? "createOffer" : "createAnswer"}`, e);
                            throw e;
                        }
                        try {
                            return yield this._connection.setLocalDescription(sessionDescription);
                        }
                        catch (e) {
                            this._log.warn(`error on setLocalDescription`, e);
                            throw e;
                        }
                    }
                    else {
                        return this._localDescription;
                    }
                }
                else {
                    return this._localDescription;
                }
            });
        }
        setAudioOutputDevice() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.mediaOwnedByCurrentInstance) {
                    const audioOutputDevice = this._manager.device.audioOutput;
                    if (audioOutputDevice && audioOutputDevice != this._remoteMedia.audioOutput) {
                        try {
                            yield this._remoteMedia.setAudioOutput(audioOutputDevice);
                            this._log.debug(`Audio Output Device set to ${JSON.stringify(audioOutputDevice)}`);
                        }
                        catch (err) {
                            this._log.error("Error on changeAudioSinkOutput", err);
                        }
                    }
                }
            });
        }
        createTlinkConnection() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    if (!(this._connection === undefined || this._connection.state === Connection.State.Closed)) {
                        return this;
                    }
                    this._connection = new Connection({ iceServers: yield this._manager.getIceServers() }, this._localMedia, this._remoteMedia);
                    this._connection.id = this._callId;
                    const defaultTimeout = this._manager.options.connectionTimeout ? this._manager.options.connectionTimeout : this._connection.timeout;
                    const defaultDeadStreamTimeout = this._manager.options.deadStreamTimeout ? this._manager.options.deadStreamTimeout : this._connection.deadStreamTimeout;
                    const trickeIceDisabled = this.isTrickleIcePolicyOneOf(Connection.TrickleIcePolicy.NotSupported, Connection.TrickleIcePolicy.HalfTrickle);
                    this._connection.timeout = trickeIceDisabled ? 7200000 : defaultTimeout;
                    this._connection.deadStreamTimeout = trickeIceDisabled ? 7200000 : defaultDeadStreamTimeout;
                    this._connection.trickleIcePolicy = this._manager.trickleIcePolicy;
                    this._connection.iceGatherType.length = 0;
                    this._connection.iceGatherType.push.apply(this._connection.iceGatherType, this._manager.options.iceGatherPolicy);
                    this._connection.on("localCandidate", (candidate) => {
                        this._localCandidateToSend.push(candidate);
                        this.signallingWebRTCFields(false);
                    });
                    this._connection.on("localDescription", (sessionDescription) => {
                        const origin = sessionDescription.sdp.origin;
                        if (origin)
                            origin.username = `WebAPIclient-${LIB_VERSION$1}`;
                        this.manageBandwidth(false, sessionDescription);
                        this._localDescriptionToSend = sessionDescription;
                        this._localDescription = sessionDescription;
                        this.signallingWebRTCFields(false);
                    });
                    this._connection.on("remoteDescription", (sessionDescription) => {
                        this.manageBandwidth(true, sessionDescription);
                        this._remoteDescription = sessionDescription;
                    });
                    if (this.isTrickleIcePolicyOneOf(Connection.TrickleIcePolicy.FullTrickle, Connection.TrickleIcePolicy.HalfTrickle)) {
                        this._connection.on("gatheringStateChange", (state) => {
                            if (state === Connection.IceGatheringState.Complete) {
                                this.signallingWebRTCFields(true);
                            }
                        });
                    }
                    this._connection.on("sendDtmfToneChange", (tone) => {
                        this._log.info(`${this._callId} - Sender's DTMF tone is changing: ${tone}`);
                    });
                    this._connection.on("stateChange", (connectionState) => {
                        var _a, _b;
                        const connectionError = !!this._connection.error;
                        if (connectionError) {
                            this._log.info(`${this._callId} - Connection state is ${connectionState}.`, this._connection.error.getException());
                        }
                        else {
                            this._log.info(`${this._callId} - Connection state is ${connectionState}.`);
                        }
                        const connectionStateNotification = {
                            callId: this._callId,
                            state: connectionState,
                            error: connectionError ? this._connection.error : null,
                        };
                        switch (connectionState) {
                            case Connection.State.Connecting:
                                setTimeout(() => this.setAudioOutputDevice());
                                break;
                            case Connection.State.Connected:
                                this.startConnectionStats();
                                this._connection.timeout = defaultTimeout;
                                this._connection.deadStreamTimeout = defaultDeadStreamTimeout;
                                this.setAudioOutputDevice();
                                break;
                            case Connection.State.Closing:
                            case Connection.State.Failing:
                                (_a = this._layoutManager) === null || _a === void 0 ? void 0 : _a.dispose();
                                (_b = this._localMedia) === null || _b === void 0 ? void 0 : _b.dispose();
                                this._remoteMedia.dispose();
                                break;
                            case Connection.State.Failed:
                                this._manager.methods.cancel(this._callId, true, !(this instanceof CallChecker));
                                break;
                            case Connection.State.Closed:
                                this.stopConnectionStats();
                                break;
                        }
                        if (this._isRealState) {
                            if (connectionStateNotification.state === Connection.State.Connected && this._signalingState !== CallState.CONNECTED) {
                                this._connectionStateConnected = connectionState;
                            }
                            else {
                                this._connectionState.next(connectionState);
                                delete this._connectionStateConnected;
                            }
                        }
                        else {
                            this._connectionStates.push(connectionState);
                        }
                    });
                    yield this._connection.start();
                }
                return this;
            });
        }
        manageBandwidth(local, sessionDescription) {
            let audioData = { callMedia: CallMedia.audio, maxBandwidth: 0 };
            let videoData = { callMedia: CallMedia.video, maxBandwidth: 0 };
            let type = local ? "local" : "remote";
            try {
                audioData.maxBandwidth = this._manager.options.mediaConfiguration[type].audio.bandwidth;
            }
            catch (e) { }
            try {
                audioData.maxBandwidth = this._mediaConstraints[type].audio.bandwidth;
            }
            catch (e) { }
            try {
                videoData.maxBandwidth = this._manager.options.mediaConfiguration[type].video.bandwidth;
            }
            catch (e) { }
            try {
                videoData.maxBandwidth = this._mediaConstraints[type].video.bandwidth;
            }
            catch (e) { }
            [audioData, videoData].forEach((data) => {
                try {
                    let media = sessionDescription.extractMedia(data.callMedia.toString());
                    if (media && media.length && data.maxBandwidth) {
                        media.forEach((m) => {
                            let addAttribute = data.callMedia === CallMedia.video;
                            if (!addAttribute || data.callMedia === CallMedia.audio) {
                                addAttribute = !!m.rtp.find((rtpMapAttribute) => rtpMapAttribute.codec && "OPUS" === rtpMapAttribute.codec.toUpperCase());
                            }
                            if (addAttribute) {
                                m.bandwidth = [
                                    { type: "AS", limit: data.maxBandwidth },
                                    { type: "TIAS", limit: data.maxBandwidth * 1024 },
                                ];
                            }
                        });
                    }
                }
                catch (e) {
                    this._log.error("Could not add bandwidth constraints to SDP message", e);
                }
            });
        }
        notifyConnectionState() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction() && this._isRealState) {
                    if (this._connectionStates.length) {
                        this._connectionStates.forEach((state) => this._connectionState.next(state));
                        this._connectionStates.length = 0;
                    }
                    if (this._localDescriptionToSend || this._localCandidateToSend.length) {
                        this.signallingWebRTCFields(true);
                    }
                }
            });
        }
        updateRemoteWebrtcFields() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction() && this._mediaEnabled && this._connection && this._remoteWebrtcfield && ((this._remoteWebrtcfield.sessionDescription && this._remoteWebrtcfield.sessionDescription.session) || (this._remoteWebrtcfield.candidate && this._remoteWebrtcfield.candidate.candidate && this._remoteWebrtcfield.candidate.candidate.length))) {
                    const webrtcfields = Object.assign({}, this._remoteWebrtcfield);
                    const webrtcFieldsWithSdp = !!(webrtcfields.sessionDescription && webrtcfields.sessionDescription.session);
                    const remoteDescriptionHasChanged = webrtcFieldsWithSdp && (!this._remoteDescription || this.sessionDescriptionChange(this._remoteDescription, webrtcfields.sessionDescription.session));
                    this._remoteWebrtcfield = null;
                    try {
                        const receivedValidSdp = webrtcFieldsWithSdp && remoteDescriptionHasChanged;
                        if (this._connection.state !== Connection.State.Connected && receivedValidSdp) {
                            yield this._connection.setRemoteDescription(webrtcfields.sessionDescription.session);
                        }
                        yield this.createAndSetLocalDescription(false);
                        if (webrtcfields.candidate && webrtcfields.candidate.candidate && webrtcfields.candidate.candidate.length) {
                            yield this._connection.addRemoteCandidates(webrtcfields.candidate.candidate);
                        }
                    }
                    catch (e) {
                        this._log.error("error on updateWebrtcFields", e);
                    }
                }
            });
        }
        close() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.managedCall && !this.callIsForApp) {
                    yield this._manager.phoneSignal.stop(this._callId, false);
                }
                this.closeConnection();
                this._controlMessageSubscription.unsubscribe();
                this._updateFields.complete();
                this._callIsOnServer.complete();
                this._localAudioLevel.end();
                this._remoteAudioLevel.end();
                this._connectionState.complete();
            });
        }
        closeConnection() {
            var _a, _b;
            (_a = this._layoutManager) === null || _a === void 0 ? void 0 : _a.dispose();
            if (this._connection) {
                this._connection.dispose();
                this._connection = undefined;
                this._connectionStates.length = 0;
            }
            (_b = this.localMedia) === null || _b === void 0 ? void 0 : _b.dispose();
            this.remoteMedia.dispose();
        }
        toggleAudioMute(mute, notifyMediaFeature = true, requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    let result = this.toggleMediaTrackMuted(this._localMedia, true, mute);
                    if (this._localMedia) {
                        if (notifyMediaFeature) {
                            try {
                                if (!(yield this.notifyCallMediaState({ audio: true }, requestTimeout))) {
                                    result = yield this.toggleAudioMute(!mute, false);
                                }
                            }
                            catch (err) {
                                result = yield this.toggleAudioMute(!mute, false);
                                throw err;
                            }
                        }
                    }
                    return result;
                }
                else {
                    return false;
                }
            });
        }
        toggleVideoMute(mute, notifyMediaFeature = true, requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    let result = this.toggleMediaTrackMuted(this._localMedia, false, mute);
                    if (this._localMedia) {
                        if (notifyMediaFeature) {
                            try {
                                if (!(yield this.notifyCallMediaState(new MediaParamImpl({ video: true }), requestTimeout))) {
                                    result = yield this.toggleVideoMute(!mute, false);
                                }
                            }
                            catch (err) {
                                result = yield this.toggleVideoMute(!mute, false);
                                throw err;
                            }
                        }
                    }
                    return result;
                }
                else {
                    return false;
                }
            });
        }
        toggleRemoteAudioMute(mute) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    const result = this.toggleMediaTrackMuted(this._remoteMedia, true, mute);
                    if (this._remoteMedia && this._remoteMedia.stream) {
                        this.publishLastControlMessage();
                    }
                    return result;
                }
                else {
                    return false;
                }
            });
        }
        toggleRemoteVideoMute(mute) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    const result = this.toggleMediaTrackMuted(this._remoteMedia, false, mute);
                    if (this._remoteMedia && this._remoteMedia.stream) {
                        this.publishLastControlMessage();
                    }
                    return result;
                }
                else {
                    return false;
                }
            });
        }
        isAudioEnabled() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    return this._remoteDescription ? !!this.retriveCallMediaFromSessionDescription(this._remoteDescription).audio : true;
                }
                else {
                    return false;
                }
            });
        }
        isVideoEnabled() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    return this._remoteDescription ? !!this.retriveCallMediaFromSessionDescription(this._remoteDescription).video : true;
                }
                else {
                    return false;
                }
            });
        }
        startAudio() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    if (yield this.isAudioEnabled()) {
                        if (this._localMedia) {
                            if (!this._localCallMedia.audio) {
                                const newMedia = new MediaParamImpl(Object.assign({}, this._localCallMedia));
                                newMedia.audio = true;
                                yield this.setLocalMedia(newMedia, this._mediaConstraints);
                                yield this.toggleAudioMute(false, false);
                            }
                            return true;
                        }
                        return false;
                    }
                    else {
                        throw new Error("Unable to start audio, remote peer is not supporting");
                    }
                }
                else {
                    return false;
                }
            });
        }
        stopAudio() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    yield this.toggleAudioMute(true, false);
                    if (this._localMedia) {
                        if (this._localCallMedia.audio) {
                            const newMedia = new MediaParamImpl(Object.assign({}, this._localCallMedia));
                            newMedia.audio = false;
                            yield this.setLocalMedia(newMedia, this._mediaConstraints);
                        }
                        return true;
                    }
                    return false;
                }
                else {
                    return false;
                }
            });
        }
        get audioLinkStatus() {
            if (this.canDoAction()) {
                return this._localMedia && this._localMedia.stream ? (this._localMedia.audioLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
            }
            else {
                return null;
            }
        }
        get audioRemoteLinkStatus() {
            if (this.canDoAction()) {
                return this._remoteMedia && this._remoteMedia.stream ? (this._remoteMedia.audioLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
            }
            else {
                return null;
            }
        }
        startVideo(mediaConstraints, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    if (yield this.isVideoEnabled()) {
                        if (this._localMedia && !this._localCallMedia.video) {
                            if (videoContainer) {
                                this.videoContainer = videoContainer;
                            }
                            if (mediaConstraints && this._mediaConstraints) {
                                this._mediaConstraints.local.video = new LocalMediaConfigurationConstraints(mediaConstraints);
                            }
                            const newMedia = new MediaParamImpl(Object.assign({}, this._localCallMedia));
                            newMedia.video = true;
                            yield this.setLocalMedia(newMedia, this._mediaConstraints);
                            yield this.toggleVideoMute(false, false);
                            return this.notifyVideoStartOrStop();
                        }
                        else {
                            return false;
                        }
                    }
                    else {
                        throw new Error("Unable to start video, remote peer is not supporting");
                    }
                }
                else {
                    return false;
                }
            });
        }
        stopVideo() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    yield this.toggleVideoMute(true, false);
                    if (this._localMedia && this._localCallMedia.video) {
                        const newMedia = new MediaParamImpl(Object.assign({}, this._localCallMedia));
                        newMedia.video = false;
                        yield this.setLocalMedia(newMedia, this._mediaConstraints);
                        return this.notifyVideoStartOrStop();
                    }
                    else {
                        return false;
                    }
                }
                else {
                    return false;
                }
            });
        }
        get videoLinkStatus() {
            if (this.canDoAction()) {
                return this._localMedia && this._localMedia.stream ? (this._localMedia.videoLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
            }
            else {
                return null;
            }
        }
        get videoRemoteLinkStatus() {
            if (this.canDoAction()) {
                return this._remoteMedia && this._remoteMedia.stream ? (this._remoteMedia.videoLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
            }
            else {
                return null;
            }
        }
        toggleMediaTrackMuted(mediaTrack, audio, mute) {
            if (mediaTrack) {
                if (typeof mute === "boolean") {
                    if (mute !== (audio ? mediaTrack.audioMuted : mediaTrack.videoMuted)) {
                        if (audio) {
                            mediaTrack.audioMuted = mute;
                        }
                        else {
                            mediaTrack.videoMuted = mute;
                        }
                    }
                }
                else {
                    if (audio) {
                        mediaTrack.audioMuted = !mediaTrack.audioMuted;
                    }
                    else {
                        mediaTrack.videoMuted = !mediaTrack.videoMuted;
                    }
                }
                return audio ? mediaTrack.audioMuted : mediaTrack.videoMuted;
            }
            else {
                return false;
            }
        }
        stopConnectionStats() {
            this._connectionStats.stop();
            this._localAudioLevel.stop();
            this._remoteAudioLevel.stop();
        }
        startConnectionStats() {
            if (this.canDoAction()) {
                this._connectionStats.active = true;
            }
        }
        getConnectionStats() {
            return this._connectionStats.start();
        }
        changeLocalMedia(media, mediaConfiguration) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    const mediaConstraints = yield this.mediaConfigurationToLocalMediaConstraints(mediaConfiguration);
                    yield ((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.changeConstraints(mediaConstraints));
                    let audioEnable = !!this._localCallMedia.audio;
                    let desktopEnable = !!this._localCallMedia.desktop;
                    !!this._localCallMedia.video;
                    let audioInput;
                    if (audioEnable && this._manager.device.audioInput) {
                        audioInput = this._manager.device.audioInput;
                    }
                    let videoInput;
                    if (mediaConstraints.video && !desktopEnable && typeof this._manager.device.videoInput !== "boolean" && this._manager.device.videoInput) {
                        videoInput = this._manager.device.videoInput;
                    }
                    if (audioInput || videoInput) {
                        yield ((_b = this._localMedia) === null || _b === void 0 ? void 0 : _b.changeAudioVideoInput(audioInput, videoInput));
                    }
                    return true;
                }
                else {
                    return false;
                }
            });
        }
        mediaConfigurationToLocalMediaConstraints(mediaConfiguration) {
            return __awaiter(this, void 0, void 0, function* () {
                this._mediaConstraints = new MediaConfiguration(mediaConfiguration);
                const audioEnable = !!this._localCallMedia.audio;
                const videoEnable = !!this._localCallMedia.video;
                const desktopEnable = !!this._localCallMedia.desktop;
                let audioConfig = audioEnable;
                let videoConfig = videoEnable || desktopEnable ? {} : false;
                if (!!(this._mediaConstraints || null) && this._mediaConstraints.local) {
                    const constraints = this._mediaConstraints.local;
                    if (audioConfig && constraints.audio && constraints.audio.constraints) {
                        if (Object.keys(constraints.audio.constraints).length > 0) {
                            audioConfig = Object.assign({}, constraints.audio.constraints);
                        }
                    }
                    if (videoConfig && constraints.video && constraints.video.constraints) {
                        if (Object.keys(constraints.video.constraints).length > 0) {
                            videoConfig = Object.assign({}, constraints.video.constraints);
                        }
                    }
                }
                if (videoConfig) {
                    videoConfig.width = desktopEnable ? window.screen.width : videoConfig.width;
                    videoConfig.height = desktopEnable ? window.screen.height : videoConfig.height;
                    videoConfig.frameRate = desktopEnable ? 3 : videoConfig.frameRate;
                }
                if (audioConfig) {
                    this._log.info(`local audio is enabled - constraints ${JSON.stringify(audioConfig, MapOrSet_toJSON)}`);
                }
                if (!!videoConfig && !desktopEnable) {
                    this._log.info(`local video is enabled - constraints ${JSON.stringify(videoConfig, MapOrSet_toJSON)}`);
                }
                if (videoConfig && !(yield this._manager.device.getMediaDevice(false, false, true)).videoInputEnabled) {
                    videoConfig = false;
                }
                return { audio: audioConfig, video: videoConfig };
            });
        }
        setLocalMedia(media, mediaConfiguration) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    if (!this._mediaEnabled) {
                        return this;
                    }
                    const mediaImpl = new MediaParamImpl(media);
                    if (this._localMedia) {
                        let mdiff = 0;
                        for (const m in this.localCallMedia) {
                            if (!mediaImpl[m]) {
                                mdiff++;
                            }
                        }
                        if (mdiff === 0) {
                            for (const m in mediaImpl) {
                                if (!this._localCallMedia[m]) {
                                    mdiff++;
                                }
                            }
                        }
                        if (mdiff > 0) {
                            yield this.changeLocalMedia(mediaImpl, mediaConfiguration);
                        }
                    }
                    else {
                        this._localCallMedia = mediaImpl;
                        if (this.mediaOwnedByCurrentInstance) {
                            if (!this._localCallMedia._hasMedia()) {
                                throw new Error("Parameter error, audio or video or desktop must be set");
                            }
                            let audioEnable = !!this._localCallMedia.audio;
                            let desktopEnable = !!this._localCallMedia.desktop;
                            const mediaConstraints = yield this.mediaConfigurationToLocalMediaConstraints(mediaConfiguration);
                            this._localMedia = new LocalMedia(mediaConstraints);
                            this._localAudioLevel._activate();
                            let audioInput;
                            if (audioEnable && this._manager.device.audioInput) {
                                audioInput = this._manager.device.audioInput;
                            }
                            let videoInput;
                            if (mediaConstraints.video && !desktopEnable && typeof this._manager.device.videoInput !== "boolean" && this._manager.device.videoInput) {
                                videoInput = this._manager.device.videoInput;
                            }
                            if (audioInput || videoInput) {
                                yield ((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.changeAudioVideoInput(audioInput, videoInput));
                            }
                            if (this._layoutManager) {
                                this._layoutManager.localMedia = this._localMedia;
                            }
                        }
                    }
                }
                return this;
            });
        }
        notifyLastControlMessage(cleanMedia) {
            var _a;
            const controlMessage = Object.assign({}, this._lastControlMessage);
            controlMessage.device = (_a = this._device) !== null && _a !== void 0 ? _a : undefined;
            controlMessage._isFromServer = false;
            if (cleanMedia) {
                if (controlMessage.local_media_feature) {
                    controlMessage.local_media_feature = undefined;
                }
                if (controlMessage.media) {
                    controlMessage.media = undefined;
                }
                controlMessage.media_feature = undefined;
                controlMessage.remote_media_status = null;
            }
            setTimeout(() => this._manager.publishControlMessage(controlMessage));
        }
        notifyVideoStartOrStop() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.canDoAction()) {
                    if (this.channelType === ChannelType.Video) {
                        this.notifyLastControlMessage(true);
                        return true;
                    }
                    else {
                        if (this._localCallMedia.video) {
                            return toPromise$1(this._manager.methods.startVideoOnCall(this._callId).result);
                        }
                        else {
                            return toPromise$1(this._manager.methods.stopVideoOnCall(this._callId).result);
                        }
                    }
                }
                else {
                    return false;
                }
            });
        }
        notifyCallMediaState(media, requestTimeout) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                const mediaImpl = new MediaParamImpl(media);
                if (this.canDoAction() && mediaImpl._hasMedia()) {
                    if (this._manager.options.notifyMediaFeature) {
                        if (this.channelType === ChannelType.Video) {
                            this.notifyLastControlMessage(true);
                            return true;
                        }
                        else {
                            let mediaMapMuted = new Map();
                            for (const m in mediaImpl) {
                                if (m && this._localCallMedia[m]) {
                                    let muted = null;
                                    switch (m) {
                                        case CallMedia.audio:
                                            muted = (_a = this.localMedia) === null || _a === void 0 ? void 0 : _a.audioMuted;
                                            break;
                                        case CallMedia.video:
                                            muted = (_b = this.localMedia) === null || _b === void 0 ? void 0 : _b.videoMuted;
                                            break;
                                    }
                                    if (muted !== null) {
                                        let mediaParam = mediaMapMuted.get(muted);
                                        if (!mediaParam) {
                                            mediaParam = {};
                                            mediaMapMuted.set(muted, mediaParam);
                                        }
                                        mediaParam[m] = true;
                                    }
                                }
                            }
                            const response = yield Promise.all([
                                (() => __awaiter(this, void 0, void 0, function* () {
                                    const media = mediaMapMuted.get(true);
                                    return media ? toPromise$1(this._manager.methods.notifyMute(this._callId, media, undefined, requestTimeout).result) : true;
                                }))(),
                                (() => __awaiter(this, void 0, void 0, function* () {
                                    const media = mediaMapMuted.get(false);
                                    return media ? toPromise$1(this._manager.methods.notifyUnmute(this._callId, media, undefined, requestTimeout).result) : true;
                                }))(),
                            ]);
                            return response[0] && response[1];
                        }
                    }
                    else {
                        return true;
                    }
                }
                return false;
            });
        }
        publishLastControlMessage() {
            const controlMessage = Object.assign({}, this._lastControlMessage);
            controlMessage._isFromServer = false;
            this._manager.publishControlMessage(controlMessage);
        }
    }
    class MonitorAudioLevel {
        constructor(id, call) {
            this.id = id;
            this.call = call;
            this._audioLevelPublisher = null;
            this._audioLevelSubscription = Subscription.EMPTY;
            this._audioLevelObservable = null;
            this._log = Log$1.of("webrtc:call:audioLevel", call.manager.client);
        }
        start() {
            if (!this._audioLevelObservable) {
                this._log.info(`start ${this.id}`);
                this._audioLevelObservable = new Observable((publisher) => {
                    if (this._audioLevelObservable) {
                        this._audioLevelPublisher = publisher;
                        this._activate();
                    }
                    else {
                        publisher.error(new Error(`${this.id} monitorAudioLevel is ended`));
                    }
                    return () => this.stop();
                }).pipe(share());
            }
            return this._audioLevelObservable;
        }
        stop() {
            if (this._audioLevelSubscription !== Subscription.EMPTY)
                this._log.info(`stop ${this.id}`);
            this._audioLevelSubscription.unsubscribe();
            this._audioLevelSubscription = Subscription.EMPTY;
        }
        end() {
            if (this._audioLevelObservable)
                this._log.info(`end ${this.id}`);
            this.stop();
            if (this._audioLevelPublisher) {
                this._audioLevelPublisher.complete();
                this._audioLevelPublisher = null;
            }
            this._audioLevelObservable = null;
        }
        _activate() {
            this.stop();
            const media = this.id === "local" ? this.call.localMedia : this.call.remoteMedia;
            if (media && this._audioLevelPublisher) {
                this._log.info(`activate ${this.id}`);
                this._audioLevelSubscription = media.audioLevel.subscribe((value) => this._audioLevelPublisher.next(value), (err) => this._audioLevelPublisher.error(err));
            }
        }
    }
    class MonitorStats {
        constructor(call) {
            this.call = call;
            this._stats = null;
            this._statsPublisher = null;
            this._statsSubscription = Subscription.EMPTY;
            this._active = false;
            this._log = Log$1.of("webrtc:call:stats", call.manager.client);
        }
        set active(active) {
            this._active = active;
            this.activate();
        }
        start() {
            if (!this._stats) {
                this._log.info("start");
                this._stats = new Observable((publisher) => {
                    if (this._stats) {
                        this._statsPublisher = publisher;
                        this.activate();
                    }
                    else {
                        publisher.error(new Error(`monitorMediaStreamStats is ended`));
                    }
                    return () => this.stop();
                }).pipe(share());
            }
            return this._stats;
        }
        stop() {
            if (this._statsSubscription !== Subscription.EMPTY)
                this._log.info("stop");
            this._statsSubscription.unsubscribe();
            this._statsSubscription = Subscription.EMPTY;
        }
        end() {
            if (this._stats)
                this._log.info("end");
            this.stop();
            if (this._statsPublisher) {
                this._statsPublisher.complete();
                this._statsPublisher = null;
            }
            this._stats = null;
        }
        activate() {
            this.stop();
            if (this._active && this._statsPublisher && this._statsSubscription === Subscription.EMPTY) {
                this._log.info("activate");
                this._statsSubscription = interval(1000).subscribe(() => __awaiter(this, void 0, void 0, function* () {
                    var _a;
                    let connectionStats;
                    try {
                        connectionStats = yield ((_a = this.call.connection) === null || _a === void 0 ? void 0 : _a.getStats());
                    }
                    catch (err) {
                        this._log.error("Error on retrive connection stats", err);
                    }
                    if (connectionStats) {
                        try {
                            this._statsPublisher.next(connectionStats);
                        }
                        catch (e) {
                            this._log.error("Error on handle connection stats", e);
                        }
                    }
                }));
            }
        }
    }
    class CallChecker extends Call {
        constructor(manager, connectionState, callId, channelType, isOffer, state, realState) {
            super(manager, connectionState, callId, channelType, isOffer, state, realState);
            this._toneSignalEnabled = false;
        }
    }
    class CallOmnidesk extends Call {
        constructor(manager, callId, state) {
            super(manager, null, callId, ChannelType.Omnidesk, false, state, true);
        }
    }

    class WebRTCMethodsExecutor extends MethodExecutor {
        constructor(
        client) {
            super(client);
            this.client = client;
        }
        echoTestConnectivityCheck(media, mediaConfiguration, videoContainer) {
            return this.executeRequestPromise(MethodFactory.echoTestConnectivityCheck(media, mediaConfiguration, videoContainer));
        }
        stopEchoTestConnectivityCheck(id) {
            return this.executeRequestPromise(MethodFactory.cancel(id, true, false));
        }
        setWebRTCAvailableMedia(media, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.setWebRTCAvailableMedia(media), requestTimeout);
        }
        startVideoEchoTest(audio, video, videoContainer, mediaConfiguration, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.startVideoEchoTest(audio, video, videoContainer, mediaConfiguration), requestTimeout);
        }
        dial(dialParams, videoContainer, mediaConstraints, userInteractionAction, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.dial(dialParams, videoContainer, mediaConstraints, userInteractionAction), requestTimeout);
        }
        answer(channelId, callId, media, customFields, videoContainer, mediaConfiguration, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.answer(channelId, callId, media, customFields, videoContainer, mediaConfiguration), requestTimeout);
        }
        hold(callId, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.hold(callId), requestTimeout);
        }
        unhold(callId, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.unhold(callId), requestTimeout);
        }
        attendedTransfer(callId, heldCallId, media, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.attendedTransfer(callId, heldCallId, media, fields), requestTimeout);
        }
        blindTransfer(callId, accessCode, number, data, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.blindTransfer(callId, accessCode, number, data), requestTimeout);
        }
        sendDTMF(callId, dtmf, playTone = true, dtmfDuration, dtmfInterToneGap, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.sendDTMF(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap), requestTimeout);
        }
        forceCancel(callId, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.forceCancel(callId), requestTimeout);
        }
        cancel(callId, storeAction, execWebapiRequest, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.cancel(callId, storeAction, execWebapiRequest), requestTimeout);
        }
        createUserInteraction(createUserInteraction, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.createUserInteraction(createUserInteraction), requestTimeout);
        }
        removeCallFromUserInteraction(callId, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.removeCallFromUserInteraction(callId), requestTimeout);
        }
        updateWebRTCFields(callId, media, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.updateWebRTCFields(callId, media, fields), requestTimeout);
        }
        getWebrtcConfiguration(requestTimeout) {
            return this.executeRequestPromise(MethodFactory.getWebrtcConfiguration(), requestTimeout);
        }
        mute(callId, media, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.mute(callId, media), requestTimeout);
        }
        unmute(callId, media, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.unmute(callId, media), requestTimeout);
        }
        notifyMute(callId, media, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.notifyMute(callId, media, fields), requestTimeout);
        }
        notifyUnmute(callId, media, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.notifyUnmute(callId, media, fields), requestTimeout);
        }
        startVideoOnCall(callId, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.startVideoOnCall(callId, fields), requestTimeout);
        }
        stopVideoOnCall(callId, fields, requestTimeout) {
            return this.executeRequestPromise(MethodFactory.stopVideoOnCall(callId, fields), requestTimeout);
        }
    }

    class MediaDeviceNotification {
        constructor(devices, status) {
            this.devices = devices;
            this.status = status;
        }
    }
    class MediaDeviceStatus {
        constructor(lastMediaDevice, currentMediaDevice) {
            this.added = new MediaDevice();
            this.deleted = new MediaDevice();
            this.none = new MediaDevice();
            [
                [lastMediaDevice.audioInput, currentMediaDevice.audioInput],
                [lastMediaDevice.audioOutput, currentMediaDevice.audioOutput],
                [lastMediaDevice.videoInput, currentMediaDevice.videoInput],
            ].forEach(([prev, curr]) => {
                const previousDevices = [...prev];
                curr.forEach((newDevice) => {
                    const previousDeviceIndex = previousDevices.findIndex((previousDevice) => previousDevice.deviceId === newDevice.deviceId);
                    if (previousDeviceIndex > -1) {
                        previousDevices.splice(previousDeviceIndex, 1);
                        this.none.addDevice(newDevice);
                    }
                    else {
                        this.added.addDevice(newDevice);
                    }
                });
                previousDevices.forEach((previousDevice) => {
                    this.deleted.addDevice(previousDevice);
                });
            });
        }
    }
    const DEVICE_CHANGE = DeviceManager.deviceChange.pipe(filter((mediaDevice) => !!mediaDevice), pairwise(),
    map(([lastMediaDevice, currentMediaDevice]) => new MediaDeviceNotification(currentMediaDevice, new MediaDeviceStatus(lastMediaDevice, currentMediaDevice))));
    const MEDIA_AVAILABLE = DeviceManager.mediaAvailable;
    class MediaDeviceTest {
        constructor(localMedia, videoContainer) {
            this.localMedia = localMedia;
            this.localMedia.sink.audioSink.muted = false;
            this.videoContainer = videoContainer;
        }
        set videoContainer(videoContainer) {
            if (this.layoutManager) {
                this.layoutManager.dispose();
                this.layoutManager = undefined;
            }
            if (videoContainer) {
                this.layoutManager = new LayoutManager(videoContainer);
                this.layoutManager.localMedia = this.localMedia;
            }
        }
        get audioLevel() {
            return this.localMedia.audioLevel;
        }
        start() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.localMedia.started) {
                    yield this.localMedia.start();
                }
            });
        }
        stop() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.localMedia.started) {
                    yield this.localMedia.stop();
                }
            });
        }
        changeAudioVideoInput(audioInput, videoInput) {
            return __awaiter(this, void 0, void 0, function* () {
                if (videoInput !== false && !this.layoutManager) {
                    throw new Error("videoContainer must be set to test videoInput");
                }
                return this.localMedia.changeAudioVideoInput(audioInput, videoInput);
            });
        }
        changeAudioOutput(audioOutput) {
            return __awaiter(this, void 0, void 0, function* () {
                this.localMedia.changeAudioOutput(audioOutput);
            });
        }
    }
    class WebrtDeviceManager {
        constructor(
        manager) {
            this.manager = manager;
            this._selfManagedDeviceActivity = new Subject();
            this._addedDeviceOnSelfManagedMode = new Subject();
            this._execNotifyAvailableMedia = new Subject();
            this._mediaNotified = new MediaParamImpl();
            this._loaded = false;
            this._deviceSelected = {
                audioInput: null,
                audioOutput: null,
                videoInput: null,
                audioSignalOutput: null,
                audioNotificationOutput: null,
            };
            this._log = Log$1.of("webrtc:device", manager.client);
            this._useDeviceHistory = new UseDeviceHistoryManager(this.manager.options.customUseDeviceHistoryStore ? this.manager.options.customUseDeviceHistoryStore : new UseDeviceHistoryStore());
            this.status
                .pipe(tap((deviceNotification) => this._log.info("Media device change", deviceNotification)), concatMap((deviceNotification) => __awaiter(this, void 0, void 0, function* () {
                try {
                    yield this._useDeviceHistory.init();
                }
                catch (err) {
                    this._log.error("error on init useDeviceHistory", err);
                }
                return deviceNotification;
            })), concatMap((deviceNotification) => {
                if (this.manager.options.selfManagedDeviceActivity) {
                    return this.selfManagedDeviceChangeHandler(deviceNotification);
                }
                else {
                    return Promise.resolve(deviceNotification);
                }
            }), catchError((err, obs) => {
                this._log.error("error on selfManagedDeviceChangeHandler", err);
                return obs;
            }), filter((deviceNotification) => deviceNotification.devices.retrivedWithUserAuthorization), concatMap((deviceNotification) => this.checkSelectedMediaDevice(deviceNotification.devices)), catchError((err, obs) => {
                this._log.error("error on checkSelectedMediaDevice", err);
                return obs;
            }))
                .subscribe();
            combineLatest([this.manager.client.loginProfileLoggedOnNewSession, MEDIA_AVAILABLE, this._execNotifyAvailableMedia.pipe(throttleTime(200, asyncScheduler, { leading: false, trailing: true }))])
                .pipe(filter(([loginProfile, mediaInputAvailable]) => this.manager.enable && loginProfile && !!mediaInputAvailable), map(([loginProfile, mediaInputAvailable]) => {
                return new MediaParamImpl({ audio: mediaInputAvailable.audio, video: mediaInputAvailable.video && (typeof this.videoInput === "boolean" ? this.videoInput : true), desktop: true, data: false });
            }), filter((mediaNotified) => this._mediaNotified.audio !== mediaNotified.audio || this._mediaNotified.video !== mediaNotified.video || this._mediaNotified.desktop !== mediaNotified.desktop || this._mediaNotified.data !== mediaNotified.data), concatMap((mediaNotified) => {
                this._mediaNotified = mediaNotified;
                if (this.manager.options.notifyAvailableMedia) {
                    this._log.debug("Notify available media");
                    return this.manager.methods.setWebRTCAvailableMedia(this._mediaNotified).result.pipe(tap((response) => {
                        if (response) {
                            this._log.debug("Available media notified");
                        }
                        else {
                            this._log.error("Available media notified but have unexpected response");
                        }
                    }), catchError((err) => {
                        this._log.error("Error on notify available media", err);
                        return of(false);
                    }));
                }
                else {
                    this._log.info("options.notifyAvailableMedia is not enable, no call to setWebRTCAvailableMedia");
                    return of(true);
                }
            }))
                .subscribe();
        }
        static get deviceIdToIgnore() {
            return DeviceManager.deviceIdToIgnore;
        }
        get audioInput() {
            return this._deviceSelected.audioInput;
        }
        get videoInput() {
            return this._deviceSelected.videoInput;
        }
        get audioOutput() {
            return this._deviceSelected.audioOutput;
        }
        get audioSignalOutput() {
            return this._deviceSelected.audioSignalOutput;
        }
        get audioNotificationOutput() {
            return this._deviceSelected.audioNotificationOutput;
        }
        get status() {
            return DEVICE_CHANGE;
        }
        get selfManagedDeviceActivity() {
            return this._selfManagedDeviceActivity.asObservable();
        }
        get addedDeviceOnSelfManagedMode() {
            return this._addedDeviceOnSelfManagedMode.asObservable();
        }
        get callMediaNotified() {
            return this._mediaNotified;
        }
        init() {
            var _a, _b, _c, _d, _e;
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._loaded && this.manager.enable) {
                    this._loaded = true;
                    try {
                        yield this._useDeviceHistory.init();
                    }
                    catch (err) {
                        this._log.error("error on init useDeviceHistory", err);
                    }
                    yield this.useDeviceInternal(new UseDeviceManager({
                        audioInput: this.manager.options.audioDeviceInput || this._deviceSelected.audioInput || ((_a = this._useDeviceHistory.audioInputUsed) === null || _a === void 0 ? void 0 : _a.device) || null,
                        videoInput: this.manager.options.videoDeviceInput || this._deviceSelected.videoInput || ((_b = this._useDeviceHistory.videoInputUsed) === null || _b === void 0 ? void 0 : _b.device),
                        audioOutput: this.manager.options.audioDeviceOutput || this._deviceSelected.audioOutput || ((_c = this._useDeviceHistory.audioOutputUsed) === null || _c === void 0 ? void 0 : _c.device) || null,
                        audioSignalOutput: this.manager.options.audioDeviceSignalOutput || this._deviceSelected.audioSignalOutput || ((_d = this._useDeviceHistory.audioSignalOutputUsed) === null || _d === void 0 ? void 0 : _d.device) || null,
                        audioNotificationOutput: this.manager.options.audioDeviceNotificationOutput || this._deviceSelected.audioNotificationOutput || ((_e = this._useDeviceHistory.audioNotificationOutputUsed) === null || _e === void 0 ? void 0 : _e.device) || null,
                    }), true, false);
                    try {
                        yield DeviceManager.getMediaDevice(false, true, true);
                    }
                    catch (e) {
                        this._log.error("Error on retrive media devices", e);
                    }
                    if (!Object.keys(this._mediaNotified).length) {
                        this.notifyAvailableMedia();
                    }
                }
            });
        }
        notifyAvailableMedia() {
            this._execNotifyAvailableMedia.next();
            return true;
        }
        useDevice(device) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.useDeviceInternal(new UseDeviceManager(device), true, true);
            });
        }
        setMediaDevice(audioInput, videoInput, audioOutput, audioSignalOutput, audioNotificationOutput) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.useDevice({
                    audioInput,
                    videoInput,
                    audioOutput,
                    audioSignalOutput,
                    audioNotificationOutput,
                });
            });
        }
        useDeviceInternal(useDeviceRequest, setByUser, saveOnStorage) {
            var _a, _b, _c, _d, _e;
            return __awaiter(this, void 0, void 0, function* () {
                const useDevice = useDeviceRequest.cloneAndCompleteWithPreviousUsedDevice(this._deviceSelected, setByUser);
                const audio_input = (_a = useDevice.audioInput) === null || _a === void 0 ? void 0 : _a.device;
                const video_input = (_b = useDevice.videoInput) === null || _b === void 0 ? void 0 : _b.device;
                const audio_output = (_c = useDevice.audioOutput) === null || _c === void 0 ? void 0 : _c.device;
                const audio_signal_output = (_d = useDevice.audioSignalOutput) === null || _d === void 0 ? void 0 : _d.device;
                const audio_notification_output = (_e = useDevice.audioNotificationOutput) === null || _e === void 0 ? void 0 : _e.device;
                const deviceSelectedAudioInput = audio_input ? audio_input : null;
                const deviceSelectedVideoInput = typeof video_input === "boolean" ? video_input : video_input === null || !!video_input ? video_input : false;
                const deviceSelectedAudioOutput = audio_output ? audio_output : null;
                const deviceSelectedAudioSignalOutput = audio_signal_output ? audio_signal_output : null;
                const deviceSelectedAudioNotificationOutput = audio_notification_output ? audio_notification_output : null;
                if (this._deviceSelected.audioInput !== deviceSelectedAudioInput || this._deviceSelected.videoInput !== deviceSelectedVideoInput || this._deviceSelected.audioOutput !== deviceSelectedAudioOutput || this._deviceSelected.audioSignalOutput !== deviceSelectedAudioSignalOutput || this._deviceSelected.audioNotificationOutput !== deviceSelectedAudioNotificationOutput) {
                    this._deviceSelected.audioInput = deviceSelectedAudioInput;
                    this._deviceSelected.videoInput = deviceSelectedVideoInput;
                    this._deviceSelected.audioOutput = deviceSelectedAudioOutput;
                    this._deviceSelected.audioSignalOutput = deviceSelectedAudioSignalOutput;
                    this._deviceSelected.audioNotificationOutput = deviceSelectedAudioNotificationOutput;
                    if (this._deviceSelected.audioInput || this._deviceSelected.videoInput || this._deviceSelected.audioOutput || this._deviceSelected.audioSignalOutput || this._deviceSelected.audioNotificationOutput) {
                        try {
                            yield this.checkSelectedMediaDevice(yield DeviceManager.getMediaDevice(false, true, true));
                        }
                        catch (err) {
                            this._log.error(err);
                        }
                    }
                }
                this.notifyAvailableMedia();
                this.manager.deviceChanged();
                if (saveOnStorage) {
                    yield this._useDeviceHistory.store(useDevice, setByUser);
                }
                return;
            });
        }
        getMediaDevice(startMedia, acquireAudio = true, acquireVideo = true) {
            return DeviceManager.getMediaDevice(startMedia, acquireAudio, acquireVideo);
        }
        checkDevicePermission(permission) {
            return __awaiter(this, void 0, void 0, function* () {
                const localStream = new LocalMedia({ audio: !!permission.audio, video: !!permission.video });
                yield localStream.start();
                yield localStream.stop();
                return { audio: !!permission.audio, video: !!permission.video };
            });
        }
        testMediaDevice(audioInput, videoInput, audioOutput, videoContainer) {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function* () {
                try {
                    yield ((_a = this.mediaDeviceTest) === null || _a === void 0 ? void 0 : _a.stop());
                    const localMedia = new LocalMedia({ audio: !!(audioInput !== null && audioInput !== void 0 ? audioInput : true), video: !!(videoInput !== null && videoInput !== void 0 ? videoInput : true) });
                    localMedia.changeAudioVideoInput(audioInput, videoInput);
                    this.mediaDeviceTest = new MediaDeviceTest(localMedia, videoContainer);
                    try {
                        yield this.mediaDeviceTest.start();
                    }
                    catch (e) {
                        this._log.warn("Error on start localMedia for testMediaDevice", { audioInput, videoInput });
                    }
                    if (audioOutput) {
                        try {
                            yield localMedia.changeAudioOutput(audioOutput);
                        }
                        catch (e) {
                            this._log.warn("Error on changeAudioOutput for testMediaDevice", { audioOutput });
                        }
                    }
                    return this.mediaDeviceTest;
                }
                catch (e) {
                    (_b = this.mediaDeviceTest) === null || _b === void 0 ? void 0 : _b.stop();
                    throw e;
                }
            });
        }
        checkSelectedMediaDevice(currentMediaDevice) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this._deviceSelected.audioInput && !currentMediaDevice.hasAudioInput(this._deviceSelected.audioInput)) {
                    this._deviceSelected.audioInput = null;
                }
                if (typeof this._deviceSelected.videoInput === "boolean") {
                    this._deviceSelected.videoInput = false === this._deviceSelected.videoInput ? false : null;
                }
                else if (this._deviceSelected.videoInput && !currentMediaDevice.hasVideoInput(this._deviceSelected.videoInput)) {
                    this._deviceSelected.videoInput = null;
                }
                if (this._deviceSelected.audioOutput && !currentMediaDevice.hasAudioOutput(this._deviceSelected.audioOutput)) {
                    this._deviceSelected.audioOutput = null;
                }
                if (this._deviceSelected.audioSignalOutput && !currentMediaDevice.hasAudioOutput(this._deviceSelected.audioSignalOutput)) {
                    this._deviceSelected.audioSignalOutput = null;
                }
                if (this._deviceSelected.audioNotificationOutput && !currentMediaDevice.hasAudioOutput(this._deviceSelected.audioNotificationOutput)) {
                    this._deviceSelected.audioNotificationOutput = null;
                }
                return currentMediaDevice;
            });
        }
        selfManagedDeviceChangeHandler(deviceNotification) {
            return __awaiter(this, void 0, void 0, function* () {
                const deviceToUpdate = new UseDeviceManager();
                const newAddedDevice = new MediaDevice();
                let setConfigByUser = false;
                let saveOnStorage = false;
                let ejectedDevice = false;
                function getDeviceToUseAfterDeviceRemoved(removedDevice, currentDevice, selectedDevice, historySelectedDevice) {
                    let deviceToUse = undefined;
                    if (!((selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.isDeviceDefault()) || (selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.isDeviceDisabled())) && removedDevice.find((entry) => entry.deviceId === (selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.deviceId))) {
                        ejectedDevice = true;
                        const firstValidDevice = historySelectedDevice === null || historySelectedDevice === void 0 ? void 0 : historySelectedDevice.find((device) => currentDevice.some((entry) => entry.deviceId == device.deviceId));
                        if (firstValidDevice) {
                            deviceToUse = new UseDeviceStored(firstValidDevice.device || null);
                            saveOnStorage = true;
                        }
                        else {
                            deviceToUse = new UseDeviceStored(null);
                        }
                    }
                    return deviceToUse;
                }
                function getDeviceToUseAfterDeviceAdded(addedDevice, newDeviceIsAdded, selectedDevice, historySelectedDevice) {
                    let deviceToUse = undefined;
                    addedDevice
                        .filter((device) => device.deviceId !== (selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.deviceId))
                        .forEach((device) => {
                        let setByUser = false;
                        if (!(selectedDevice === null || selectedDevice === void 0 ? void 0 : selectedDevice.setByUser)) {
                            const sameDeviceById = historySelectedDevice === null || historySelectedDevice === void 0 ? void 0 : historySelectedDevice.find((entry) => entry.deviceId === device.deviceId);
                            if (sameDeviceById) {
                                setByUser = !!sameDeviceById.setByUser;
                            }
                            else {
                                const sameDeviceByLabel = historySelectedDevice === null || historySelectedDevice === void 0 ? void 0 : historySelectedDevice.find((entry) => entry.label === device.label);
                                if (sameDeviceByLabel) {
                                    setByUser = !!sameDeviceByLabel.setByUser;
                                }
                            }
                        }
                        if (setByUser) {
                            deviceToUse = new UseDeviceStored(device);
                            setConfigByUser = true;
                            saveOnStorage = true;
                        }
                        else {
                            if (!newDeviceIsAdded(device)) {
                                newAddedDevice.addDevice(device);
                            }
                        }
                    });
                    return deviceToUse;
                }
                const deviceToUseAfterRemove = new UseDeviceManager();
                deviceToUseAfterRemove.audioInput = getDeviceToUseAfterDeviceRemoved(deviceNotification.status.deleted.audioInput, deviceNotification.devices.audioInput, this._useDeviceHistory.audioInputUsed, this._useDeviceHistory.audioInput);
                deviceToUseAfterRemove.videoInput = getDeviceToUseAfterDeviceRemoved(deviceNotification.status.deleted.videoInput, deviceNotification.devices.videoInput, this._useDeviceHistory.videoInputUsed, this._useDeviceHistory.videoInput);
                deviceToUseAfterRemove.audioOutput = getDeviceToUseAfterDeviceRemoved(deviceNotification.status.deleted.audioOutput, deviceNotification.devices.audioOutput, this._useDeviceHistory.audioOutputUsed, this._useDeviceHistory.audioOutput);
                deviceToUseAfterRemove.audioSignalOutput = getDeviceToUseAfterDeviceRemoved(deviceNotification.status.deleted.audioOutput, deviceNotification.devices.audioOutput, this._useDeviceHistory.audioSignalOutputUsed, this._useDeviceHistory.audioSignalOutput);
                deviceToUseAfterRemove.audioNotificationOutput = getDeviceToUseAfterDeviceRemoved(deviceNotification.status.deleted.audioOutput, deviceNotification.devices.audioOutput, this._useDeviceHistory.audioNotificationOutputUsed, this._useDeviceHistory.audioNotificationOutput);
                deviceToUpdate.useDeviceFromOtherUseDeviceManager(deviceToUseAfterRemove);
                const deviceToUseAfterAdded = new UseDeviceManager();
                deviceToUseAfterAdded.audioInput = getDeviceToUseAfterDeviceAdded(deviceNotification.status.added.audioInput, newAddedDevice.hasAudioInput.bind(newAddedDevice), this._useDeviceHistory.audioInputUsed, this._useDeviceHistory.audioInput);
                deviceToUseAfterAdded.videoInput = getDeviceToUseAfterDeviceAdded(deviceNotification.status.added.videoInput, newAddedDevice.hasVideoInput.bind(newAddedDevice), this._useDeviceHistory.videoInputUsed, this._useDeviceHistory.videoInput);
                deviceToUseAfterAdded.audioOutput = getDeviceToUseAfterDeviceAdded(deviceNotification.status.added.audioOutput, newAddedDevice.hasAudioOutput.bind(newAddedDevice), this._useDeviceHistory.audioOutputUsed, this._useDeviceHistory.audioOutput);
                deviceToUseAfterAdded.audioSignalOutput = getDeviceToUseAfterDeviceAdded(deviceNotification.status.added.audioOutput, newAddedDevice.hasAudioOutput.bind(newAddedDevice), this._useDeviceHistory.audioSignalOutputUsed, this._useDeviceHistory.audioSignalOutput);
                deviceToUseAfterAdded.audioNotificationOutput = getDeviceToUseAfterDeviceAdded(deviceNotification.status.added.audioOutput, newAddedDevice.hasAudioOutput.bind(newAddedDevice), this._useDeviceHistory.audioNotificationOutputUsed, this._useDeviceHistory.audioNotificationOutput);
                deviceToUpdate.useDeviceFromOtherUseDeviceManager(deviceToUseAfterAdded);
                if (deviceToUpdate.audioInput || deviceToUpdate.videoInput || deviceToUpdate.audioOutput || deviceToUpdate.audioSignalOutput || deviceToUpdate.audioNotificationOutput) {
                    yield this.useDeviceInternal(deviceToUpdate, setConfigByUser, saveOnStorage);
                }
                this._selfManagedDeviceActivity.next({ ejectedDevice, deviceToUpdate });
                if (newAddedDevice.audioInputEnabled || newAddedDevice.audioOutputEnabled || newAddedDevice.videoInputEnabled) {
                    this._addedDeviceOnSelfManagedMode.next(newAddedDevice);
                }
                return deviceNotification;
            });
        }
    }
    class UseDeviceStored {
        constructor(device, setByUser = false, lastUsedAt = new Date()) {
            this.device = device !== null && device !== void 0 ? device : null;
            this.lastUsedAt = lastUsedAt;
            this.setByUser = setByUser;
        }
        get deviceId() {
            return this.device ? this.device.deviceId : undefined;
        }
        get label() {
            return this.device ? this.device.label : undefined;
        }
        isDeviceDefault() {
            return this.device === null || this.device === undefined;
        }
        isDeviceDisabled() {
            return this.device === false;
        }
    }
    class UseDeviceManager {
        constructor(device) {
            if (device) {
                this.audioInput = new UseDeviceStored(device.audioInput);
                this.videoInput = new UseDeviceStored(device.videoInput);
                this.audioOutput = new UseDeviceStored(device.audioOutput);
                this.audioSignalOutput = new UseDeviceStored(device.audioSignalOutput);
                this.audioNotificationOutput = new UseDeviceStored(device.audioNotificationOutput);
            }
        }
        useDeviceFromOtherUseDeviceManager(deviceManager) {
            if (deviceManager.audioInput)
                this.audioInput = deviceManager.audioInput;
            if (deviceManager.videoInput)
                this.videoInput = deviceManager.videoInput;
            if (deviceManager.audioOutput)
                this.audioOutput = deviceManager.audioOutput;
            if (deviceManager.audioSignalOutput)
                this.audioSignalOutput = deviceManager.audioSignalOutput;
            if (deviceManager.audioNotificationOutput)
                this.audioNotificationOutput = deviceManager.audioNotificationOutput;
        }
        cloneAndCompleteWithPreviousUsedDevice(previousUsedDevice, setByUser) {
            const useDevice = new UseDeviceManager(previousUsedDevice);
            if (this.audioInput) {
                useDevice.audioInput = this.audioInput;
            }
            if (this.videoInput) {
                useDevice.videoInput = this.videoInput;
            }
            if (this.audioOutput) {
                useDevice.audioOutput = this.audioOutput;
            }
            if (this.audioSignalOutput) {
                useDevice.audioSignalOutput = this.audioSignalOutput;
            }
            if (this.audioNotificationOutput) {
                useDevice.audioNotificationOutput = this.audioNotificationOutput;
            }
            useDevice.setByUser = setByUser;
            return useDevice;
        }
        set setByUser(setByUser) {
            [this.audioInput, this.videoInput, this.audioOutput, this.audioSignalOutput, this.audioNotificationOutput].forEach((useDevice) => {
                if (useDevice) {
                    useDevice.setByUser = setByUser;
                }
            });
        }
    }
    class UseDeviceHistoryManager {
        constructor(historyStore) {
            this.historyStore = historyStore;
            this.history = {};
            this.storeInitialized = false;
        }
        buildHistory(historyProto) {
            const history = {};
            if (historyProto) {
                if (historyProto.audioInput) {
                    history.audioInput = historyProto.audioInput.map((d) => new UseDeviceStored(d.device, d.setByUser, new Date(d.lastUsedAt)));
                }
                if (historyProto.audioOutput) {
                    history.audioOutput = historyProto.audioOutput.map((d) => new UseDeviceStored(d.device, d.setByUser, new Date(d.lastUsedAt)));
                }
                if (historyProto.audioSignalOutput) {
                    history.audioSignalOutput = historyProto.audioSignalOutput.map((d) => new UseDeviceStored(d.device, d.setByUser, new Date(d.lastUsedAt)));
                }
                if (historyProto.audioNotificationOutput) {
                    history.audioNotificationOutput = historyProto.audioNotificationOutput.map((d) => new UseDeviceStored(d.device, d.setByUser, new Date(d.lastUsedAt)));
                }
                if (historyProto.videoInput) {
                    history.videoInput = historyProto.videoInput.map((d) => new UseDeviceStored(d.device, d.setByUser, new Date(d.lastUsedAt)));
                }
            }
            this.history = history;
        }
        init() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.storeInitialized) {
                    this.buildHistory(yield this.historyStore.get());
                    this.storeInitialized = true;
                }
            });
        }
        get audioInputUsed() {
            var _a;
            return (_a = this.history.audioInput) === null || _a === void 0 ? void 0 : _a[0];
        }
        get audioOutputUsed() {
            var _a;
            return (_a = this.history.audioOutput) === null || _a === void 0 ? void 0 : _a[0];
        }
        get audioSignalOutputUsed() {
            var _a;
            return (_a = this.history.audioSignalOutput) === null || _a === void 0 ? void 0 : _a[0];
        }
        get audioNotificationOutputUsed() {
            var _a;
            return (_a = this.history.audioNotificationOutput) === null || _a === void 0 ? void 0 : _a[0];
        }
        get videoInputUsed() {
            var _a;
            return (_a = this.history.videoInput) === null || _a === void 0 ? void 0 : _a[0];
        }
        get audioInput() {
            return this.history.audioInput;
        }
        get audioOutput() {
            return this.history.audioOutput;
        }
        get audioSignalOutput() {
            return this.history.audioSignalOutput;
        }
        get audioNotificationOutput() {
            return this.history.audioNotificationOutput;
        }
        get videoInput() {
            return this.history.videoInput;
        }
        updateStoredDevices(device, setByUser, deviceHistory) {
            const history = deviceHistory !== null && deviceHistory !== void 0 ? deviceHistory : [];
            let deviceOnHistory = undefined;
            if (device.isDeviceDisabled()) {
                deviceOnHistory = history.find((entry) => entry.isDeviceDisabled());
            }
            else if (device.isDeviceDefault()) {
                deviceOnHistory = history.find((entry) => entry.isDeviceDefault());
            }
            else {
                const sameDeviceById = history.find((entry) => entry.deviceId === device.deviceId);
                if (sameDeviceById) {
                    deviceOnHistory = sameDeviceById;
                }
                else {
                    const sameDeviceByLabel = history.find((entry) => entry.label === device.label);
                    if (sameDeviceByLabel) {
                        deviceOnHistory = sameDeviceByLabel;
                    }
                }
            }
            if (deviceOnHistory) {
                deviceOnHistory.device = device.device;
                deviceOnHistory.lastUsedAt = new Date();
                deviceOnHistory.setByUser = setByUser;
            }
            else {
                history.push(new UseDeviceStored(device.device, setByUser, new Date()));
            }
            return history;
        }
        store({ audioInput, videoInput, audioOutput, audioSignalOutput, audioNotificationOutput }, setByUser) {
            return __awaiter(this, void 0, void 0, function* () {
                yield this.init();
                if (audioInput) {
                    this.history.audioInput = this.updateStoredDevices(audioInput, setByUser, this.history.audioInput);
                }
                if (audioOutput) {
                    this.history.audioOutput = this.updateStoredDevices(audioOutput, setByUser, this.history.audioOutput);
                }
                if (audioSignalOutput) {
                    this.history.audioSignalOutput = this.updateStoredDevices(audioSignalOutput, setByUser, this.history.audioSignalOutput);
                }
                if (audioNotificationOutput) {
                    this.history.audioNotificationOutput = this.updateStoredDevices(audioNotificationOutput, setByUser, this.history.audioNotificationOutput);
                }
                if (videoInput) {
                    this.history.videoInput = this.updateStoredDevices(videoInput, setByUser, this.history.videoInput);
                }
                [this.history.audioInput, this.history.audioOutput, this.history.audioSignalOutput, this.history.audioNotificationOutput, this.history.videoInput].forEach((useDeviceHistory) => {
                    if (useDeviceHistory) {
                        useDeviceHistory.sort((a, b) => {
                            if (a.lastUsedAt > b.lastUsedAt) {
                                return -1;
                            }
                            if (a.lastUsedAt < b.lastUsedAt) {
                                return 1;
                            }
                            return 0;
                        });
                    }
                });
                if (this.storeInitialized) {
                    this.buildHistory(yield this.historyStore.set(this.history));
                }
            });
        }
    }
    class UseDeviceHistoryStore {
        get() {
            return __awaiter(this, void 0, void 0, function* () {
                return {};
            });
        }
        set(history) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!history) {
                    return this.get();
                }
                [history.audioInput, history.audioOutput, history.videoInput].forEach((devices) => {
                    if (devices && devices.length > 20) {
                        devices.pop();
                    }
                });
                return history;
            });
        }
    }

    const AllowedMethods = ["startVideoEchoTest", "dial", "answer", "hold", "unhold", "attendedTransfer", "blindTransfer", "sendDTMF", "cancel", "createUserInteraction", "removeCallFromUserInteraction", "updateWebRTCFields", "getWebrtcConfiguration", "setWebRTCAvailableMedia", "mute", "unmute", "startVideoOnCall", "stopVideoOnCall"];
    class WebrtcMethodProxy {
        constructor(manager, methodImpl) {
            this.manager = manager;
            this.methodImpl = methodImpl;
        }
        getMethod(method) {
            if (AllowedMethods.indexOf(method) < 0) {
                throw new Error(`Webrtc method ${method} is invalid`);
            }
            if (this.methodImpl && this.methodImpl.hasOwnProperty(method)) {
                return this.methodImpl[method];
            }
            throw new Error(`Webrtc method ${method} not implemented.`);
        }
        startVideoEchoTest(params, options) {
            return this.getMethod("startVideoEchoTest")(params, options);
        }
        dial(params, options) {
            return this.getMethod("dial")(params, options);
        }
        answer(params, options) {
            return this.getMethod("answer")(params, options);
        }
        hold(params, options) {
            return this.getMethod("hold")(params, options);
        }
        unhold(params, options) {
            return this.getMethod("unhold")(params, options);
        }
        attendedTransfer(params, options) {
            return this.getMethod("attendedTransfer")(params, options);
        }
        blindTransfer(params, options) {
            return this.getMethod("blindTransfer")(params, options);
        }
        sendDTMF(params, options) {
            return this.getMethod("sendDTMF")(params, options);
        }
        cancel(params, options) {
            return this.getMethod("cancel")(params, options);
        }
        createUserInteraction(params, options) {
            return this.getMethod("createUserInteraction")(params, options);
        }
        removeCallFromUserInteraction(params, options) {
            return this.getMethod("removeCallFromUserInteraction")(params, options);
        }
        updateWebRTCFields(params, options) {
            return this.getMethod("updateWebRTCFields")(params, options);
        }
        getWebrtcConfiguration(params, options) {
            return this.getMethod("getWebrtcConfiguration")(params, options);
        }
        setWebRTCAvailableMedia(params, options) {
            return this.getMethod("setWebRTCAvailableMedia")(params, options);
        }
        mute(params, options) {
            return this.getMethod("mute")(params, options);
        }
        unmute(params, options) {
            return this.getMethod("unmute")(params, options);
        }
        startVideoOnCall(params, options) {
            return this.getMethod("startVideoOnCall")(params, options);
        }
        stopVideoOnCall(params, options) {
            return this.getMethod("stopVideoOnCall")(params, options);
        }
    }

    class WebRTCManager {
        constructor(options = new WebrtcConfig()) {
            this._callIdToRemove = new Set();
            this._controlMessageNotifierSubscription = Subscription.EMPTY;
            this._connectionStateSubscription = Subscription.EMPTY;
            this._loadedOptions = new WebrtcConfig(options);
            this.applyOptions();
        }
        get client() {
            return this._client;
        }
        get log() {
            return this._log;
        }
        get enable() {
            return !!this._enabled;
        }
        get options() {
            return this._loadedOptions;
        }
        set options(options) {
            this._loadedOptions = new WebrtcConfig(options);
            this.applyOptions();
        }
        get methods() {
            return this._apiMethods;
        }
        get methodExecutor() {
            return this._methodExecutor;
        }
        get callConnectionState() {
            return this._callConnectionStateSubject.asObservable();
        }
        get trickleIcePolicy() {
            return this.options.trickleIcePolicy || Connection.TrickleIcePolicy.NotSupported;
        }
        get phoneSignal() {
            return this._phoneSignalManager;
        }
        get device() {
            return this._deviceManager;
        }
        attachToClient(client, methodImpl) {
            const prevClient = this._client;
            this._client = client;
            if (!prevClient || prevClient.instanceId !== client.instanceId) {
                this._log = Log$1.of("webrtc", client);
                this._log.info("WebRTCManager attached to client, configuration used:", this._loadedOptions);
                this._enabled = false;
                this._callIdToRemove.clear();
                this._tLinkLogger = new TLinkLogger(this);
                this._methodExecutor = new WebrtcMethodProxy(this, methodImpl);
                this._apiMethods = new WebRTCMethodsExecutor(client);
                if (!client.webrtc || (prevClient && prevClient.instanceId != client.instanceId)) {
                    client.webrtc = this;
                }
            }
        }
        initFromClient(controlMessageNotifier) {
            if (controlMessageNotifier) {
                this._controlMessageNotifier = controlMessageNotifier;
                this.init();
            }
        }
        isEnabledForChannel(channelType) {
            return this._loadedOptions.enabledOnChannel.indexOf(channelType) > -1;
        }
        init() {
            this._log.info("WebRTCManager init");
            this._connections = new Map();
            this._callConnectionStateSubject = new Subject();
            this._deviceManager = new WebrtDeviceManager(this);
            this._phoneSignalManager = new PhoneSignalManager(this);
            if (this._loadedOptions.enabled) {
                return this.start();
            }
            else {
                return Promise.resolve();
            }
        }
        applyOptions() {
            const options = this._loadedOptions;
            if (options.iceServers) {
                this._iceServers = options.iceServers.map((iceServer) => iceServer.username
                    ? {
                        urls: iceServer.url,
                        username: iceServer.username,
                        credential: iceServer.password,
                        credentialType: "password",
                    }
                    : { urls: iceServer.url });
            }
            else {
                this._iceServers = null;
            }
        }
        deviceChanged() {
            this._connections.forEach((call) => {
                var _a, _b;
                (_a = call.localMedia) === null || _a === void 0 ? void 0 : _a.changeAudioVideoInput(this._deviceManager.audioInput, this._deviceManager.videoInput);
                (_b = call.remoteMedia) === null || _b === void 0 ? void 0 : _b.setAudioOutput(this._deviceManager.audioOutput);
            });
        }
        getIceServers(requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._iceServers || this._iceServers.length === 0) {
                    this._iceServers = [];
                    try {
                        const response = yield toPromise$1(this._apiMethods.getWebrtcConfiguration(requestTimeout).result);
                        if (response) {
                            if (response.iceServers && response.iceServers.length) {
                                response.iceServers.forEach((s) => {
                                    if (s && s.url) {
                                        try {
                                            const iceServer = { urls: s.url };
                                            if (s.hasOwnProperty("username")) {
                                                iceServer.username = s.username;
                                                iceServer.credential = s.password || "";
                                            }
                                            this._iceServers.push(iceServer);
                                        }
                                        catch (e) {
                                            this._log.error("Error on create IceServer", e);
                                        }
                                    }
                                });
                            }
                        }
                    }
                    catch (e) {
                        this._log.error("Error on getWebrtcConfiguration", e);
                    }
                }
                return this._iceServers;
            });
        }
        setEnabledOnChannel(channels) {
            if (channels) {
                this._loadedOptions.enabledOnChannel.length = 0;
                this._loadedOptions.enabledOnChannel.push.apply(this._loadedOptions.enabledOnChannel, channels);
                this._log.debug(`Enabled on channels ${this._loadedOptions.enabledOnChannel.join(",")}`);
            }
        }
        start() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this._enabled && this._client) {
                    registerProvider(this._tLinkLogger);
                    this._enabled = true;
                    var uniqueId = 0;
                    this._log.debug(`Enabled on channels ${this._loadedOptions.enabledOnChannel.join(",")}`);
                    this._controlMessageNotifierSubscription.unsubscribe();
                    this._controlMessageNotifierSubscription = this._controlMessageNotifier
                        .pipe(tap((controlMessage) => {
                        controlMessage.internalId = ++uniqueId;
                        this._log.debug(`ControlMessageManager - Receiving message ${controlMessage.internalId}`, controlMessage);
                    }), map((controlMessage) => this.createCallFromControlMessage(controlMessage)), tap((data) => { var _a; return (_a = data.call) === null || _a === void 0 ? void 0 : _a.controlMessageNotifier.next(data.controlMessage); }), filter(({ call }) => !call), concatMap(({ controlMessage }) => this.manageControlMessage(controlMessage, false)))
                        .subscribe();
                    this._client.loginProfileLoggedOnNewSession.subscribe(() => __awaiter(this, void 0, void 0, function* () {
                        try {
                            this.getIceServers();
                        }
                        catch (e) { }
                    }));
                    this._connectionStateSubscription.unsubscribe();
                    this._connectionStateSubscription = this._client.connectionEvent.subscribe((event) => {
                        if (event.connected) {
                            this.cleanPendingCall();
                        }
                    });
                    return this.device.init();
                }
            });
        }
        stop() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this._enabled) {
                    this._controlMessageNotifierSubscription.unsubscribe();
                    this._connectionStateSubscription.unsubscribe();
                    this._enabled = false;
                    this._connections.forEach((call) => {
                        this.methods.cancel(call.callId, true, true);
                    });
                }
            });
        }
        checkUniqueCallBeforeDial(dialParam) {
            this._connections.forEach((call) => {
                if (call.isOffer) {
                    const callDialParams = call.dialParams;
                    if (callDialParams && callDialParams.equals(dialParam)) {
                        throw CallInProgress.newInstance(call.callId);
                    }
                }
            });
        }
        generateWebrtcFieldsForDial(dialParam, mediaConfiguration, videoContainer, userInteractionAction, requestTimeout) {
            return __awaiter(this, void 0, void 0, function* () {
                this.checkUniqueCallBeforeDial(dialParam);
                const callId = uuidv4();
                const call = this.createCall(callId, ChannelType.PhoneCall, true, CallState.NEW_OUTBOUND, false, true, dialParam);
                const fromDevice = dialParam.params.fromDevice;
                const contact = dialParam.params.contact;
                const media = dialParam.params.media;
                const createUserInteraction = !(dialParam.params.serviceCode || dialParam.params.abandonedCallId || dialParam.params.callbackRequestId);
                if (createUserInteraction) {
                    this._apiMethods
                        .createUserInteraction({
                        action: userInteractionAction,
                        contact: contact,
                        callId: callId,
                        type: UserInteractionType.call,
                    }, requestTimeout)
                        .result.subscribe((userInteractionId) => {
                        if (!call || (call.isOffer && !call.signalingState)) {
                            this._log.debug(`createUserInteraction response before dial for call ${callId}, emit dummy NEW_OUTBOUND event`);
                            this.publishControlMessage({
                                callId: callId,
                                device: fromDevice,
                                direction: CallDirection.outbound,
                                state: CallState.NEW_OUTBOUND,
                                features: [CallFeature.CANCEL],
                                _isFromServer: false,
                                _channelType: dialParam.params.channelId,
                                _realChannelType: dialParam.params.channelId,
                            });
                        }
                    }, (error) => {
                        this._log.error("createUserInteraction error", error);
                    });
                }
                try {
                    if (call.deviceIsApp) {
                        return this.generateWebrtcFieldsForApp(callId, false, media, mediaConfiguration, videoContainer);
                    }
                    else {
                        return yield this.generateWebrtcFields(call, false, media, mediaConfiguration, videoContainer);
                    }
                }
                catch (e) {
                    if (createUserInteraction && call && call.signalingState && call.signalingState === CallState.NEW_OUTBOUND && !call.realState) {
                        this.publishControlMessage({
                            callId: callId,
                            device: fromDevice,
                            direction: CallDirection.outbound,
                            state: CallState.IDLE,
                            _isFromServer: false,
                            _channelType: dialParam.params.channelId,
                            _realChannelType: dialParam.params.channelId,
                        });
                    }
                    throw e;
                }
            });
        }
        generateWebrtcFieldsForCallChannel(call, answer, media, mediaConfiguration) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.generateWebrtcFields(call, answer, media, mediaConfiguration);
            });
        }
        generateWebrtcFieldsForAnswer(channelId, callId, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                let answer = true;
                let offer = false;
                if (channelId && channelId === ChannelType.Video) {
                    answer = false;
                    offer = true;
                }
                const call = this.createCall(callId, channelId, offer, CallState.NEW_INBOUND, false, true);
                yield this.phoneSignal.stop(call.callId, false);
                const result = yield this.generateWebrtcFields(call, answer, media, mediaConfiguration, videoContainer);
                call.waitForAnswer = false;
                return result;
            });
        }
        generateWebrtcFieldsForConnectivityCheck(channelType, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.createCall(uuidv4(), channelType, true, CallState.CONNECTED, true, true);
                return this.generateWebrtcFields(call, false, media, mediaConfiguration, videoContainer);
            });
        }
        generateWebrtcFieldsForApp(callId, answer, media, mediaConfiguration, videoContainer) {
            return new WebRTCField(answer ? null : callId, new WebRTCFieldSession(answer, null), null, null, null);
        }
        generateWebrtcFields(call, answer, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                call.mediaEnabled = true;
                if (videoContainer) {
                    call.videoContainer = videoContainer;
                }
                const mediaParam = MediaParam.of(media);
                if (mediaParam._hasMedia()) {
                    if (!answer) {
                        yield this.phoneSignal.play(call.callId, MediaSignal.dialtone);
                    }
                    return call.connectionActionQueue(() => __awaiter(this, void 0, void 0, function* () {
                        var _a;
                        try {
                            yield call.setLocalMedia(mediaParam, mediaConfiguration);
                        }
                        catch (err) {
                            this._log.error("error on generateWebrtcFields.setLocalMedia", err);
                            throw err;
                        }
                        try {
                            yield ((_a = call.localMedia) === null || _a === void 0 ? void 0 : _a.start());
                        }
                        catch (err) {
                            this._log.error("error on generateWebrtcFields.startLocalMedia", err);
                            throw err;
                        }
                        yield call.initTlinkConnection();
                        const webrtcField = call.generateLocalWebRTCField();
                        if (webrtcField.sessionDescription) {
                            webrtcField.sessionDescription.answer = !call.isOffer;
                        }
                        else {
                            webrtcField.sessionDescription = new WebRTCFieldSession(answer, null);
                        }
                        webrtcField.clientid = answer ? null : call.callId;
                        call.localDescriptionIsNotified();
                        return webrtcField;
                    }));
                }
                else {
                    return new WebRTCField(answer ? null : call.callId, new WebRTCFieldSession(answer, null), null, null, null);
                }
            });
        }
        toggleHold(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                if (call) {
                    const callIsHold = call.signalingState == CallState.HOLD;
                    call.setSignalingState(callIsHold ? CallState.CONNECTED : CallState.HOLD, null);
                    return call.toggleRemoteAudioMute(!callIsHold);
                }
                else {
                    return false;
                }
            });
        }
        setLocalMedia(callId, media, mediaConfiguration) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                if (call) {
                    yield call.setLocalMedia(new MediaParamImpl(media), mediaConfiguration);
                    return this;
                }
                else {
                    throw new Error("idCall is invalid");
                }
            });
        }
        toggleAudioMute(callId, mute) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.toggleAudioMute(mute, true) : false;
            });
        }
        toggleVideoMute(callId, mute) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.toggleVideoMute(mute, true) : false;
            });
        }
        toggleRemoteAudioMute(callId, mute) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.toggleRemoteAudioMute(mute) : false;
            });
        }
        toggleRemoteVideoMute(callId, mute) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.toggleRemoteVideoMute(mute) : false;
            });
        }
        isVideoEnabled(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.isVideoEnabled() : false;
            });
        }
        startAudio(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.startAudio() : false;
            });
        }
        stopAudio(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.stopAudio() : false;
            });
        }
        startVideo(callId, constraints, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.startVideo(constraints, videoContainer) : false;
            });
        }
        stopVideo(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                return call ? call.stopVideo() : false;
            });
        }
        getLocalVideoFrame(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                if (call) {
                    return call.getLocalVideoFrame();
                }
                else {
                    throw new Error(`Call ${callId} is not defined`);
                }
            });
        }
        getRemoteVideoFrame(callId) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                if (call) {
                    return call.getRemoteVideoFrame();
                }
                else {
                    throw new Error(`Call ${callId} is not defined`);
                }
            });
        }
        setVideoContainer(callId, videoContainer) {
            const call = this.retriveCall(callId);
            if (call) {
                call.videoContainer = videoContainer;
            }
        }
        getRemoteAudioLevel(callId) {
            const call = this.retriveCall(callId);
            return call ? call.getRemoteAudioLevel() : EMPTY;
        }
        getLocalAudioLevel(callId) {
            const call = this.retriveCall(callId);
            return call ? call.getLocalAudioLevel() : EMPTY;
        }
        getConnectionStats(callId) {
            const call = this.retriveCall(callId);
            return call ? call.getConnectionStats() : EMPTY;
        }
        publishControlMessage(controlMessage) {
            var _a;
            (_a = this._controlMessageNotifier) === null || _a === void 0 ? void 0 : _a.next(controlMessage);
        }
        createCallFromControlMessage(controlMessage) {
            if (controlMessage._channelType === ChannelType.Omnidesk) {
                return { controlMessage };
            }
            if (!this.isEnabledForChannel(controlMessage._channelType)) {
                throw new Error(`controlMessageHandler - Channel ${controlMessage._channelType} not enabled for webrtc`);
            }
            let call = this.retriveCall(controlMessage.callId);
            if (!call) {
                const deviceIsApp = controlMessage.device && controlMessage.device.startsWith("_app_");
                if (!deviceIsApp) {
                    const realEvent = controlMessage._isFromServer;
                    switch (controlMessage.state) {
                        case CallState.CONNECTED:
                        case CallState.NEW_INBOUND:
                            const offer = controlMessage._channelType === ChannelType.Video;
                            call = this.createCall(controlMessage.callId, controlMessage._channelType, offer, controlMessage.state, realEvent, false);
                            break;
                        case CallState.NEW_OUTBOUND:
                            if (controlMessage._channelType === ChannelType.PhoneCall) {
                                call = this.createCall(controlMessage.callId, controlMessage._channelType, true, controlMessage.state, realEvent, false);
                            }
                            break;
                    }
                }
                if (call) {
                    this._log.info(`ControlMessageManager - call created from msg ${controlMessage.internalId} - ${controlMessage.callId}`);
                }
            }
            return { call, controlMessage };
        }
        manageControlMessage(controlMessage, notifiedFromCall) {
            return __awaiter(this, void 0, void 0, function* () {
                const msg = `manage message ${controlMessage.internalId} ${notifiedFromCall ? "- cn " : ""}- ${controlMessage.state} - ${controlMessage.callId}`;
                this._log.info(`ControlMessageManager - Start ${msg}`);
                try {
                    return yield this.controlMessageHandler(controlMessage);
                }
                catch (err) {
                    this._log.error(`ControlMessageManager - Error on manage message ${err.controlMessage.internalId}`, err);
                    return err.controlMessage;
                }
                finally {
                    this._log.debug(`ControlMessageManager - End ${msg}`);
                }
            });
        }
        omnideskControlMessageHandler(_webrtcControlMessage) {
            return __awaiter(this, void 0, void 0, function* () {
                const callInfo = _webrtcControlMessage;
                let call = this.retriveCall(callInfo.callId);
                const deviceIsApp = (call && call.deviceIsApp) || (callInfo.device && callInfo.device.startsWith("_app_"));
                const realEvent = callInfo._isFromServer;
                switch (callInfo.state) {
                    case CallState.NEW_INBOUND:
                        if (!call && !deviceIsApp) {
                            call = this.createCall(callInfo.callId, callInfo._channelType, false, callInfo.state, realEvent, false);
                        }
                        if (call) {
                            this.phoneSignal.stop(call.callId, true);
                            yield this.phoneSignal.play(call.callId, this._connections.size > 1 ? MediaSignal.ringAdvertising : MediaSignal.ring);
                        }
                        break;
                    case CallState.IDLE:
                        if (call) {
                            if (realEvent) {
                                this._callIdToRemove.delete(call.callId);
                            }
                            else {
                                call.markAsClosedLocal();
                            }
                            const currentPlay = this.phoneSignal.getCurrentPlay(call.callId);
                            if (call.signalingState === CallState.NEW_INBOUND) {
                                this.phoneSignal.stop(call.callId, true);
                            }
                            else if (currentPlay) {
                                if (currentPlay !== MediaSignal.hold) {
                                    if (!call.isClosedLocal()) {
                                        this.phoneSignal.stop(call.callId, true);
                                        yield this.phoneSignal.play(call.callId, currentPlay === MediaSignal.ringback ? MediaSignal.congestion : MediaSignal.busy);
                                    }
                                }
                            }
                            else {
                                if (!call.isClosedLocal() && callInfo.idleReason && callInfo.idleReason !== IdleReason.HANGUP) {
                                    yield this.phoneSignal.play(call.callId, callInfo.idleReason === IdleReason.CONGESTION ? MediaSignal.congestion : MediaSignal.busy);
                                }
                            }
                        }
                        else if (realEvent) {
                            this._callIdToRemove.delete(callInfo.callId);
                        }
                        if (yield this.destroyCall(callInfo.callId)) {
                            call = null;
                        }
                        break;
                    case CallState.CONNECTED:
                        if (call) {
                            call.waitForAnswer = false;
                            this.phoneSignal.stop(call.callId, true);
                        }
                        break;
                }
                if (call) {
                    call.setSignalingState(callInfo.state, realEvent, true);
                }
                else {
                    if (callInfo.state !== CallState.IDLE) {
                        throw new Error("No call");
                    }
                }
                return _webrtcControlMessage;
            });
        }
        controlMessageHandler(_webrtcControlMessage) {
            return __awaiter(this, void 0, void 0, function* () {
                try {
                    if (!_webrtcControlMessage) {
                        throw new Error("controlMessageHandler - message is invalid");
                    }
                    if (_webrtcControlMessage._channelType === ChannelType.Omnidesk) {
                        return yield this.omnideskControlMessageHandler(_webrtcControlMessage);
                    }
                    const callInfo = _webrtcControlMessage;
                    if (!this.isEnabledForChannel(callInfo._channelType)) {
                        throw new Error(`controlMessageHandler - Channel ${callInfo._channelType} not enabled for webrtc`);
                    }
                    let call = this.retriveCall(callInfo.callId);
                    const deviceIsApp = (call && call.deviceIsApp) || (callInfo.device && callInfo.device.startsWith("_app_"));
                    const webrtcfields = callInfo.fields ? WebRTCField.fromObject(callInfo.fields) : null;
                    const localMediaFeature = {};
                    const realEvent = callInfo._isFromServer;
                    if (callInfo.media_feature && callInfo.media_feature.local) {
                        for (const media in callInfo.media_feature.local) {
                            localMediaFeature[media] = new Set(callInfo.media_feature.local[media] ? callInfo.media_feature.local[media] : []);
                        }
                    }
                    const applyAction = () => __awaiter(this, void 0, void 0, function* () {
                        var _a;
                        switch (callInfo.state) {
                            case CallState.NEW_INBOUND:
                                const offer = callInfo._channelType === ChannelType.Video;
                                if (!call && !deviceIsApp) {
                                    call = this.createCall(callInfo.callId, callInfo._channelType, offer, callInfo.state, realEvent, false);
                                }
                                if (call) {
                                    if (webrtcfields) {
                                        call.remoteWebrtcfield = webrtcfields;
                                        yield call.tryAutoanswer();
                                    }
                                    if (callInfo.remote_media_status) {
                                        call.remoteCallMedia.audio = !!callInfo.remote_media_status.audio;
                                        call.remoteCallMedia.video = !!callInfo.remote_media_status.video;
                                        call.remoteCallMedia.desktop = !!callInfo.remote_media_status.desktop;
                                        call.remoteCallMedia.data = !!callInfo.remote_media_status.data;
                                    }
                                    if (!localMediaFeature.audio || !localMediaFeature.audio.has(CallMediaFeature.START)) {
                                        yield call.toggleAudioMute(true, false);
                                    }
                                    if (!localMediaFeature.video || !localMediaFeature.video.has(CallMediaFeature.START)) {
                                        yield call.toggleVideoMute(true, false);
                                    }
                                    if (!call.autoanswer && call.waitForAnswer) {
                                        this.phoneSignal.stop(call.callId, true);
                                        yield this.phoneSignal.play(call.callId, this._connections.size > 1 ? MediaSignal.ringAdvertising : MediaSignal.ring);
                                    }
                                }
                                break;
                            case CallState.NEW_OUTBOUND:
                                if (!call && !deviceIsApp && callInfo._channelType === ChannelType.PhoneCall) {
                                    call = this.createCall(callInfo.callId, callInfo._channelType, true, callInfo.state, realEvent, false);
                                }
                                if (call) {
                                    call.waitForAnswer = false;
                                    let playringback = call.realState && call.signalingState != CallState.NEW_INBOUND && call.signalingState != CallState.CONNECTED;
                                    if (playringback) {
                                        yield call.toggleAudioMute(true, false);
                                        yield call.toggleVideoMute(true, false);
                                    }
                                    if (webrtcfields) {
                                        call.remoteWebrtcfield = webrtcfields;
                                        if (webrtcfields.sessionDescription && webrtcfields.sessionDescription.session) {
                                            yield this.phoneSignal.stop(call.callId, true);
                                            playringback = false;
                                        }
                                        if (!this.options.immediateRingback && playringback && !webrtcfields.ring) {
                                            playringback = false;
                                        }
                                    }
                                    this.phoneSignal.stop(call.callId, true);
                                    if (playringback) {
                                        yield this.phoneSignal.play(call.callId, MediaSignal.ringback);
                                    }
                                }
                                break;
                            case CallState.IDLE:
                                if (call) {
                                    if (realEvent) {
                                        this._callIdToRemove.delete(call.callId);
                                    }
                                    else {
                                        call.markAsClosedLocal();
                                    }
                                    const currentPlay = this.phoneSignal.getCurrentPlay(call.callId);
                                    if (call.signalingState === CallState.NEW_INBOUND) {
                                        yield this.phoneSignal.stop(call.callId, true);
                                    }
                                    else if (currentPlay) {
                                        if (currentPlay !== MediaSignal.hold) {
                                            if (!call.isClosedLocal()) {
                                                yield this.phoneSignal.stop(call.callId, true);
                                                yield this.phoneSignal.play(call.callId, currentPlay === MediaSignal.ringback ? MediaSignal.congestion : MediaSignal.busy);
                                            }
                                        }
                                    }
                                    else {
                                        if (!call.isClosedLocal() && callInfo.idleReason && callInfo.idleReason !== IdleReason.HANGUP) {
                                            yield this.phoneSignal.play(call.callId, callInfo.idleReason === IdleReason.CONGESTION ? MediaSignal.congestion : MediaSignal.busy);
                                        }
                                    }
                                    call.closeConnection();
                                    call.remoteWebrtcfield = null;
                                }
                                else if (realEvent) {
                                    this._callIdToRemove.delete(callInfo.callId);
                                }
                                if (yield this.destroyCall(callInfo.callId)) {
                                    call = null;
                                }
                                break;
                            case CallState.CONNECTED:
                                if (call) {
                                    call.waitForAnswer = false;
                                    call.remoteWebrtcfield = webrtcfields;
                                    call.setSignalingState(callInfo.state, realEvent);
                                    yield this.phoneSignal.stop(call.callId, true);
                                    if (call.localMedia) {
                                    }
                                    else if (localMediaFeature) {
                                        yield call.setLocalMedia(new MediaParamImpl({
                                            audio: localMediaFeature.audio && (localMediaFeature.audio.has(CallMediaFeature.UNMUTE) || localMediaFeature.audio.has(CallMediaFeature.START)),
                                            video: localMediaFeature.video && (localMediaFeature.video.has(CallMediaFeature.UNMUTE) || localMediaFeature.video.has(CallMediaFeature.START)),
                                            desktop: localMediaFeature.desktop && (localMediaFeature.desktop.has(CallMediaFeature.UNMUTE) || localMediaFeature.desktop.has(CallMediaFeature.START)),
                                            data: localMediaFeature.data && (localMediaFeature.data.has(CallMediaFeature.UNMUTE) || localMediaFeature.data.has(CallMediaFeature.START)),
                                        }), this._loadedOptions.mediaConfiguration);
                                    }
                                    else {
                                        throw new Error("No media defined");
                                    }
                                    yield ((_a = call.localMedia) === null || _a === void 0 ? void 0 : _a.start());
                                    if (call.mediaOwnedByCurrentInstance) {
                                        yield call.initTlinkConnection();
                                        if (call.audioLinkStatus === CallMediaLinkStatus.MUTE && localMediaFeature.audio && localMediaFeature.audio.has(CallMediaFeature.MUTE)) {
                                            yield call.toggleAudioMute(false, false);
                                        }
                                        if (call.videoLinkStatus === CallMediaLinkStatus.MUTE && localMediaFeature.video && localMediaFeature.video.has(CallMediaFeature.MUTE)) {
                                            yield call.toggleVideoMute(false, false);
                                        }
                                    }
                                }
                                else {
                                    if (!deviceIsApp) {
                                        const offer = callInfo._channelType === ChannelType.Video;
                                        call = this.createCall(callInfo.callId, callInfo._channelType, offer, callInfo.state, realEvent, false);
                                    }
                                    if (call) {
                                        if (webrtcfields) {
                                            call.remoteWebrtcfield = webrtcfields;
                                        }
                                        if (callInfo.remote_media_status) {
                                            call.remoteCallMedia.audio = !!callInfo.remote_media_status.audio;
                                            call.remoteCallMedia.video = !!callInfo.remote_media_status.video;
                                            call.remoteCallMedia.desktop = !!callInfo.remote_media_status.desktop;
                                            call.remoteCallMedia.data = !!callInfo.remote_media_status.data;
                                        }
                                    }
                                }
                                break;
                            case CallState.HOLD:
                                if (call) {
                                    call.remoteWebrtcfield = webrtcfields;
                                    if (call.mediaOwnedByCurrentInstance) {
                                        if (call.audioLinkStatus === CallMediaLinkStatus.UNMUTE) {
                                            yield call.toggleAudioMute(true, false);
                                        }
                                        if (call.videoLinkStatus === CallMediaLinkStatus.UNMUTE) {
                                            yield call.toggleVideoMute(true, false);
                                        }
                                        if (CallState.HOLD !== call.signalingState) {
                                            yield this.phoneSignal.play(call.callId, MediaSignal.hold);
                                        }
                                    }
                                }
                                break;
                        }
                        if (call) {
                            call.setSignalingState(callInfo.state, realEvent, true);
                            yield call.updateRemoteWebrtcFields();
                        }
                        else {
                            if (callInfo.state !== CallState.IDLE) {
                                throw new Error("No call");
                            }
                        }
                        return _webrtcControlMessage;
                    });
                    if (call) {
                        return yield call.connectionActionQueue(applyAction);
                    }
                    else {
                        return yield applyAction();
                    }
                }
                catch (err) {
                    err.controlMessage = _webrtcControlMessage;
                    throw err;
                }
            });
        }
        createCall(callId, channelType, offer, state, realState, markOwner, dialParam, callChecker) {
            let call = this.retriveCall(callId);
            if (!call) {
                if (channelType === ChannelType.Omnidesk) {
                    call = new CallOmnidesk(this, callId, state);
                }
                else {
                    if (callChecker) {
                        call = new CallChecker(this, this._callConnectionStateSubject, callId, channelType, offer, state, realState);
                    }
                    else {
                        call = new Call(this, this._callConnectionStateSubject, callId, channelType, offer, state, realState);
                    }
                    if (dialParam) {
                        call.dialParams = dialParam;
                    }
                }
                this._connections.set(callId, call);
            }
            if (markOwner) {
                call.mediaOwnerId = this._client.instanceId;
            }
            return call;
        }
        retriveCall(callId) {
            var _a;
            return (callId !== null && callId !== void 0 ? callId : null) !== null ? (_a = this._connections.get(callId)) !== null && _a !== void 0 ? _a : null : null;
        }
        cleanPendingCall() {
            if (this._callIdToRemove.size > 0) {
                new Set(this._callIdToRemove).forEach((callId) => {
                    this._log.info(`Cancel pending call ${callId}`);
                    this._apiMethods.forceCancel(callId).result.subscribe(() => {
                        this._callIdToRemove.delete(callId);
                    }, (err) => {
                        this._log.error(`Error on cancel pending call ${callId}`, err);
                    });
                    this._apiMethods.removeCallFromUserInteraction(callId).result.subscribe({
                        error: (err) => {
                            this._log.error(`Error on removeCallFromUserInteraction of pending call ${callId}`, err);
                        },
                    });
                });
            }
        }
        cancelCallRequest(callId) {
            var _a;
            if (this._connections.has(callId)) {
                this._callIdToRemove.add(callId);
                setTimeout((channelType) => {
                    this.publishControlMessage({
                        callId: callId,
                        device: ExtenType.WEBRTC,
                        direction: CallDirection.outbound,
                        state: CallState.IDLE,
                        _isFromServer: false,
                        _channelType: channelType,
                        _realChannelType: channelType,
                    });
                }, 0, ((_a = this._connections.get(callId)) === null || _a === void 0 ? void 0 : _a.channelType) || ChannelType.PhoneCall);
                return true;
            }
            else {
                return false;
            }
        }
        destroyCall(callId, dialParam, error) {
            return __awaiter(this, void 0, void 0, function* () {
                const call = this.retriveCall(callId);
                const deviceIsApp = (call && call.deviceIsApp) || (dialParam && dialParam.isForApp());
                if (call || deviceIsApp) {
                    if (dialParam && error && error instanceof WebAPI) {
                        setTimeout(() => {
                            if (deviceIsApp || (call && call.signalingState && call.signalingState === CallState.NEW_OUTBOUND && !call.realState)) {
                                this.publishControlMessage({
                                    callId: callId,
                                    device: dialParam.params.fromDevice,
                                    direction: CallDirection.outbound,
                                    state: CallState.IDLE,
                                    _isFromServer: false,
                                    _channelType: dialParam.params.channelId,
                                    _realChannelType: dialParam.params.channelId,
                                });
                            }
                        });
                    }
                    if (call) {
                        yield call.close();
                        this._connections.delete(callId);
                    }
                    if (deviceIsApp || (call && call.channelType === ChannelType.PhoneCall && !(call instanceof CallChecker))) {
                        this._apiMethods.removeCallFromUserInteraction(callId).result.subscribe(null, (err) => {
                            this._log.error("Error on removeCallFromUserInteraction", err);
                        });
                    }
                    if (this._connections.size === 1) {
                        this.phoneSignal.convertRingAdvertisingToRingIfNeedle();
                    }
                    return true;
                }
                else {
                    return false;
                }
            });
        }
    }
    class TLinkLogger extends LogProvider {
        constructor(manager) {
            super();
            this.manager = manager;
            this._logger = Log$1.of("webrtc:tlink", manager.client);
        }
        get logLevel() {
            return this.manager.client.logger.logLevel;
        }
        log(logItem) {
            this._logger.logWithTimestamp(logItem.level, logItem.timestamp, logItem.message);
        }
    }

    exports.Device = void 0;
    (function (Device) {
        Device.PKG = "device";
    })(exports.Device || (exports.Device = {}));

    class DeviceWebrtcMedia extends EventEmitter {
        constructor(
        deviceWebrtc) {
            super(`${exports.Device.PKG}webrtc:media`, deviceWebrtc.phone.client);
            this.deviceWebrtc = deviceWebrtc;
            deviceWebrtc.api.device.status.subscribe((deviceNotification) => {
                this.emit("device_change", deviceNotification.status, deviceNotification.devices);
            });
            deviceWebrtc.api.device.selfManagedDeviceActivity.subscribe((notification) => {
                this.emit("use_device_when_device_change", notification.deviceToUpdate, notification.ejectedDevice);
            });
            deviceWebrtc.api.device.addedDeviceOnSelfManagedMode.subscribe((notification) => {
                this.emit("unused_device_added", notification);
            });
        }
        static get deviceIdToIgnore() {
            return WebrtDeviceManager.deviceIdToIgnore;
        }
        get audioInput() {
            return this.deviceWebrtc.api.device.audioInput;
        }
        get audioOutput() {
            return this.deviceWebrtc.api.device.audioOutput;
        }
        get videoInput() {
            return this.deviceWebrtc.api.device.videoInput;
        }
        get audioSignalOutput() {
            return this.deviceWebrtc.api.device.audioSignalOutput;
        }
        useDevice(audioInput, audioOutput, videoInput, audioSignalOutput, audioNotificationOutput) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.deviceWebrtc.api.device.setMediaDevice(audioInput, videoInput, audioOutput, audioSignalOutput, audioNotificationOutput);
            });
        }
        getMediaDevice(startMedia, acquireAudio = true, acquireVideo = true) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.deviceWebrtc.api.device.getMediaDevice(startMedia, acquireAudio, acquireVideo);
            });
        }
        checkDevicePermission(permission) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.deviceWebrtc.api.device.checkDevicePermission(permission);
            });
        }
        testMediaDevice(audioInput, videoInput, audioOutput, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                const test = yield this.deviceWebrtc.api.device.testMediaDevice(audioInput, videoInput, audioOutput, videoContainer);
                return new DeviceWebrtcMedia.MediaDeviceTest(this.deviceWebrtc, test);
            });
        }
    }
    DeviceWebrtcMedia.device_change = "device_change";
    DeviceWebrtcMedia.use_device_when_device_change = "use_device_when_device_change";
    DeviceWebrtcMedia.unused_device_added = "unused_device_added";
    (function (DeviceWebrtcMedia) {
        class MediaDeviceTest extends EventEmitter {
            constructor(deviceWebrtc,
            test) {
                super(`${exports.Device.PKG}webrtc:mediatest`, deviceWebrtc.client);
                this.test = test;
                test.audioLevel.subscribe((level) => {
                    this.emit("audio_level", level);
                });
            }
            start() {
                return __awaiter(this, void 0, void 0, function* () {
                    return this.test.start();
                });
            }
            stop() {
                return __awaiter(this, void 0, void 0, function* () {
                    return this.test.stop();
                });
            }
            changeAudioVideoInput(audioInput, videoInput) {
                return __awaiter(this, void 0, void 0, function* () {
                    return this.test.changeAudioVideoInput(audioInput, videoInput);
                });
            }
            changeAudioOutput(audioOutput) {
                return __awaiter(this, void 0, void 0, function* () {
                    return this.test.changeAudioOutput(audioOutput);
                });
            }
        }
        DeviceWebrtcMedia.MediaDeviceTest = MediaDeviceTest;
    })(DeviceWebrtcMedia || (DeviceWebrtcMedia = {}));

    class DeviceWebrtc {
        constructor(
        _phone,
        label,
        exten) {
            this._phone = _phone;
            this.label = label;
            this.exten = exten;
            this.type = exports.C.LineType.WEBRTC;
            this.configuration = new DeviceWebrtc.Configuration(this);
            this.media = new DeviceWebrtcMedia(this);
        }
        get client() {
            return this._phone.client;
        }
        get phone() {
            return this._phone;
        }
        get api() {
            return this._phone.client.api.webrtc;
        }
        dialAudio(phoneNumber, param) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.dial(phoneNumber, param, { media: { audio: true, video: false } });
            });
        }
        dialVideo(phoneNumber, param, videoContainer) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.dial(phoneNumber, param, { media: { audio: true, video: true } }, videoContainer);
            });
        }
        dial(phoneNumber, dialParamValue, _dialParam, videoContainer) {
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function* () {
                const contactIdentifier = {
                    type: AddressBookContactType.UNKNOWN,
                    value: phoneNumber,
                };
                const param = dialParamValue;
                if (param === null || param === void 0 ? void 0 : param.contactIdentifier) {
                    Object.assign(contactIdentifier, param.contactIdentifier);
                }
                const dialParam = Object.assign({
                    fromDeviceType: ExtenType.WEBRTC,
                    fromDevice: this.exten,
                    accessCode: param === null || param === void 0 ? void 0 : param.accessCode,
                    privateCall: param === null || param === void 0 ? void 0 : param.privateCall,
                    serviceCode: param === null || param === void 0 ? void 0 : param.serviceCode,
                    note1: param === null || param === void 0 ? void 0 : param.note1,
                    note2: param === null || param === void 0 ? void 0 : param.note2,
                    channelId: ChannelType.PhoneCall,
                    contact: contactIdentifier,
                }, _dialParam);
                if (param === null || param === void 0 ? void 0 : param.contact) {
                    contactIdentifier.uid = param.contact.id;
                    contactIdentifier.type = (_a = param.contact.addressBookContactType) !== null && _a !== void 0 ? _a : contactIdentifier.type;
                    if (InternalUserContact.check(param.contact)) {
                        const contactIdentifierWithUser = contactIdentifier;
                        contactIdentifierWithUser.username = param.contact.data.username;
                        contactIdentifierWithUser.surname = param.contact.data.surname;
                        contactIdentifierWithUser.name = param.contact.data.name;
                    }
                }
                if ((_c = (_b = dialParam.contact) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : null) {
                    try {
                        const response = yield this.client.api.methods.dial(dialParam, videoContainer);
                        if (!response) {
                            throw "Unable to dial, server response is empty";
                        }
                    }
                    catch (e) {
                        if (e instanceof DeviceRequestFailed) {
                            throw "TVox Client not logged";
                        }
                        else {
                            throw e;
                        }
                    }
                }
                else {
                    throw "Unable to dial, phoneNumber is empty";
                }
            });
        }
    }
    (function (DeviceWebrtc) {
        class Configuration {
            constructor(device) {
                this.device = device;
                this._options = new Configuration.Options(device.client.api.webrtc.options);
            }
            get options() {
                return this._options;
            }
            get media() {
                return this.device.client.api.webrtc.device;
            }
        }
        DeviceWebrtc.Configuration = Configuration;
        (function (Configuration) {
            class Options {
                constructor(config) {
                    this.config = config;
                }
                get iceServers() {
                    return this.config.iceServers;
                }
                set iceServers(iceServers) {
                    this.config.iceServers = iceServers;
                }
                get trickleIcePolicy() {
                    return this.config.trickleIcePolicy;
                }
                set trickleIcePolicy(trickleIcePolicy) {
                    this.config.trickleIcePolicy = trickleIcePolicy;
                }
                get iceGatherPolicy() {
                    return this.config.iceGatherPolicy;
                }
                set iceGatherPolicy(iceGatherPolicy) {
                    this.config.iceGatherPolicy = iceGatherPolicy;
                }
                get immediateRingback() {
                    return this.config.immediateRingback;
                }
                set immediateRingback(immediateRingback) {
                    this.config.immediateRingback = immediateRingback;
                }
                get connectionTimeout() {
                    return this.config.connectionTimeout;
                }
                set connectionTimeout(connectionTimeout) {
                    this.config.connectionTimeout = connectionTimeout;
                }
                get deadStreamTimeout() {
                    return this.config.deadStreamTimeout;
                }
                set deadStreamTimeout(deadStreamTimeout) {
                    this.config.deadStreamTimeout = deadStreamTimeout;
                }
                get mediaConfiguration() {
                    return this.config.mediaConfiguration;
                }
            }
            Configuration.Options = Options;
        })(Configuration = DeviceWebrtc.Configuration || (DeviceWebrtc.Configuration = {}));
    })(DeviceWebrtc || (DeviceWebrtc = {}));

    class Phone extends EventEmitter {
        constructor(
        _client) {
            super(Phone.PKG, _client);
            this._client = _client;
            this._state = Phone.Status.ERROR_NO_DEVICE_AVAILABLE;
            this._tvoxClientState = Phone.TVoxClientState.UNKNOWN;
            this._tvoxClientStateDetail = { lastUpdate: new Date() };
            this._clientStatusSubject = new Subject();
            this.availableDevice = [];
            this._device = null;
            this._deviceChosen = null;
            this._calls = new Map();
            this._client.api.channelNotification.subscribe((() => {
                let callNotificationHandlerChain = Promise.resolve();
                return (channelEvent) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        yield callNotificationHandlerChain;
                    }
                    finally {
                        callNotificationHandlerChain = this.handleChannelNotification(channelEvent);
                    }
                });
            })());
            this.clientStatusNotification = new NotificationManager(this._client.api, "clientStatusNotify", (requestTimeout) => this._client.api.methods.startClientStatusNotify(requestTimeout), this._clientStatusSubject, (clientStatus) => clientStatus);
            this._clientStatusSubject.subscribe((clientStatus) => {
                this._tvoxClientStateDetail = {
                    lastUpdate: new Date(clientStatus.currentTime),
                    platform: clientStatus.platform === Platform$1.EXE ? Phone.TVoxClientPlatform.APPLICATION : Phone.TVoxClientPlatform.BROWSER,
                    userAgent: clientStatus.userAgent,
                };
                switch (clientStatus.status) {
                    case ClientStatus.INACTIVE:
                        this._tvoxClientState = Phone.TVoxClientState.INACTIVE;
                        break;
                    case ClientStatus.ACTIVE:
                        this._tvoxClientState = Phone.TVoxClientState.ACTIVE;
                        break;
                    case ClientStatus.ACTIVATING:
                        this._tvoxClientState = Phone.TVoxClientState.ACTIVATING;
                        break;
                    case ClientStatus.DISCONNETING:
                        this._tvoxClientState = Phone.TVoxClientState.DISCONNETING;
                        break;
                }
                if (this.managedByTVoxClient && this._tvoxClientState === Phone.TVoxClientState.ACTIVE && this._tvoxClientStateDetail.platform === Phone.TVoxClientPlatform.BROWSER) {
                    this.log.warn("-- WARNING -- remote control of TVox Client may not work properly on browsers");
                }
                this.emit("tvoxclient_state_change", this._tvoxClientState, this._tvoxClientStateDetail);
            });
            this._client.commandReceived$
                .pipe(filter((data) => {
                switch (data.command.command) {
                    case ClientCommandRequest.DIAL:
                        return true;
                    default:
                        return false;
                }
            }), concatMap(({ command, subscriber }) => __awaiter(this, void 0, void 0, function* () {
                const result = yield (() => __awaiter(this, void 0, void 0, function* () {
                    var _a;
                    switch (command.command) {
                        case ClientCommandRequest.DIAL:
                            try {
                                if (!this.device) {
                                    throw new Error("No active device, dial denied");
                                }
                                const dialCommand = command;
                                const dialParam = {
                                    accessCode: dialCommand.accessCode,
                                    privateCall: dialCommand.privateCall,
                                    serviceCode: dialCommand.serviceCode,
                                    note1: dialCommand.note1,
                                    note2: dialCommand.note2,
                                    contactIdentifier: dialCommand.contact,
                                };
                                if (this._device instanceof DeviceSip) {
                                    yield this._device.dial(dialCommand.number, dialParam);
                                }
                                else if (this.device instanceof DeviceWebrtc) {
                                    yield this.device.dialAudio(dialCommand.number, dialParam);
                                }
                                else {
                                    throw new Error(`Device ${(_a = this._device) === null || _a === void 0 ? void 0 : _a.type} cannot manage DialCommand`);
                                }
                                return { result: ClientCommandResult.OK };
                            }
                            catch (e) {
                                return { result: ClientCommandResult.FAILED, resultMessage: e instanceof Error ? e.message : typeof e === "string" ? e : "Unknown error on dial" };
                            }
                        default:
                            return { result: ClientCommandResult.FAILED, resultMessage: "Command not implemented" };
                    }
                }))();
                subscriber.next(result);
                subscriber.complete();
            })), catchError((err, obs) => {
                this.log.error("Action error: ", err);
                return obs;
            }))
                .subscribe();
        }
        get managedByTVoxClient() {
            return !this._client.api.phoneManagerActive;
        }
        set managedByTVoxClient(managedByTVoxClient) {
            this._client.api.phoneManagerActive = !!!managedByTVoxClient;
        }
        get state() {
            return this._state;
        }
        set state(state) {
            this._state = state;
        }
        get tvoxClientState() {
            return this._tvoxClientState;
        }
        get tvoxClientStateDetail() {
            return this._tvoxClientStateDetail;
        }
        get device() {
            return this._device;
        }
        set device(device) {
            this._device = device;
        }
        get client() {
            return this._client;
        }
        initFromApiData(userDetail) {
            return __awaiter(this, void 0, void 0, function* () {
                this.clientStatusNotification.start();
                if (userDetail.devices) {
                    const availableDevice = userDetail.devices
                        .filter((d) => { var _a; return d.type === ExtenType.SIP || (d.type === ExtenType.WEBRTC && !((_a = d.extension) === null || _a === void 0 ? void 0 : _a.startsWith("_app_"))); })
                        .map((d) => {
                        return d.type === ExtenType.SIP ? new DeviceSip(this, d.label, d.extension) : new DeviceWebrtc(this, d.label, d.extension);
                    })
                        .filter((d) => d != null);
                    this.availableDevice.forEach((d, index, data) => {
                        if (!availableDevice.find((ds) => ds.type === d.type && ds.exten === d.exten)) {
                            data.splice(index, 1);
                        }
                    });
                    availableDevice
                        .filter((d) => !this.availableDevice.find((ds) => ds.type === d.type && ds.exten === d.exten))
                        .forEach((d) => {
                        this.availableDevice.push(d);
                    });
                }
                yield this.checkDeviceChosen(userDetail.chosenDeviceTypeByClient, userDetail.chosenDeviceByClient);
                yield this.checkDeviceAfterApiData();
            });
        }
        initFromApiDataUpdate(userDetail) {
            return __awaiter(this, void 0, void 0, function* () {
                const userDetailHasDeviceToAnalize = userDetail.devices && userDetail.devices.length;
                if (userDetailHasDeviceToAnalize) {
                    userDetail.devices.forEach((device) => {
                        var _a;
                        if (device.type === ExtenType.SIP || (device.type === ExtenType.WEBRTC && !((_a = device.extension) === null || _a === void 0 ? void 0 : _a.startsWith("_app_")))) {
                            const type = device.type === ExtenType.SIP ? exports.C.LineType.SIP : exports.C.LineType.WEBRTC;
                            const fromAvailableDevice = this.availableDevice.find((d) => d.type === type && d.exten === device.extension);
                            if (fromAvailableDevice) {
                                if (device.deleted) {
                                    this._calls.forEach((call) => {
                                        if (call.device === fromAvailableDevice) {
                                            try {
                                                call.terminate();
                                            }
                                            catch (e) { }
                                        }
                                    });
                                    this.availableDevice.splice(this.availableDevice.indexOf(fromAvailableDevice), 1);
                                }
                            }
                            else {
                                this.availableDevice.push(type === exports.C.LineType.SIP ? new DeviceSip(this, device.label, device.extension) : new DeviceWebrtc(this, device.label, device.extension));
                            }
                        }
                    });
                    yield this.checkDeviceChosen(userDetail.chosenDeviceTypeByClient, userDetail.chosenDeviceByClient);
                    yield this.checkDeviceAfterApiData();
                }
                if (!userDetailHasDeviceToAnalize) {
                    yield this.checkDeviceChosen(userDetail.chosenDeviceTypeByClient, userDetail.chosenDeviceByClient);
                }
            });
        }
        checkDeviceChosen(type, device) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                if (type && device) {
                    const lineType = type === ExtenType.SIP ? exports.C.LineType.SIP : exports.C.LineType.WEBRTC;
                    const deviceByClient = (_a = this.availableDevice.find((ds) => ds.type === lineType && ds.exten === device)) !== null && _a !== void 0 ? _a : null;
                    if (deviceByClient) {
                        const changeDevice = this._deviceChosen ? !(deviceByClient.type === this._deviceChosen.type && deviceByClient.exten === this._deviceChosen.exten) : true;
                        if (changeDevice) {
                            yield this.useDevice(deviceByClient);
                            const previousDeviceByClient = this._deviceChosen;
                            this._deviceChosen = deviceByClient;
                            this.emit("device_change", deviceByClient, previousDeviceByClient);
                        }
                    }
                }
            });
        }
        checkDeviceAfterApiData() {
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function* () {
                if (this.availableDevice.length) {
                    if (this.device ? !this.availableDevice.find((d) => { var _a; return d.type === ((_a = this.device) === null || _a === void 0 ? void 0 : _a.type) && d.exten === this.device.exten; }) : true) {
                        yield this.useDevice((_c = (_b = (_a = (this.device ? (this.availableDevice.indexOf(this.device) >= 0 ? this.device : undefined) : undefined)) !== null && _a !== void 0 ? _a : this.availableDevice.find((d) => d.type === exports.C.LineType.SIP)) !== null && _b !== void 0 ? _b : this.availableDevice.find((d) => d.type === exports.C.LineType.WEBRTC)) !== null && _c !== void 0 ? _c : this.availableDevice[0]);
                    }
                }
                else {
                    this.device = null;
                    this.state = Phone.Status.ERROR_NO_DEVICE_AVAILABLE;
                }
            });
        }
        handleChannelNotification(channelEvent) {
            return __awaiter(this, void 0, void 0, function* () {
                if (ChannelType.PhoneCall !== channelEvent.channel) {
                    return;
                }
                const callInfo = channelEvent.callInfo;
                let call = this.getCall(callInfo.callId);
                if (call) {
                    yield call.updateFromApi(channelEvent, true, false);
                    if (channelEvent.isGeneratedByServer() && callInfo.state === CallState.IDLE) {
                        setTimeout(() => {
                            if (callInfo.callId && this._calls && this._calls.has(callInfo.callId)) {
                                this._calls.delete(callInfo.callId);
                            }
                        }, 2000);
                    }
                }
                else if (callInfo.state !== CallState.IDLE && callInfo.deviceType && callInfo.direction) {
                    const lineType = exports.C.LineType[callInfo.deviceType.toUpperCase()];
                    if (lineType) {
                        const direction = Call$1.Direction[callInfo.direction.toUpperCase()];
                        const deviceOfCall = this.availableDevice.find((d) => d.type === lineType && d.exten === callInfo.device);
                        if (deviceOfCall) {
                            switch (lineType) {
                                case exports.C.LineType.SIP:
                                    call = new CallSip(deviceOfCall, callInfo.callId, direction);
                                    break;
                                case exports.C.LineType.WEBRTC:
                                    call = new CallWebrtc(deviceOfCall, callInfo.callId, direction);
                                    break;
                            }
                        }
                    }
                    if (call) {
                        let previousConnected = false;
                        this._calls.set(call.callId, call);
                        const callInfoState = callInfo.state;
                        if (call.direction === Call$1.Direction.INBOUND && callInfoState !== CallState.NEW_INBOUND) {
                            callInfo.state = CallState.NEW_INBOUND;
                            previousConnected = true;
                        }
                        else if (call.direction === Call$1.Direction.OUTBOUND && callInfoState !== CallState.NEW_OUTBOUND) {
                            callInfo.state = CallState.NEW_OUTBOUND;
                            previousConnected = true;
                        }
                        yield call.updateFromApi(channelEvent, false, false);
                        this.emit("newcall", call, { previousConnected });
                        if (callInfo.state != callInfoState) {
                            yield call.updateFromApi(new ChannelEvent(channelEvent.channel, Object.assign(Object.assign({}, callInfo), { state: callInfoState }), channelEvent.generatedBy), true, false);
                        }
                    }
                }
            });
        }
        useDevice(device) {
            return __awaiter(this, void 0, void 0, function* () {
                if (device) {
                    if (device instanceof DeviceWebrtc) {
                        if (this._client.api.webrtc && !this._client.api.webrtc.enable) {
                            yield this._client.api.webrtc.start();
                        }
                    }
                    else {
                        if (this._client.api.webrtc && this._client.api.webrtc.enable) {
                            this._client.api.webrtc.stop();
                        }
                    }
                    if (this.client.user.info.profile) {
                        if (this._deviceChosen !== device) {
                            yield this.client.api.methods.useDevice(device.type === exports.C.LineType.SIP ? ExtenType.SIP : ExtenType.WEBRTC, device.exten, false);
                        }
                    }
                    this.device = device;
                    this.state = Phone.Status.READY;
                    return true;
                }
                this.state = Phone.Status.ERROR_NO_DEVICE;
                return false;
            });
        }
        getCall(id) {
            var _a;
            return (_a = this._calls.get(id)) !== null && _a !== void 0 ? _a : null;
        }
    }
    Phone.newcall = "newcall";
    Phone.tvoxclient_state_change = "tvoxclient_state_change";
    Phone.device_change = "device_change";
    (function (Phone) {
        Phone.PKG = "phone";
        (function (Status) {
            Status["READY"] = "READY";
            Status["ERROR_NO_DEVICE_AVAILABLE"] = "ERROR_NO_DEVICE_AVAILABLE";
            Status["ERROR_NO_DEVICE"] = "ERROR_NO_DEVICE";
        })(Phone.Status || (Phone.Status = {}));
        (function (TVoxClientState) {
            TVoxClientState["UNKNOWN"] = "UNKNOWN";
            TVoxClientState["ACTIVE"] = "ACTIVE";
            TVoxClientState["INACTIVE"] = "INACTIVE";
            TVoxClientState["ACTIVATING"] = "ACTIVATING";
            TVoxClientState["DISCONNETING"] = "DISCONNETING";
        })(Phone.TVoxClientState || (Phone.TVoxClientState = {}));
        (function (TVoxClientPlatform) {
            TVoxClientPlatform["BROWSER"] = "BROWSER";
            TVoxClientPlatform["APPLICATION"] = "APPLICATION";
        })(Phone.TVoxClientPlatform || (Phone.TVoxClientPlatform = {}));
    })(Phone || (Phone = {}));

    class Transport extends EventEmitter {
        constructor(
        client) {
            super(Transport.PKG, client);
            this.client = client;
            this._state = Transport.Status.DISCONNECTED;
            this.client.api.connectionEvent.subscribe((event) => {
                if (event.connected) {
                    this._state = Transport.Status.CONNECTED;
                    this.emit("connect");
                }
                else {
                    this._state = Transport.Status.DISCONNECTED;
                    this.emit("disconnect");
                }
            });
        }
        get state() {
            return this._state;
        }
        connect() {
            this.client.api.transport.connect();
        }
        disconnect() {
            this.client.api.disconnect();
        }
        isConnected() {
            return this.state === Transport.Status.CONNECTED;
        }
    }
    Transport.connect = "connect";
    Transport.disconnect = "disconnect";
    (function (Transport) {
        Transport.PKG = "transport";
        (function (Status) {
            Status["CONNECTED"] = "CONNECTED";
            Status["DISCONNECTED"] = "DISCONNECTED";
        })(Transport.Status || (Transport.Status = {}));
    })(Transport || (Transport = {}));

    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 jszip_minExports = {};
    var jszip_min = {
      get exports(){ return jszip_minExports; },
      set exports(v){ jszip_minExports = v; },
    };

    (function (module, exports) {
    	!function(e){module.exports=e();}(function(){return function s(a,o,h){function u(r,e){if(!o[r]){if(!a[r]){var t="function"==typeof commonjsRequire&&commonjsRequire;if(!e&&t)return t(r,!0);if(l)return l(r,!0);var n=new Error("Cannot find module '"+r+"'");throw n.code="MODULE_NOT_FOUND",n}var i=o[r]={exports:{}};a[r][0].call(i.exports,function(e){var t=a[r][1][e];return u(t||e)},i,i.exports,s,a,o,h);}return o[r].exports}for(var l="function"==typeof commonjsRequire&&commonjsRequire,e=0;e<h.length;e++)u(h[e]);return u}({1:[function(e,t,r){var d=e("./utils"),c=e("./support"),p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(e){for(var t,r,n,i,s,a,o,h=[],u=0,l=e.length,f=l,c="string"!==d.getTypeOf(e);u<e.length;)f=l-u,n=c?(t=e[u++],r=u<l?e[u++]:0,u<l?e[u++]:0):(t=e.charCodeAt(u++),r=u<l?e.charCodeAt(u++):0,u<l?e.charCodeAt(u++):0),i=t>>2,s=(3&t)<<4|r>>4,a=1<f?(15&r)<<2|n>>6:64,o=2<f?63&n:64,h.push(p.charAt(i)+p.charAt(s)+p.charAt(a)+p.charAt(o));return h.join("")},r.decode=function(e){var t,r,n,i,s,a,o=0,h=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var l,f=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===p.charAt(64)&&f--,e.charAt(e.length-2)===p.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(l=c.uint8array?new Uint8Array(0|f):new Array(0|f);o<e.length;)t=p.indexOf(e.charAt(o++))<<2|(i=p.indexOf(e.charAt(o++)))>>4,r=(15&i)<<4|(s=p.indexOf(e.charAt(o++)))>>2,n=(3&s)<<6|(a=p.indexOf(e.charAt(o++))),l[h++]=t,64!==s&&(l[h++]=r),64!==a&&(l[h++]=n);return l};},{"./support":30,"./utils":32}],2:[function(e,t,r){var n=e("./external"),i=e("./stream/DataWorker"),s=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,r,n,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=i;}o.prototype={getContentWorker:function(){var e=new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,r){return e.pipe(new s).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",t)},t.exports=o;},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){var n=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},r.DEFLATE=e("./flate");},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){var n=e("./utils");var o=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e;}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a<s;a++)e=e>>>8^i[255&(e^t[a])];return -1^e}(0|t,e,e.length,0):function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a<s;a++)e=e>>>8^i[255&(e^t.charCodeAt(a))];return -1^e}(0|t,e,e.length,0):0};},{"./utils":32}],5:[function(e,t,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null;},{}],6:[function(e,t,r){var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n};},{lie:37}],7:[function(e,t,r){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,i=e("pako"),s=e("./utils"),a=e("./stream/GenericWorker"),o=n?"uint8array":"array";function h(e,t){a.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={};}r.magic="\b\0",s.inherits(h,a),h.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,e.data),!1);},h.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0);},h.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null;},h.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta});};},r.compressWorker=function(e){return new h("Deflate",e)},r.uncompressWorker=function(){return new h("Inflate",{})};},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,r){function A(e,t){var r,n="";for(r=0;r<t;r++)n+=String.fromCharCode(255&e),e>>>=8;return n}function n(e,t,r,n,i,s){var a,o,h=e.file,u=e.compression,l=s!==O.utf8encode,f=I.transformTo("string",s(h.name)),c=I.transformTo("string",O.utf8encode(h.name)),d=h.comment,p=I.transformTo("string",s(d)),m=I.transformTo("string",O.utf8encode(d)),_=c.length!==h.name.length,g=m.length!==d.length,b="",v="",y="",w=h.dir,k=h.date,x={crc32:0,compressedSize:0,uncompressedSize:0};t&&!r||(x.crc32=e.crc32,x.compressedSize=e.compressedSize,x.uncompressedSize=e.uncompressedSize);var S=0;t&&(S|=8),l||!_&&!g||(S|=2048);var z=0,C=0;w&&(z|=16),"UNIX"===i?(C=798,z|=function(e,t){var r=e;return e||(r=t?16893:33204),(65535&r)<<16}(h.unixPermissions,w)):(C=20,z|=function(e){return 63&(e||0)}(h.dosPermissions)),a=k.getUTCHours(),a<<=6,a|=k.getUTCMinutes(),a<<=5,a|=k.getUTCSeconds()/2,o=k.getUTCFullYear()-1980,o<<=4,o|=k.getUTCMonth()+1,o<<=5,o|=k.getUTCDate(),_&&(v=A(1,1)+A(B(f),4)+c,b+="up"+A(v.length,2)+v),g&&(y=A(1,1)+A(B(p),4)+m,b+="uc"+A(y.length,2)+y);var E="";return E+="\n\0",E+=A(S,2),E+=u.magic,E+=A(a,2),E+=A(o,2),E+=A(x.crc32,4),E+=A(x.compressedSize,4),E+=A(x.uncompressedSize,4),E+=A(f.length,2),E+=A(b.length,2),{fileRecord:R.LOCAL_FILE_HEADER+E+f+b,dirRecord:R.CENTRAL_FILE_HEADER+A(C,2)+E+A(p.length,2)+"\0\0\0\0"+A(z,4)+A(n,4)+f+b+p}}var I=e("../utils"),i=e("../stream/GenericWorker"),O=e("../utf8"),B=e("../crc32"),R=e("../signature");function s(e,t,r,n){i.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[];}I.inherits(s,i),s.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,i.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-n-1))/r:100}}));},s.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}});}else this.accumulate=!0;},s.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,r=n(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:function(e){return R.DATA_DESCRIPTOR+A(e.crc32,4)+A(e.compressedSize,4)+A(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null;},s.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var r=this.bytesWritten-e,n=function(e,t,r,n,i){var s=I.transformTo("string",i(n));return R.CENTRAL_DIRECTORY_END+"\0\0\0\0"+A(e,2)+A(e,2)+A(t,4)+A(r,4)+A(s.length,2)+s}(this.dirRecords.length,r,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}});},s.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume();},s.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e);}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end();}),e.on("error",function(e){t.error(e);}),this},s.prototype.resume=function(){return !!i.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},s.prototype.error=function(e){var t=this._sources;if(!i.prototype.error.call(this,e))return !1;for(var r=0;r<t.length;r++)try{t[r].error(e);}catch(e){}return !0},s.prototype.lock=function(){i.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock();},t.exports=s;},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,r){var u=e("../compressions"),n=e("./ZipFileWorker");r.generateWorker=function(e,a,t){var o=new n(a.streamFiles,t,a.platform,a.encodeFileName),h=0;try{e.forEach(function(e,t){h++;var r=function(e,t){var r=e||t,n=u[r];if(!n)throw new Error(r+" is not a valid compression method !");return n}(t.options.compression,a.compression),n=t.options.compressionOptions||a.compressionOptions||{},i=t.dir,s=t.date;t._compressWorker(r,n).withStreamInfo("file",{name:e,dir:i,date:s,comment:t.comment||"",unixPermissions:t.unixPermissions,dosPermissions:t.dosPermissions}).pipe(o);}),o.entriesCount=h;}catch(e){o.error(e);}return o};},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,r){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new n;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e};}(n.prototype=e("./object")).loadAsync=e("./load"),n.support=e("./support"),n.defaults=e("./defaults"),n.version="3.10.1",n.loadAsync=function(e,t){return (new n).loadAsync(e,t)},n.external=e("./external"),t.exports=n;},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,r){var u=e("./utils"),i=e("./external"),n=e("./utf8"),s=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function f(n){return new i.Promise(function(e,t){var r=n.decompressed.getContentWorker().pipe(new a);r.on("error",function(e){t(e);}).on("end",function(){r.streamInfo.crc32!==n.decompressed.crc32?t(new Error("Corrupted zip : CRC32 mismatch")):e();}).resume();})}t.exports=function(e,o){var h=this;return o=u.extend(o||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:n.utf8decode}),l.isNode&&l.isStream(e)?i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):u.prepareContent("the loaded zip file",e,!0,o.optimizedBinaryString,o.base64).then(function(e){var t=new s(o);return t.load(e),t}).then(function(e){var t=[i.Promise.resolve(e)],r=e.files;if(o.checkCRC32)for(var n=0;n<r.length;n++)t.push(f(r[n]));return i.Promise.all(t)}).then(function(e){for(var t=e.shift(),r=t.files,n=0;n<r.length;n++){var i=r[n],s=i.fileNameStr,a=u.resolve(i.fileNameStr);h.file(a,i.decompressed,{binary:!0,optimizedBinaryString:!0,date:i.date,dir:i.dir,comment:i.fileCommentStr.length?i.fileCommentStr:null,unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions,createFolders:o.createFolders}),i.dir||(h.file(a).unsafeOriginalName=s);}return t.zipComment.length&&(h.comment=t.zipComment),h})};},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,r){var n=e("../utils"),i=e("../stream/GenericWorker");function s(e,t){i.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t);}n.inherits(s,i),s.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}});}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e);}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end();});},s.prototype.pause=function(){return !!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return !!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=s;},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,r){var i=e("readable-stream").Readable;function n(e,t,r){i.call(this,t),this._helper=e;var n=this;e.on("data",function(e,t){n.push(e)||n._helper.pause(),r&&r(t);}).on("error",function(e){n.emit("error",e);}).on("end",function(){n.push(null);});}e("../utils").inherits(n,i),n.prototype._read=function(){this._helper.resume();},t.exports=n;},{"../utils":32,"readable-stream":16}],14:[function(e,t,r){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}};},{}],15:[function(e,t,r){function s(e,t,r){var n,i=u.getTypeOf(t),s=u.extend(r||{},f);s.date=s.date||new Date,null!==s.compression&&(s.compression=s.compression.toUpperCase()),"string"==typeof s.unixPermissions&&(s.unixPermissions=parseInt(s.unixPermissions,8)),s.unixPermissions&&16384&s.unixPermissions&&(s.dir=!0),s.dosPermissions&&16&s.dosPermissions&&(s.dir=!0),s.dir&&(e=g(e)),s.createFolders&&(n=_(e))&&b.call(this,n,!0);var a="string"===i&&!1===s.binary&&!1===s.base64;r&&void 0!==r.binary||(s.binary=!a),(t instanceof c&&0===t.uncompressedSize||s.dir||!t||0===t.length)&&(s.base64=!1,s.binary=!0,t="",s.compression="STORE",i="string");var o=null;o=t instanceof c||t instanceof l?t:p.isNode&&p.isStream(t)?new m(e,t):u.prepareContent(e,t,s.binary,s.optimizedBinaryString,s.base64);var h=new d(e,o,s);this.files[e]=h;}var i=e("./utf8"),u=e("./utils"),l=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),f=e("./defaults"),c=e("./compressedObject"),d=e("./zipObject"),o=e("./generate"),p=e("./nodejsUtils"),m=e("./nodejs/NodejsStreamInputAdapter"),_=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},g=function(e){return "/"!==e.slice(-1)&&(e+="/"),e},b=function(e,t){return t=void 0!==t?t:f.createFolders,e=g(e),this.files[e]||s.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function h(e){return "[object RegExp]"===Object.prototype.toString.call(e)}var n={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,r,n;for(t in this.files)n=this.files[t],(r=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(r,n);},filter:function(r){var n=[];return this.forEach(function(e,t){r(e,t)&&n.push(t);}),n},file:function(e,t,r){if(1!==arguments.length)return e=this.root+e,s.call(this,e,t,r),this;if(h(e)){var n=e;return this.filter(function(e,t){return !t.dir&&n.test(e)})}var i=this.files[this.root+e];return i&&!i.dir?i:null},folder:function(r){if(!r)return this;if(h(r))return this.filter(function(e,t){return t.dir&&r.test(e)});var e=this.root+r,t=b.call(this,e),n=this.clone();return n.root=t.name,n},remove:function(r){r=this.root+r;var e=this.files[r];if(e||("/"!==r.slice(-1)&&(r+="/"),e=this.files[r]),e&&!e.dir)delete this.files[r];else for(var t=this.filter(function(e,t){return t.name.slice(0,r.length)===r}),n=0;n<t.length;n++)delete this.files[t[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,r={};try{if((r=u.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:i.utf8encode})).type=r.type.toLowerCase(),r.compression=r.compression.toUpperCase(),"binarystring"===r.type&&(r.type="string"),!r.type)throw new Error("No output type specified.");u.checkSupport(r.type),"darwin"!==r.platform&&"freebsd"!==r.platform&&"linux"!==r.platform&&"sunos"!==r.platform||(r.platform="UNIX"),"win32"===r.platform&&(r.platform="DOS");var n=r.comment||this.comment||"";t=o.generateWorker(this,r,n);}catch(e){(t=new l("error")).error(e);}return new a(t,r.type||"string",r.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return (e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=n;},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,r){t.exports=e("stream");},{stream:void 0}],17:[function(e,t,r){var n=e("./DataReader");function i(e){n.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t];}e("../utils").inherits(i,n),i.prototype.byteAt=function(e){return this.data[this.zero+e]},i.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),i=e.charCodeAt(3),s=this.length-4;0<=s;--s)if(this.data[s]===t&&this.data[s+1]===r&&this.data[s+2]===n&&this.data[s+3]===i)return s-this.zero;return -1},i.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),i=e.charCodeAt(3),s=this.readData(4);return t===s[0]&&r===s[1]&&n===s[2]&&i===s[3]},i.prototype.readData=function(e){if(this.checkOffset(e),0===e)return [];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./DataReader":18}],18:[function(e,t,r){var n=e("../utils");function i(e){this.data=e,this.length=e.length,this.index=0,this.zero=0;}i.prototype={checkOffset:function(e){this.checkIndex(this.index+e);},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e;},skip:function(e){this.setIndex(this.index+e);},byteAt:function(){},readInt:function(e){var t,r=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)r=(r<<8)+this.byteAt(t);return this.index+=e,r},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=i;},{"../utils":32}],19:[function(e,t,r){var n=e("./Uint8ArrayReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,r){var n=e("./DataReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},i.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},i.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./DataReader":18}],21:[function(e,t,r){var n=e("./ArrayReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,r){var n=e("../utils"),i=e("../support"),s=e("./ArrayReader"),a=e("./StringReader"),o=e("./NodeBufferReader"),h=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||i.uint8array?"nodebuffer"===t?new o(e):i.uint8array?new h(n.transformTo("uint8array",e)):new s(n.transformTo("array",e)):new a(e)};},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,r){r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b";},{}],24:[function(e,t,r){var n=e("./GenericWorker"),i=e("../utils");function s(e){n.call(this,"ConvertWorker to "+e),this.destType=e;}i.inherits(s,n),s.prototype.processChunk=function(e){this.push({data:i.transformTo(this.destType,e.data),meta:e.meta});},t.exports=s;},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,r){var n=e("./GenericWorker"),i=e("../crc32");function s(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0);}e("../utils").inherits(s,n),s.prototype.processChunk=function(e){this.streamInfo.crc32=i(e.data,this.streamInfo.crc32||0),this.push(e);},t.exports=s;},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,r){var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0);}n.inherits(s,i),s.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length;}i.prototype.processChunk.call(this,e);},t.exports=s;},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,r){var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat();},function(e){t.error(e);});}n.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null;},s.prototype.resume=function(){return !!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0));},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return !1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t);}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=s;},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,r){function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null;}n.prototype={push:function(e){this.emit("data",e);},end:function(){if(this.isFinished)return !1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0;}catch(e){this.emit("error",e);}return !0},error:function(e){return !this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[];},emit:function(e,t){if(this._listeners[e])for(var r=0;r<this._listeners[e].length;r++)this._listeners[e][r].call(this,t);},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e);}),e.on("end",function(){t.end();}),e.on("error",function(e){t.error(e);}),this},pause:function(){return !this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return !1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e);},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e]);},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock();},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=n;},{}],29:[function(e,t,r){var h=e("../utils"),i=e("./ConvertWorker"),s=e("./GenericWorker"),u=e("../base64"),n=e("../support"),a=e("../external"),o=null;if(n.nodestream)try{o=e("../nodejs/NodejsStreamOutputAdapter");}catch(e){}function l(e,o){return new a.Promise(function(t,r){var n=[],i=e._internalType,s=e._outputType,a=e._mimeType;e.on("data",function(e,t){n.push(e),o&&o(t);}).on("error",function(e){n=[],r(e);}).on("end",function(){try{var e=function(e,t,r){switch(e){case"blob":return h.newBlob(h.transformTo("arraybuffer",t),r);case"base64":return u.encode(t);default:return h.transformTo(e,t)}}(s,function(e,t){var r,n=0,i=null,s=0;for(r=0;r<t.length;r++)s+=t[r].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(i=new Uint8Array(s),r=0;r<t.length;r++)i.set(t[r],n),n+=t[r].length;return i;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(i,n),a);t(e);}catch(e){r(e);}n=[];}).resume();})}function f(e,t,r){var n=t;switch(t){case"blob":case"arraybuffer":n="uint8array";break;case"base64":n="string";}try{this._internalType=n,this._outputType=t,this._mimeType=r,h.checkSupport(n),this._worker=e.pipe(new i(n)),e.lock();}catch(e){this._worker=new s("error"),this._worker.error(e);}}f.prototype={accumulate:function(e){return l(this,e)},on:function(e,t){var r=this;return "data"===e?this._worker.on(e,function(e){t.call(r,e.data,e.meta);}):this._worker.on(e,function(){h.delay(t,arguments,r);}),this},resume:function(){return h.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(h.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new o(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=f;},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,r){if(r.base64=!0,r.array=!0,r.string=!0,r.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,r.nodebuffer="undefined"!=typeof Buffer,r.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)r.blob=!1;else {var n=new ArrayBuffer(0);try{r.blob=0===new Blob([n],{type:"application/zip"}).size;}catch(e){try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(n),r.blob=0===i.getBlob("application/zip").size;}catch(e){r.blob=!1;}}}try{r.nodestream=!!e("readable-stream").Readable;}catch(e){r.nodestream=!1;}},{"readable-stream":16}],31:[function(e,t,s){for(var o=e("./utils"),h=e("./support"),r=e("./nodejsUtils"),n=e("./stream/GenericWorker"),u=new Array(256),i=0;i<256;i++)u[i]=252<=i?6:248<=i?5:240<=i?4:224<=i?3:192<=i?2:1;u[254]=u[254]=1;function a(){n.call(this,"utf-8 decode"),this.leftOver=null;}function l(){n.call(this,"utf-8 encode");}s.utf8encode=function(e){return h.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,r,n,i,s,a=e.length,o=0;for(i=0;i<a;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),o+=r<128?1:r<2048?2:r<65536?3:4;for(t=h.uint8array?new Uint8Array(o):new Array(o),i=s=0;s<o;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),r<128?t[s++]=r:(r<2048?t[s++]=192|r>>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t}(e)},s.utf8decode=function(e){return h.nodebuffer?o.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,r,n,i,s=e.length,a=new Array(2*s);for(t=r=0;t<s;)if((n=e[t++])<128)a[r++]=n;else if(4<(i=u[n]))a[r++]=65533,t+=i-1;else {for(n&=2===i?31:3===i?15:7;1<i&&t<s;)n=n<<6|63&e[t++],i--;1<i?a[r++]=65533:n<65536?a[r++]=n:(n-=65536,a[r++]=55296|n>>10&1023,a[r++]=56320|1023&n);}return a.length!==r&&(a.subarray?a=a.subarray(0,r):a.length=r),o.applyFromCharCode(a)}(e=o.transformTo(h.uint8array?"uint8array":"array",e))},o.inherits(a,n),a.prototype.processChunk=function(e){var t=o.transformTo(h.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(h.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length);}else t=this.leftOver.concat(t);this.leftOver=null;}var n=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+u[e[r]]>t?r:t}(t),i=t;n!==t.length&&(h.uint8array?(i=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(i=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:s.utf8decode(i),meta:e.meta});},a.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null);},s.Utf8DecodeWorker=a,o.inherits(l,n),l.prototype.processChunk=function(e){this.push({data:s.utf8encode(e.data),meta:e.meta});},s.Utf8EncodeWorker=l;},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,a){var o=e("./support"),h=e("./base64"),r=e("./nodejsUtils"),u=e("./external");function n(e){return e}function l(e,t){for(var r=0;r<e.length;++r)t[r]=255&e.charCodeAt(r);return t}e("setimmediate"),a.newBlob=function(t,r){a.checkSupport("blob");try{return new Blob([t],{type:r})}catch(e){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(t),n.getBlob(r)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var i={stringifyByChunk:function(e,t,r){var n=[],i=0,s=e.length;if(s<=r)return String.fromCharCode.apply(null,e);for(;i<s;)"array"===t||"nodebuffer"===t?n.push(String.fromCharCode.apply(null,e.slice(i,Math.min(i+r,s)))):n.push(String.fromCharCode.apply(null,e.subarray(i,Math.min(i+r,s)))),i+=r;return n.join("")},stringifyByChar:function(e){for(var t="",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},applyCanBeUsed:{uint8array:function(){try{return o.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return !1}}(),nodebuffer:function(){try{return o.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(e){return !1}}()}};function s(e){var t=65536,r=a.getTypeOf(e),n=!0;if("uint8array"===r?n=i.applyCanBeUsed.uint8array:"nodebuffer"===r&&(n=i.applyCanBeUsed.nodebuffer),n)for(;1<t;)try{return i.stringifyByChunk(e,r,t)}catch(e){t=Math.floor(t/2);}return i.stringifyByChar(e)}function f(e,t){for(var r=0;r<e.length;r++)t[r]=e[r];return t}a.applyFromCharCode=s;var c={};c.string={string:n,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return c.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},c.array={string:s,array:n,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(e)}},c.arraybuffer={string:function(e){return s(new Uint8Array(e))},array:function(e){return f(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:n,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},c.uint8array={string:s,array:function(e){return f(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:n,nodebuffer:function(e){return r.newBufferFrom(e)}},c.nodebuffer={string:s,array:function(e){return f(e,new Array(e.length))},arraybuffer:function(e){return c.nodebuffer.uint8array(e).buffer},uint8array:function(e){return f(e,new Uint8Array(e.length))},nodebuffer:n},a.transformTo=function(e,t){if(t=t||"",!e)return t;a.checkSupport(e);var r=a.getTypeOf(t);return c[r][e](t)},a.resolve=function(e){for(var t=e.split("/"),r=[],n=0;n<t.length;n++){var i=t[n];"."===i||""===i&&0!==n&&n!==t.length-1||(".."===i?r.pop():r.push(i));}return r.join("/")},a.getTypeOf=function(e){return "string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":o.nodebuffer&&r.isBuffer(e)?"nodebuffer":o.uint8array&&e instanceof Uint8Array?"uint8array":o.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},a.checkSupport=function(e){if(!o[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},a.MAX_VALUE_16BITS=65535,a.MAX_VALUE_32BITS=-1,a.pretty=function(e){var t,r,n="";for(r=0;r<(e||"").length;r++)n+="\\x"+((t=e.charCodeAt(r))<16?"0":"")+t.toString(16).toUpperCase();return n},a.delay=function(e,t,r){setImmediate(function(){e.apply(r||null,t||[]);});},a.inherits=function(e,t){function r(){}r.prototype=t.prototype,e.prototype=new r;},a.extend=function(){var e,t,r={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===r[t]&&(r[t]=arguments[e][t]);return r},a.prepareContent=function(r,e,n,i,s){return u.Promise.resolve(e).then(function(n){return o.blob&&(n instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(n)))&&"undefined"!=typeof FileReader?new u.Promise(function(t,r){var e=new FileReader;e.onload=function(e){t(e.target.result);},e.onerror=function(e){r(e.target.error);},e.readAsArrayBuffer(n);}):n}).then(function(e){var t=a.getTypeOf(e);return t?("arraybuffer"===t?e=a.transformTo("uint8array",e):"string"===t&&(s?e=h.decode(e):n&&!0!==i&&(e=function(e){return l(e,o.uint8array?new Uint8Array(e.length):new Array(e.length))}(e))),e):u.Promise.reject(new Error("Can't read the data of '"+r+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})};},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,r){var n=e("./reader/readerFor"),i=e("./utils"),s=e("./signature"),a=e("./zipEntry"),o=e("./support");function h(e){this.files=[],this.loadOptions=e;}h.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(t)+", expected "+i.pretty(e)+")")}},isSignature:function(e,t){var r=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4)===t;return this.reader.setIndex(r),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=o.uint8array?"uint8array":"array",r=i.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(r);},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,r,n=this.zip64EndOfCentralSize-44;0<n;)e=this.reader.readInt(2),t=this.reader.readInt(4),r=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:r};},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes();},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(e=new a({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(e<0)throw !this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory");this.reader.setIndex(e);var t=e;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===i.MAX_VALUE_16BITS||this.diskWithCentralDirStart===i.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===i.MAX_VALUE_16BITS||this.centralDirRecords===i.MAX_VALUE_16BITS||this.centralDirSize===i.MAX_VALUE_32BITS||this.centralDirOffset===i.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral();}var r=this.centralDirOffset+this.centralDirSize;this.zip64&&(r+=20,r+=12+this.zip64EndOfCentralSize);var n=t-r;if(0<n)this.isSignature(t,s.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(e){this.reader=n(e);},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles();}},t.exports=h;},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,r){var n=e("./reader/readerFor"),s=e("./utils"),i=e("./compressedObject"),a=e("./crc32"),o=e("./utf8"),h=e("./compressions"),u=e("./support");function l(e,t){this.options=e,this.loadOptions=t;}l.prototype={isEncrypted:function(){return 1==(1&this.bitFlag)},useUTF8:function(){return 2048==(2048&this.bitFlag)},readLocalPart:function(e){var t,r;if(e.skip(22),this.fileNameLength=e.readInt(2),r=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(r),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in h)if(Object.prototype.hasOwnProperty.call(h,t)&&h[t].magic===e)return h[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new i(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize));},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength);},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0);},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4));}},readExtraFields:function(e){var t,r,n,i=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<i;)t=e.readInt(2),r=e.readInt(2),n=e.readData(r),this.extraFields[t]={id:t,length:r,value:n};e.setIndex(i);},handleUTF8:function(){var e=u.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else {var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else {var r=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(r);}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else {var i=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(i);}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=n(e.value);return 1!==t.readInt(1)?null:a(this.fileName)!==t.readInt(4)?null:o.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=n(e.value);return 1!==t.readInt(1)?null:a(this.fileComment)!==t.readInt(4)?null:o.utf8decode(t.readData(e.length-5))}return null}},t.exports=l;},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,r){function n(e,t,r){this.name=e,this.dir=r.dir,this.date=r.date,this.comment=r.comment,this.unixPermissions=r.unixPermissions,this.dosPermissions=r.dosPermissions,this._data=t,this._dataBinary=r.binary,this.options={compression:r.compression,compressionOptions:r.compressionOptions};}var s=e("./stream/StreamHelper"),i=e("./stream/DataWorker"),a=e("./utf8"),o=e("./compressedObject"),h=e("./stream/GenericWorker");n.prototype={internalStream:function(e){var t=null,r="string";try{if(!e)throw new Error("No output type specified.");var n="string"===(r=e.toLowerCase())||"text"===r;"binarystring"!==r&&"text"!==r||(r="string"),t=this._decompressWorker();var i=!this._dataBinary;i&&!n&&(t=t.pipe(new a.Utf8EncodeWorker)),!i&&n&&(t=t.pipe(new a.Utf8DecodeWorker));}catch(e){(t=new h("error")).error(e);}return new s(t,r,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof o&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var r=this._decompressWorker();return this._dataBinary||(r=r.pipe(new a.Utf8EncodeWorker)),o.createWorkerFrom(r,e,t)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof h?this._data:new i(this._data)}};for(var u=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},f=0;f<u.length;f++)n.prototype[u[f]]=l;t.exports=n;},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,l,t){(function(t){var r,n,e=t.MutationObserver||t.WebKitMutationObserver;if(e){var i=0,s=new e(u),a=t.document.createTextNode("");s.observe(a,{characterData:!0}),r=function(){a.data=i=++i%2;};}else if(t.setImmediate||void 0===t.MessageChannel)r="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){u(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null;},t.document.documentElement.appendChild(e);}:function(){setTimeout(u,0);};else {var o=new t.MessageChannel;o.port1.onmessage=u,r=function(){o.port2.postMessage(0);};}var h=[];function u(){var e,t;n=!0;for(var r=h.length;r;){for(t=h,h=[],e=-1;++e<r;)t[e]();r=h.length;}n=!1;}l.exports=function(e){1!==h.push(e)||n||r();};}).call(this,"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});},{}],37:[function(e,t,r){var i=e("immediate");function u(){}var l={},s=["REJECTED"],a=["FULFILLED"],n=["PENDING"];function o(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=n,this.queue=[],this.outcome=void 0,e!==u&&d(this,e);}function h(e,t,r){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof r&&(this.onRejected=r,this.callRejected=this.otherCallRejected);}function f(t,r,n){i(function(){var e;try{e=r(n);}catch(e){return l.reject(t,e)}e===t?l.reject(t,new TypeError("Cannot resolve promise with itself")):l.resolve(t,e);});}function c(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments);}}function d(t,e){var r=!1;function n(e){r||(r=!0,l.reject(t,e));}function i(e){r||(r=!0,l.resolve(t,e));}var s=p(function(){e(i,n);});"error"===s.status&&n(s.value);}function p(e,t){var r={};try{r.value=e(t),r.status="success";}catch(e){r.status="error",r.value=e;}return r}(t.exports=o).prototype.finally=function(t){if("function"!=typeof t)return this;var r=this.constructor;return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){throw e})})},o.prototype.catch=function(e){return this.then(null,e)},o.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===s)return this;var r=new this.constructor(u);this.state!==n?f(r,this.state===a?e:t,this.outcome):this.queue.push(new h(r,e,t));return r},h.prototype.callFulfilled=function(e){l.resolve(this.promise,e);},h.prototype.otherCallFulfilled=function(e){f(this.promise,this.onFulfilled,e);},h.prototype.callRejected=function(e){l.reject(this.promise,e);},h.prototype.otherCallRejected=function(e){f(this.promise,this.onRejected,e);},l.resolve=function(e,t){var r=p(c,t);if("error"===r.status)return l.reject(e,r.value);var n=r.value;if(n)d(e,n);else {e.state=a,e.outcome=t;for(var i=-1,s=e.queue.length;++i<s;)e.queue[i].callFulfilled(t);}return e},l.reject=function(e,t){e.state=s,e.outcome=t;for(var r=-1,n=e.queue.length;++r<n;)e.queue[r].callRejected(t);return e},o.resolve=function(e){if(e instanceof this)return e;return l.resolve(new this(u),e)},o.reject=function(e){var t=new this(u);return l.reject(t,e)},o.all=function(e){var r=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);var s=new Array(n),a=0,t=-1,o=new this(u);for(;++t<n;)h(e[t],t);return o;function h(e,t){r.resolve(e).then(function(e){s[t]=e,++a!==n||i||(i=!0,l.resolve(o,s));},function(e){i||(i=!0,l.reject(o,e));});}},o.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var r=e.length,n=!1;if(!r)return this.resolve([]);var i=-1,s=new this(u);for(;++i<r;)a=e[i],t.resolve(a).then(function(e){n||(n=!0,l.resolve(s,e));},function(e){n||(n=!0,l.reject(s,e));});var a;return s};},{immediate:36}],38:[function(e,t,r){var n={};(0, e("./lib/utils/common").assign)(n,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=n;},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,r){var a=e("./zlib/deflate"),o=e("./utils/common"),h=e("./utils/strings"),i=e("./zlib/messages"),s=e("./zlib/zstream"),u=Object.prototype.toString,l=0,f=-1,c=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=o.assign({level:f,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var r=a.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==l)throw new Error(i[r]);if(t.header&&a.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"==typeof t.dictionary?h.string2buf(t.dictionary):"[object ArrayBuffer]"===u.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(r=a.deflateSetDictionary(this.strm,n))!==l)throw new Error(i[r]);this._dict_set=!0;}}function n(e,t){var r=new p(t);if(r.push(e,!0),r.err)throw r.msg||i[r.err];return r.result}p.prototype.push=function(e,t){var r,n,i=this.strm,s=this.options.chunkSize;if(this.ended)return !1;n=t===~~t?t:!0===t?4:0,"string"==typeof e?i.input=h.string2buf(e):"[object ArrayBuffer]"===u.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(0===i.avail_out&&(i.output=new o.Buf8(s),i.next_out=0,i.avail_out=s),1!==(r=a.deflate(i,n))&&r!==l)return this.onEnd(r),!(this.ended=!0);0!==i.avail_out&&(0!==i.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(h.buf2binstring(o.shrinkBuf(i.output,i.next_out))):this.onData(o.shrinkBuf(i.output,i.next_out)));}while((0<i.avail_in||0===i.avail_out)&&1!==r);return 4===n?(r=a.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===l):2!==n||(this.onEnd(l),!(i.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e);},p.prototype.onEnd=function(e){e===l&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;},r.Deflate=p,r.deflate=n,r.deflateRaw=function(e,t){return (t=t||{}).raw=!0,n(e,t)},r.gzip=function(e,t){return (t=t||{}).gzip=!0,n(e,t)};},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,r){var c=e("./zlib/inflate"),d=e("./utils/common"),p=e("./utils/strings"),m=e("./zlib/constants"),n=e("./zlib/messages"),i=e("./zlib/zstream"),s=e("./zlib/gzheader"),_=Object.prototype.toString;function a(e){if(!(this instanceof a))return new a(e);this.options=d.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new i,this.strm.avail_out=0;var r=c.inflateInit2(this.strm,t.windowBits);if(r!==m.Z_OK)throw new Error(n[r]);this.header=new s,c.inflateGetHeader(this.strm,this.header);}function o(e,t){var r=new a(t);if(r.push(e,!0),r.err)throw r.msg||n[r.err];return r.result}a.prototype.push=function(e,t){var r,n,i,s,a,o,h=this.strm,u=this.options.chunkSize,l=this.options.dictionary,f=!1;if(this.ended)return !1;n=t===~~t?t:!0===t?m.Z_FINISH:m.Z_NO_FLUSH,"string"==typeof e?h.input=p.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new d.Buf8(u),h.next_out=0,h.avail_out=u),(r=c.inflate(h,m.Z_NO_FLUSH))===m.Z_NEED_DICT&&l&&(o="string"==typeof l?p.string2buf(l):"[object ArrayBuffer]"===_.call(l)?new Uint8Array(l):l,r=c.inflateSetDictionary(this.strm,o)),r===m.Z_BUF_ERROR&&!0===f&&(r=m.Z_OK,f=!1),r!==m.Z_STREAM_END&&r!==m.Z_OK)return this.onEnd(r),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&r!==m.Z_STREAM_END&&(0!==h.avail_in||n!==m.Z_FINISH&&n!==m.Z_SYNC_FLUSH)||("string"===this.options.to?(i=p.utf8border(h.output,h.next_out),s=h.next_out-i,a=p.buf2string(h.output,i),h.next_out=s,h.avail_out=u-s,s&&d.arraySet(h.output,h.output,i,s,0),this.onData(a)):this.onData(d.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(f=!0);}while((0<h.avail_in||0===h.avail_out)&&r!==m.Z_STREAM_END);return r===m.Z_STREAM_END&&(n=m.Z_FINISH),n===m.Z_FINISH?(r=c.inflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===m.Z_OK):n!==m.Z_SYNC_FLUSH||(this.onEnd(m.Z_OK),!(h.avail_out=0))},a.prototype.onData=function(e){this.chunks.push(e);},a.prototype.onEnd=function(e){e===m.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=d.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;},r.Inflate=a,r.inflate=o,r.inflateRaw=function(e,t){return (t=t||{}).raw=!0,o(e,t)},r.ungzip=o;},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,r){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;r.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var n in r)r.hasOwnProperty(n)&&(e[n]=r[n]);}}return e},r.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var i={arraySet:function(e,t,r,n,i){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+n),i);else for(var s=0;s<n;s++)e[i+s]=t[r+s];},flattenChunks:function(e){var t,r,n,i,s,a;for(t=n=0,r=e.length;t<r;t++)n+=e[t].length;for(a=new Uint8Array(n),t=i=0,r=e.length;t<r;t++)s=e[t],a.set(s,i),i+=s.length;return a}},s={arraySet:function(e,t,r,n,i){for(var s=0;s<n;s++)e[i+s]=t[r+s];},flattenChunks:function(e){return [].concat.apply([],e)}};r.setTyped=function(e){e?(r.Buf8=Uint8Array,r.Buf16=Uint16Array,r.Buf32=Int32Array,r.assign(r,i)):(r.Buf8=Array,r.Buf16=Array,r.Buf32=Array,r.assign(r,s));},r.setTyped(n);},{}],42:[function(e,t,r){var h=e("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0]);}catch(e){i=!1;}try{String.fromCharCode.apply(null,new Uint8Array(1));}catch(e){s=!1;}for(var u=new h.Buf8(256),n=0;n<256;n++)u[n]=252<=n?6:248<=n?5:240<=n?4:224<=n?3:192<=n?2:1;function l(e,t){if(t<65537&&(e.subarray&&s||!e.subarray&&i))return String.fromCharCode.apply(null,h.shrinkBuf(e,t));for(var r="",n=0;n<t;n++)r+=String.fromCharCode(e[n]);return r}u[254]=u[254]=1,r.string2buf=function(e){var t,r,n,i,s,a=e.length,o=0;for(i=0;i<a;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),o+=r<128?1:r<2048?2:r<65536?3:4;for(t=new h.Buf8(o),i=s=0;s<o;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),r<128?t[s++]=r:(r<2048?t[s++]=192|r>>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t},r.buf2binstring=function(e){return l(e,e.length)},r.binstring2buf=function(e){for(var t=new h.Buf8(e.length),r=0,n=t.length;r<n;r++)t[r]=e.charCodeAt(r);return t},r.buf2string=function(e,t){var r,n,i,s,a=t||e.length,o=new Array(2*a);for(r=n=0;r<a;)if((i=e[r++])<128)o[n++]=i;else if(4<(s=u[i]))o[n++]=65533,r+=s-1;else {for(i&=2===s?31:3===s?15:7;1<s&&r<a;)i=i<<6|63&e[r++],s--;1<s?o[n++]=65533:i<65536?o[n++]=i:(i-=65536,o[n++]=55296|i>>10&1023,o[n++]=56320|1023&i);}return l(o,n)},r.utf8border=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+u[e[r]]>t?r:t};},{"./common":41}],43:[function(e,t,r){t.exports=function(e,t,r,n){for(var i=65535&e|0,s=e>>>16&65535|0,a=0;0!==r;){for(r-=a=2e3<r?2e3:r;s=s+(i=i+t[n++]|0)|0,--a;);i%=65521,s%=65521;}return i|s<<16|0};},{}],44:[function(e,t,r){t.exports={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_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};},{}],45:[function(e,t,r){var o=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e;}return t}();t.exports=function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a<s;a++)e=e>>>8^i[255&(e^t[a])];return -1^e};},{}],46:[function(e,t,r){var h,c=e("../utils/common"),u=e("./trees"),d=e("./adler32"),p=e("./crc32"),n=e("./messages"),l=0,f=4,m=0,_=-2,g=-1,b=4,i=2,v=8,y=9,s=286,a=30,o=19,w=2*s+1,k=15,x=3,S=258,z=S+x+1,C=42,E=113,A=1,I=2,O=3,B=4;function R(e,t){return e.msg=n[t],t}function T(e){return (e<<1)-(4<e?9:0)}function D(e){for(var t=e.length;0<=--t;)e[t]=0;}function F(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(c.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0));}function N(e,t){u._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,F(e.strm);}function U(e,t){e.pending_buf[e.pending++]=t;}function P(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t;}function L(e,t){var r,n,i=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,h=e.strstart>e.w_size-z?e.strstart-(e.w_size-z):0,u=e.window,l=e.w_mask,f=e.prev,c=e.strstart+S,d=u[s+a-1],p=u[s+a];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do{if(u[(r=t)+a]===p&&u[r+a-1]===d&&u[r]===u[s]&&u[++r]===u[s+1]){s+=2,r++;do{}while(u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&s<c);if(n=S-(c-s),s=c-S,a<n){if(e.match_start=t,o<=(a=n))break;d=u[s+a-1],p=u[s+a];}}}while((t=f[t&l])>h&&0!=--i);return a<=e.lookahead?a:e.lookahead}function j(e){var t,r,n,i,s,a,o,h,u,l,f=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-z)){for(c.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=r=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--r;);for(t=r=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--r;);i+=f;}if(0===e.strm.avail_in)break;if(a=e.strm,o=e.window,h=e.strstart+e.lookahead,u=i,l=void 0,l=a.avail_in,u<l&&(l=u),r=0===l?0:(a.avail_in-=l,c.arraySet(o,a.input,a.next_in,l,h),1===a.state.wrap?a.adler=d(a.adler,o,l,h):2===a.state.wrap&&(a.adler=p(a.adler,o,l,h)),a.next_in+=l,a.total_in+=l,l),e.lookahead+=r,e.lookahead+e.insert>=x)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+x-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<x)););}while(e.lookahead<z&&0!==e.strm.avail_in)}function Z(e,t){for(var r,n;;){if(e.lookahead<z){if(j(e),e.lookahead<z&&t===l)return A;if(0===e.lookahead)break}if(r=0,e.lookahead>=x&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+x-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==r&&e.strstart-r<=e.w_size-z&&(e.match_length=L(e,r)),e.match_length>=x)if(n=u._tr_tally(e,e.strstart-e.match_start,e.match_length-x),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=x){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+x-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,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=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=u._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=e.strstart<x-1?e.strstart:x-1,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}function W(e,t){for(var r,n,i;;){if(e.lookahead<z){if(j(e),e.lookahead<z&&t===l)return A;if(0===e.lookahead)break}if(r=0,e.lookahead>=x&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+x-1])&e.hash_mask,r=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=x-1,0!==r&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-z&&(e.match_length=L(e,r),e.match_length<=5&&(1===e.strategy||e.match_length===x&&4096<e.strstart-e.match_start)&&(e.match_length=x-1)),e.prev_length>=x&&e.match_length<=e.prev_length){for(i=e.strstart+e.lookahead-x,n=u._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-x),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=i&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+x-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=x-1,e.strstart++,n&&(N(e,!1),0===e.strm.avail_out))return A}else if(e.match_available){if((n=u._tr_tally(e,0,e.window[e.strstart-1]))&&N(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return A}else e.match_available=1,e.strstart++,e.lookahead--;}return e.match_available&&(n=u._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<x-1?e.strstart:x-1,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}function M(e,t,r,n,i){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=i;}function H(){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=v,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 c.Buf16(2*w),this.dyn_dtree=new c.Buf16(2*(2*a+1)),this.bl_tree=new c.Buf16(2*(2*o+1)),D(this.dyn_ltree),D(this.dyn_dtree),D(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new c.Buf16(k+1),this.heap=new c.Buf16(2*s+1),D(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new c.Buf16(2*s+1),D(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}function G(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=i,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?C:E,e.adler=2===t.wrap?0:1,t.last_flush=l,u._tr_init(t),m):R(e,_)}function K(e){var t=G(e);return t===m&&function(e){e.window_size=2*e.w_size,D(e.head),e.max_lazy_match=h[e.level].max_lazy,e.good_match=h[e.level].good_length,e.nice_match=h[e.level].nice_length,e.max_chain_length=h[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=x-1,e.match_available=0,e.ins_h=0;}(e.state),t}function Y(e,t,r,n,i,s){if(!e)return _;var a=1;if(t===g&&(t=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),i<1||y<i||r!==v||n<8||15<n||t<0||9<t||s<0||b<s)return R(e,_);8===n&&(n=9);var o=new H;return (e.state=o).strm=e,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+x-1)/x),o.window=new c.Buf8(2*o.w_size),o.head=new c.Buf16(o.hash_size),o.prev=new c.Buf16(o.w_size),o.lit_bufsize=1<<i+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new c.Buf8(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=s,o.method=r,K(e)}h=[new M(0,0,0,0,function(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(j(e),0===e.lookahead&&t===l)return A;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,N(e,!1),0===e.strm.avail_out))return A;if(e.strstart-e.block_start>=e.w_size-z&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):(e.strstart>e.block_start&&(N(e,!1),e.strm.avail_out),A)}),new M(4,4,8,4,Z),new M(4,5,16,8,Z),new M(4,6,32,32,Z),new M(4,4,16,16,W),new M(8,16,32,32,W),new M(8,16,128,128,W),new M(8,32,128,256,W),new M(32,128,258,1024,W),new M(32,258,258,4096,W)],r.deflateInit=function(e,t){return Y(e,t,v,15,8,0)},r.deflateInit2=Y,r.deflateReset=K,r.deflateResetKeep=G,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?_:(e.state.gzhead=t,m):_},r.deflate=function(e,t){var r,n,i,s;if(!e||!e.state||5<t||t<0)return e?R(e,_):_;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||666===n.status&&t!==f)return R(e,0===e.avail_out?-5:_);if(n.strm=e,r=n.last_flush,n.last_flush=t,n.status===C)if(2===n.wrap)e.adler=0,U(n,31),U(n,139),U(n,8),n.gzhead?(U(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),U(n,255&n.gzhead.time),U(n,n.gzhead.time>>8&255),U(n,n.gzhead.time>>16&255),U(n,n.gzhead.time>>24&255),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(U(n,255&n.gzhead.extra.length),U(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=p(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(U(n,0),U(n,0),U(n,0),U(n,0),U(n,0),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,3),n.status=E);else {var a=v+(n.w_bits-8<<4)<<8;a|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(a|=32),a+=31-a%31,n.status=E,P(n,a),0!==n.strstart&&(P(n,e.adler>>>16),P(n,65535&e.adler)),e.adler=1;}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending!==n.pending_buf_size));)U(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73);}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,U(n,s);}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.gzindex=0,n.status=91);}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,U(n,s);}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.status=103);}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&F(e),n.pending+2<=n.pending_buf_size&&(U(n,255&e.adler),U(n,e.adler>>8&255),e.adler=0,n.status=E)):n.status=E),0!==n.pending){if(F(e),0===e.avail_out)return n.last_flush=-1,m}else if(0===e.avail_in&&T(t)<=T(r)&&t!==f)return R(e,-5);if(666===n.status&&0!==e.avail_in)return R(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==l&&666!==n.status){var o=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(j(e),0===e.lookahead)){if(t===l)return A;break}if(e.match_length=0,r=u._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}(n,t):3===n.strategy?function(e,t){for(var r,n,i,s,a=e.window;;){if(e.lookahead<=S){if(j(e),e.lookahead<=S&&t===l)return A;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=x&&0<e.strstart&&(n=a[i=e.strstart-1])===a[++i]&&n===a[++i]&&n===a[++i]){s=e.strstart+S;do{}while(n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&i<s);e.match_length=S-(s-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=x?(r=u._tr_tally(e,1,e.match_length-x),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=u._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}(n,t):h[n.level].func(n,t);if(o!==O&&o!==B||(n.status=666),o===A||o===O)return 0===e.avail_out&&(n.last_flush=-1),m;if(o===I&&(1===t?u._tr_align(n):5!==t&&(u._tr_stored_block(n,0,0,!1),3===t&&(D(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),F(e),0===e.avail_out))return n.last_flush=-1,m}return t!==f?m:n.wrap<=0?1:(2===n.wrap?(U(n,255&e.adler),U(n,e.adler>>8&255),U(n,e.adler>>16&255),U(n,e.adler>>24&255),U(n,255&e.total_in),U(n,e.total_in>>8&255),U(n,e.total_in>>16&255),U(n,e.total_in>>24&255)):(P(n,e.adler>>>16),P(n,65535&e.adler)),F(e),0<n.wrap&&(n.wrap=-n.wrap),0!==n.pending?m:1)},r.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==C&&69!==t&&73!==t&&91!==t&&103!==t&&t!==E&&666!==t?R(e,_):(e.state=null,t===E?R(e,-3):m):_},r.deflateSetDictionary=function(e,t){var r,n,i,s,a,o,h,u,l=t.length;if(!e||!e.state)return _;if(2===(s=(r=e.state).wrap)||1===s&&r.status!==C||r.lookahead)return _;for(1===s&&(e.adler=d(e.adler,t,l,0)),r.wrap=0,l>=r.w_size&&(0===s&&(D(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new c.Buf8(r.w_size),c.arraySet(u,t,l-r.w_size,r.w_size,0),t=u,l=r.w_size),a=e.avail_in,o=e.next_in,h=e.input,e.avail_in=l,e.next_in=0,e.input=t,j(r);r.lookahead>=x;){for(n=r.strstart,i=r.lookahead-(x-1);r.ins_h=(r.ins_h<<r.hash_shift^r.window[n+x-1])&r.hash_mask,r.prev[n&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=n,n++,--i;);r.strstart=n,r.lookahead=x-1,j(r);}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=x-1,r.match_available=0,e.next_in=o,e.input=h,e.avail_in=a,r.wrap=s,m},r.deflateInfo="pako deflate (from Nodeca project)";},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,r){t.exports=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;};},{}],48:[function(e,t,r){t.exports=function(e,t){var r,n,i,s,a,o,h,u,l,f,c,d,p,m,_,g,b,v,y,w,k,x,S,z,C;r=e.state,n=e.next_in,z=e.input,i=n+(e.avail_in-5),s=e.next_out,C=e.output,a=s-(t-e.avail_out),o=s+(e.avail_out-257),h=r.dmax,u=r.wsize,l=r.whave,f=r.wnext,c=r.window,d=r.hold,p=r.bits,m=r.lencode,_=r.distcode,g=(1<<r.lenbits)-1,b=(1<<r.distbits)-1;e:do{p<15&&(d+=z[n++]<<p,p+=8,d+=z[n++]<<p,p+=8),v=m[d&g];t:for(;;){if(d>>>=y=v>>>24,p-=y,0===(y=v>>>16&255))C[s++]=65535&v;else {if(!(16&y)){if(0==(64&y)){v=m[(65535&v)+(d&(1<<y)-1)];continue t}if(32&y){r.mode=12;break e}e.msg="invalid literal/length code",r.mode=30;break e}w=65535&v,(y&=15)&&(p<y&&(d+=z[n++]<<p,p+=8),w+=d&(1<<y)-1,d>>>=y,p-=y),p<15&&(d+=z[n++]<<p,p+=8,d+=z[n++]<<p,p+=8),v=_[d&b];r:for(;;){if(d>>>=y=v>>>24,p-=y,!(16&(y=v>>>16&255))){if(0==(64&y)){v=_[(65535&v)+(d&(1<<y)-1)];continue r}e.msg="invalid distance code",r.mode=30;break e}if(k=65535&v,p<(y&=15)&&(d+=z[n++]<<p,(p+=8)<y&&(d+=z[n++]<<p,p+=8)),h<(k+=d&(1<<y)-1)){e.msg="invalid distance too far back",r.mode=30;break e}if(d>>>=y,p-=y,(y=s-a)<k){if(l<(y=k-y)&&r.sane){e.msg="invalid distance too far back",r.mode=30;break e}if(S=c,(x=0)===f){if(x+=u-y,y<w){for(w-=y;C[s++]=c[x++],--y;);x=s-k,S=C;}}else if(f<y){if(x+=u+f-y,(y-=f)<w){for(w-=y;C[s++]=c[x++],--y;);if(x=0,f<w){for(w-=y=f;C[s++]=c[x++],--y;);x=s-k,S=C;}}}else if(x+=f-y,y<w){for(w-=y;C[s++]=c[x++],--y;);x=s-k,S=C;}for(;2<w;)C[s++]=S[x++],C[s++]=S[x++],C[s++]=S[x++],w-=3;w&&(C[s++]=S[x++],1<w&&(C[s++]=S[x++]));}else {for(x=s-k;C[s++]=C[x++],C[s++]=C[x++],C[s++]=C[x++],2<(w-=3););w&&(C[s++]=C[x++],1<w&&(C[s++]=C[x++]));}break}}break}}while(n<i&&s<o);n-=w=p>>3,d&=(1<<(p-=w<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=s<o?o-s+257:257-(s-o),r.hold=d,r.bits=p;};},{}],49:[function(e,t,r){var I=e("../utils/common"),O=e("./adler32"),B=e("./crc32"),R=e("./inffast"),T=e("./inftrees"),D=1,F=2,N=0,U=-2,P=1,n=852,i=592;function L(e){return (e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function s(){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 I.Buf16(320),this.work=new I.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}function a(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=P,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new I.Buf32(n),t.distcode=t.distdyn=new I.Buf32(i),t.sane=1,t.back=-1,N):U}function o(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,a(e)):U}function h(e,t){var r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?U:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,o(e))):U}function u(e,t){var r,n;return e?(n=new s,(e.state=n).window=null,(r=h(e,t))!==N&&(e.state=null),r):U}var l,f,c=!0;function j(e){if(c){var t;for(l=new I.Buf32(512),f=new I.Buf32(32),t=0;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(T(D,e.lens,0,288,l,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;T(F,e.lens,0,32,f,0,e.work,{bits:5}),c=!1;}e.lencode=l,e.lenbits=9,e.distcode=f,e.distbits=5;}function Z(e,t,r,n){var i,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new I.Buf8(s.wsize)),n>=s.wsize?(I.arraySet(s.window,t,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(i=s.wsize-s.wnext)&&(i=n),I.arraySet(s.window,t,r-n,i,s.wnext),(n-=i)?(I.arraySet(s.window,t,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0}r.inflateReset=o,r.inflateReset2=h,r.inflateResetKeep=a,r.inflateInit=function(e){return u(e,15)},r.inflateInit2=u,r.inflate=function(e,t){var r,n,i,s,a,o,h,u,l,f,c,d,p,m,_,g,b,v,y,w,k,x,S,z,C=0,E=new I.Buf8(4),A=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return U;12===(r=e.state).mode&&(r.mode=13),a=e.next_out,i=e.output,h=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,u=r.hold,l=r.bits,f=o,c=h,x=N;e:for(;;)switch(r.mode){case P:if(0===r.wrap){r.mode=13;break}for(;l<16;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(2&r.wrap&&35615===u){E[r.check=0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0),l=u=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=30;break}if(8!=(15&u)){e.msg="unknown compression method",r.mode=30;break}if(l-=4,k=8+(15&(u>>>=4)),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=30;break}r.dmax=1<<k,e.adler=r.check=1,r.mode=512&u?10:12,l=u=0;break;case 2:for(;l<16;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(r.flags=u,8!=(255&r.flags)){e.msg="unknown compression method",r.mode=30;break}if(57344&r.flags){e.msg="unknown header flags set",r.mode=30;break}r.head&&(r.head.text=u>>8&1),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=3;case 3:for(;l<32;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.head&&(r.head.time=u),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,E[2]=u>>>16&255,E[3]=u>>>24&255,r.check=B(r.check,E,4,0)),l=u=0,r.mode=4;case 4:for(;l<16;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.head&&(r.head.xflags=255&u,r.head.os=u>>8),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=5;case 5:if(1024&r.flags){for(;l<16;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.length=u,r.head&&(r.head.extra_len=u),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0;}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(o<(d=r.length)&&(d=o),d&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),I.arraySet(r.head.extra,n,s,d,k)),512&r.flags&&(r.check=B(r.check,n,d,s)),o-=d,s+=d,r.length-=d),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===o)break e;for(d=0;k=n[s+d++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k)),k&&d<o;);if(512&r.flags&&(r.check=B(r.check,n,d,s)),o-=d,s+=d,k)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=8;case 8:if(4096&r.flags){if(0===o)break e;for(d=0;k=n[s+d++],r.head&&k&&r.length<65536&&(r.head.comment+=String.fromCharCode(k)),k&&d<o;);if(512&r.flags&&(r.check=B(r.check,n,d,s)),o-=d,s+=d,k)break e}else r.head&&(r.head.comment=null);r.mode=9;case 9:if(512&r.flags){for(;l<16;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(u!==(65535&r.check)){e.msg="header crc mismatch",r.mode=30;break}l=u=0;}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=12;break;case 10:for(;l<32;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}e.adler=r.check=L(u),l=u=0,r.mode=11;case 11:if(0===r.havedict)return e.next_out=a,e.avail_out=h,e.next_in=s,e.avail_in=o,r.hold=u,r.bits=l,2;e.adler=r.check=1,r.mode=12;case 12:if(5===t||6===t)break e;case 13:if(r.last){u>>>=7&l,l-=7&l,r.mode=27;break}for(;l<3;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}switch(r.last=1&u,l-=1,3&(u>>>=1)){case 0:r.mode=14;break;case 1:if(j(r),r.mode=20,6!==t)break;u>>>=2,l-=2;break e;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=30;}u>>>=2,l-=2;break;case 14:for(u>>>=7&l,l-=7&l;l<32;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&u,l=u=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(d=r.length){if(o<d&&(d=o),h<d&&(d=h),0===d)break e;I.arraySet(i,n,s,d,a),o-=d,s+=d,h-=d,a+=d,r.length-=d;break}r.mode=12;break;case 17:for(;l<14;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(r.nlen=257+(31&u),u>>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,286<r.nlen||30<r.ndist){e.msg="too many length or distance symbols",r.mode=30;break}r.have=0,r.mode=18;case 18:for(;r.have<r.ncode;){for(;l<3;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.lens[A[r.have++]]=7&u,u>>>=3,l-=3;}for(;r.have<19;)r.lens[A[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},x=T(0,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have<r.nlen+r.ndist;){for(;g=(C=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(b<16)u>>>=_,l-=_,r.lens[r.have++]=b;else {if(16===b){for(z=_+2;l<z;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(u>>>=_,l-=_,0===r.have){e.msg="invalid bit length repeat",r.mode=30;break}k=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2;}else if(17===b){for(z=_+3;l<z;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}l-=_,k=0,d=3+(7&(u>>>=_)),u>>>=3,l-=3;}else {for(z=_+7;l<z;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}l-=_,k=0,d=11+(127&(u>>>=_)),u>>>=7,l-=7;}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=30;break}for(;d--;)r.lens[r.have++]=k;}}if(30===r.mode)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,S={bits:r.lenbits},x=T(D,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},x=T(F,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,x){e.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(6<=o&&258<=h){e.next_out=a,e.avail_out=h,e.next_in=s,e.avail_in=o,r.hold=u,r.bits=l,R(e,c),a=e.next_out,i=e.output,h=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,u=r.hold,l=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;g=(C=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(g&&0==(240&g)){for(v=_,y=g,w=b;g=(C=r.lencode[w+((u&(1<<v+y)-1)>>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}u>>>=v,l-=v,r.back+=v;}if(u>>>=_,l-=_,r.back+=_,r.length=b,0===g){r.mode=26;break}if(32&g){r.back=-1,r.mode=12;break}if(64&g){e.msg="invalid literal/length code",r.mode=30;break}r.extra=15&g,r.mode=22;case 22:if(r.extra){for(z=r.extra;l<z;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.length+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra;}r.was=r.length,r.mode=23;case 23:for(;g=(C=r.distcode[u&(1<<r.distbits)-1])>>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(0==(240&g)){for(v=_,y=g,w=b;g=(C=r.distcode[w+((u&(1<<v+y)-1)>>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}u>>>=v,l-=v,r.back+=v;}if(u>>>=_,l-=_,r.back+=_,64&g){e.msg="invalid distance code",r.mode=30;break}r.offset=b,r.extra=15&g,r.mode=24;case 24:if(r.extra){for(z=r.extra;l<z;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}r.offset+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra;}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===h)break e;if(d=c-h,r.offset>d){if((d=r.offset-d)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=30;break}p=d>r.wnext?(d-=r.wnext,r.wsize-d):r.wnext-d,d>r.length&&(d=r.length),m=r.window;}else m=i,p=a-r.offset,d=r.length;for(h<d&&(d=h),h-=d,r.length-=d;i[a++]=m[p++],--d;);0===r.length&&(r.mode=21);break;case 26:if(0===h)break e;i[a++]=r.length,h--,r.mode=21;break;case 27:if(r.wrap){for(;l<32;){if(0===o)break e;o--,u|=n[s++]<<l,l+=8;}if(c-=h,e.total_out+=c,r.total+=c,c&&(e.adler=r.check=r.flags?B(r.check,i,c,a-c):O(r.check,i,c,a-c)),c=h,(r.flags?u:L(u))!==r.check){e.msg="incorrect data check",r.mode=30;break}l=u=0;}r.mode=28;case 28:if(r.wrap&&r.flags){for(;l<32;){if(0===o)break e;o--,u+=n[s++]<<l,l+=8;}if(u!==(4294967295&r.total)){e.msg="incorrect length check",r.mode=30;break}l=u=0;}r.mode=29;case 29:x=1;break e;case 30:x=-3;break e;case 31:return -4;case 32:default:return U}return e.next_out=a,e.avail_out=h,e.next_in=s,e.avail_in=o,r.hold=u,r.bits=l,(r.wsize||c!==e.avail_out&&r.mode<30&&(r.mode<27||4!==t))&&Z(e,e.output,e.next_out,c-e.avail_out)?(r.mode=31,-4):(f-=e.avail_in,c-=e.avail_out,e.total_in+=f,e.total_out+=c,r.total+=c,r.wrap&&c&&(e.adler=r.check=r.flags?B(r.check,i,c,e.next_out-c):O(r.check,i,c,e.next_out-c)),e.data_type=r.bits+(r.last?64:0)+(12===r.mode?128:0)+(20===r.mode||15===r.mode?256:0),(0==f&&0===c||4===t)&&x===N&&(x=-5),x)},r.inflateEnd=function(e){if(!e||!e.state)return U;var t=e.state;return t.window&&(t.window=null),e.state=null,N},r.inflateGetHeader=function(e,t){var r;return e&&e.state?0==(2&(r=e.state).wrap)?U:((r.head=t).done=!1,N):U},r.inflateSetDictionary=function(e,t){var r,n=t.length;return e&&e.state?0!==(r=e.state).wrap&&11!==r.mode?U:11===r.mode&&O(1,t,n,0)!==r.check?-3:Z(e,t,n,n)?(r.mode=31,-4):(r.havedict=1,N):U},r.inflateInfo="pako inflate (from Nodeca project)";},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,r){var D=e("../utils/common"),F=[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],N=[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],U=[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],P=[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];t.exports=function(e,t,r,n,i,s,a,o){var h,u,l,f,c,d,p,m,_,g=o.bits,b=0,v=0,y=0,w=0,k=0,x=0,S=0,z=0,C=0,E=0,A=null,I=0,O=new D.Buf16(16),B=new D.Buf16(16),R=null,T=0;for(b=0;b<=15;b++)O[b]=0;for(v=0;v<n;v++)O[t[r+v]]++;for(k=g,w=15;1<=w&&0===O[w];w--);if(w<k&&(k=w),0===w)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(y=1;y<w&&0===O[y];y++);for(k<y&&(k=y),b=z=1;b<=15;b++)if(z<<=1,(z-=O[b])<0)return -1;if(0<z&&(0===e||1!==w))return -1;for(B[1]=0,b=1;b<15;b++)B[b+1]=B[b]+O[b];for(v=0;v<n;v++)0!==t[r+v]&&(a[B[t[r+v]]++]=v);if(d=0===e?(A=R=a,19):1===e?(A=F,I-=257,R=N,T-=257,256):(A=U,R=P,-1),b=y,c=s,S=v=E=0,l=-1,f=(C=1<<(x=k))-1,1===e&&852<C||2===e&&592<C)return 1;for(;;){for(p=b-S,_=a[v]<d?(m=0,a[v]):a[v]>d?(m=R[T+a[v]],A[I+a[v]]):(m=96,0),h=1<<b-S,y=u=1<<x;i[c+(E>>S)+(u-=h)]=p<<24|m<<16|_|0,0!==u;);for(h=1<<b-1;E&h;)h>>=1;if(0!==h?(E&=h-1,E+=h):E=0,v++,0==--O[b]){if(b===w)break;b=t[r+a[v]];}if(k<b&&(E&f)!==l){for(0===S&&(S=k),c+=y,z=1<<(x=b-S);x+S<w&&!((z-=O[x+S])<=0);)x++,z<<=1;if(C+=1<<x,1===e&&852<C||2===e&&592<C)return 1;i[l=E&f]=k<<24|x<<16|c-s|0;}}return 0!==E&&(i[c+E]=b-S<<24|64<<16|0),o.bits=k,0};},{"../utils/common":41}],51:[function(e,t,r){t.exports={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"};},{}],52:[function(e,t,r){var i=e("../utils/common"),o=0,h=1;function n(e){for(var t=e.length;0<=--t;)e[t]=0;}var s=0,a=29,u=256,l=u+1+a,f=30,c=19,_=2*l+1,g=15,d=16,p=7,m=256,b=16,v=17,y=18,w=[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],k=[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],x=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],z=new Array(2*(l+2));n(z);var C=new Array(2*f);n(C);var E=new Array(512);n(E);var A=new Array(256);n(A);var I=new Array(a);n(I);var O,B,R,T=new Array(f);function D(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length;}function F(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t;}function N(e){return e<256?E[e]:E[256+(e>>>7)]}function U(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255;}function P(e,t,r){e.bi_valid>d-r?(e.bi_buf|=t<<e.bi_valid&65535,U(e,e.bi_buf),e.bi_buf=t>>d-e.bi_valid,e.bi_valid+=r-d):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r);}function L(e,t,r){P(e,r[2*t],r[2*t+1]);}function j(e,t){for(var r=0;r|=1&e,e>>>=1,r<<=1,0<--t;);return r>>>1}function Z(e,t,r){var n,i,s=new Array(g+1),a=0;for(n=1;n<=g;n++)s[n]=a=a+r[n-1]<<1;for(i=0;i<=t;i++){var o=e[2*i+1];0!==o&&(e[2*i]=j(s[o]++,o));}}function W(e){var t;for(t=0;t<l;t++)e.dyn_ltree[2*t]=0;for(t=0;t<f;t++)e.dyn_dtree[2*t]=0;for(t=0;t<c;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*m]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0;}function M(e){8<e.bi_valid?U(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0;}function H(e,t,r,n){var i=2*t,s=2*r;return e[i]<e[s]||e[i]===e[s]&&n[t]<=n[r]}function G(e,t,r){for(var n=e.heap[r],i=r<<1;i<=e.heap_len&&(i<e.heap_len&&H(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!H(t,n,e.heap[i],e.depth));)e.heap[r]=e.heap[i],r=i,i<<=1;e.heap[r]=n;}function K(e,t,r){var n,i,s,a,o=0;if(0!==e.last_lit)for(;n=e.pending_buf[e.d_buf+2*o]<<8|e.pending_buf[e.d_buf+2*o+1],i=e.pending_buf[e.l_buf+o],o++,0===n?L(e,i,t):(L(e,(s=A[i])+u+1,t),0!==(a=w[s])&&P(e,i-=I[s],a),L(e,s=N(--n),r),0!==(a=k[s])&&P(e,n-=T[s],a)),o<e.last_lit;);L(e,m,t);}function Y(e,t){var r,n,i,s=t.dyn_tree,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,h=t.stat_desc.elems,u=-1;for(e.heap_len=0,e.heap_max=_,r=0;r<h;r++)0!==s[2*r]?(e.heap[++e.heap_len]=u=r,e.depth[r]=0):s[2*r+1]=0;for(;e.heap_len<2;)s[2*(i=e.heap[++e.heap_len]=u<2?++u:0)]=1,e.depth[i]=0,e.opt_len--,o&&(e.static_len-=a[2*i+1]);for(t.max_code=u,r=e.heap_len>>1;1<=r;r--)G(e,s,r);for(i=h;r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],G(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,s[2*i]=s[2*r]+s[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,s[2*r+1]=s[2*n+1]=i,e.heap[1]=i++,G(e,s,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,s,a,o,h=t.dyn_tree,u=t.max_code,l=t.stat_desc.static_tree,f=t.stat_desc.has_stree,c=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=g;s++)e.bl_count[s]=0;for(h[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<_;r++)p<(s=h[2*h[2*(n=e.heap[r])+1]+1]+1)&&(s=p,m++),h[2*n+1]=s,u<n||(e.bl_count[s]++,a=0,d<=n&&(a=c[n-d]),o=h[2*n],e.opt_len+=o*(s+a),f&&(e.static_len+=o*(l[2*n+1]+a)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2;}while(0<m);for(s=p;0!==s;s--)for(n=e.bl_count[s];0!==n;)u<(i=e.heap[--r])||(h[2*i+1]!==s&&(e.opt_len+=(s-h[2*i+1])*h[2*i],h[2*i+1]=s),n--);}}(e,t),Z(s,u,e.bl_count);}function X(e,t,r){var n,i,s=-1,a=t[1],o=0,h=7,u=4;for(0===a&&(h=138,u=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=a,a=t[2*(n+1)+1],++o<h&&i===a||(o<u?e.bl_tree[2*i]+=o:0!==i?(i!==s&&e.bl_tree[2*i]++,e.bl_tree[2*b]++):o<=10?e.bl_tree[2*v]++:e.bl_tree[2*y]++,s=i,u=(o=0)===a?(h=138,3):i===a?(h=6,3):(h=7,4));}function V(e,t,r){var n,i,s=-1,a=t[1],o=0,h=7,u=4;for(0===a&&(h=138,u=3),n=0;n<=r;n++)if(i=a,a=t[2*(n+1)+1],!(++o<h&&i===a)){if(o<u)for(;L(e,i,e.bl_tree),0!=--o;);else 0!==i?(i!==s&&(L(e,i,e.bl_tree),o--),L(e,b,e.bl_tree),P(e,o-3,2)):o<=10?(L(e,v,e.bl_tree),P(e,o-3,3)):(L(e,y,e.bl_tree),P(e,o-11,7));s=i,u=(o=0)===a?(h=138,3):i===a?(h=6,3):(h=7,4);}}n(T);var q=!1;function J(e,t,r,n){P(e,(s<<1)+(n?1:0),3),function(e,t,r,n){M(e),n&&(U(e,r),U(e,~r)),i.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r;}(e,t,r,!0);}r._tr_init=function(e){q||(function(){var e,t,r,n,i,s=new Array(g+1);for(n=r=0;n<a-1;n++)for(I[n]=r,e=0;e<1<<w[n];e++)A[r++]=n;for(A[r-1]=n,n=i=0;n<16;n++)for(T[n]=i,e=0;e<1<<k[n];e++)E[i++]=n;for(i>>=7;n<f;n++)for(T[n]=i<<7,e=0;e<1<<k[n]-7;e++)E[256+i++]=n;for(t=0;t<=g;t++)s[t]=0;for(e=0;e<=143;)z[2*e+1]=8,e++,s[8]++;for(;e<=255;)z[2*e+1]=9,e++,s[9]++;for(;e<=279;)z[2*e+1]=7,e++,s[7]++;for(;e<=287;)z[2*e+1]=8,e++,s[8]++;for(Z(z,l+1,s),e=0;e<f;e++)C[2*e+1]=5,C[2*e]=j(e,5);O=new D(z,w,u+1,l,g),B=new D(C,k,0,f,g),R=new D(new Array(0),x,0,c,p);}(),q=!0),e.l_desc=new F(e.dyn_ltree,O),e.d_desc=new F(e.dyn_dtree,B),e.bl_desc=new F(e.bl_tree,R),e.bi_buf=0,e.bi_valid=0,W(e);},r._tr_stored_block=J,r._tr_flush_block=function(e,t,r,n){var i,s,a=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return h;for(t=32;t<u;t++)if(0!==e.dyn_ltree[2*t])return h;return o}(e)),Y(e,e.l_desc),Y(e,e.d_desc),a=function(e){var t;for(X(e,e.dyn_ltree,e.l_desc.max_code),X(e,e.dyn_dtree,e.d_desc.max_code),Y(e,e.bl_desc),t=c-1;3<=t&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=i&&(i=s)):i=s=r+5,r+4<=i&&-1!==t?J(e,t,r,n):4===e.strategy||s===i?(P(e,2+(n?1:0),3),K(e,z,C)):(P(e,4+(n?1:0),3),function(e,t,r,n){var i;for(P(e,t-257,5),P(e,r-1,5),P(e,n-4,4),i=0;i<n;i++)P(e,e.bl_tree[2*S[i]+1],3);V(e,e.dyn_ltree,t-1),V(e,e.dyn_dtree,r-1);}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),K(e,e.dyn_ltree,e.dyn_dtree)),W(e),n&&M(e);},r._tr_tally=function(e,t,r){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(A[r]+u+1)]++,e.dyn_dtree[2*N(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){P(e,2,3),L(e,m,z),function(e){16===e.bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8);}(e);};},{"../utils/common":41}],53:[function(e,t,r){t.exports=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;};},{}],54:[function(e,t,r){(function(e){!function(r,n){if(!r.setImmediate){var i,s,t,a,o=1,h={},u=!1,l=r.document,e=Object.getPrototypeOf&&Object.getPrototypeOf(r);e=e&&e.setTimeout?e:r,i="[object process]"==={}.toString.call(r.process)?function(e){process.nextTick(function(){c(e);});}:function(){if(r.postMessage&&!r.importScripts){var e=!0,t=r.onmessage;return r.onmessage=function(){e=!1;},r.postMessage("","*"),r.onmessage=t,e}}()?(a="setImmediate$"+Math.random()+"$",r.addEventListener?r.addEventListener("message",d,!1):r.attachEvent("onmessage",d),function(e){r.postMessage(a+e,"*");}):r.MessageChannel?((t=new MessageChannel).port1.onmessage=function(e){c(e.data);},function(e){t.port2.postMessage(e);}):l&&"onreadystatechange"in l.createElement("script")?(s=l.documentElement,function(e){var t=l.createElement("script");t.onreadystatechange=function(){c(e),t.onreadystatechange=null,s.removeChild(t),t=null;},s.appendChild(t);}):function(e){setTimeout(c,0,e);},e.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;r<t.length;r++)t[r]=arguments[r+1];var n={callback:e,args:t};return h[o]=n,i(o),o++},e.clearImmediate=f;}function f(e){delete h[e];}function c(e){if(u)setTimeout(c,0,e);else {var t=h[e];if(t){u=!0;try{!function(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(n,r);}}(t);}finally{f(e),u=!1;}}}}function d(e){e.source===r&&"string"==typeof e.data&&0===e.data.indexOf(a)&&c(+e.data.slice(a.length));}}("undefined"==typeof self?void 0===e?this:e:self);}).call(this,"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});},{}]},{},[10])(10)});
    } (jszip_min));

    let versionData = {
        sdk: "",
        lib: "",
    };
    (function () {
        const { version } = { "version": "26.0.0" };
        versionData.lib = version;
    })();
    (function () {
        const { version } = { "version": "1.5.0" };
        versionData.sdk = version;
    })();
    const SDK_VERSION = versionData.sdk;
    const LIB_VERSION = versionData.lib;

    function getPermissionState(name) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const permission = yield navigator.permissions.query({ name });
                return permission.state;
            }
            catch (e) {
                return "unavailable";
            }
        });
    }
    class Action {
        constructor(client) {
            this.client = client;
            this.feedback = new FeedbackAction(client);
        }
        uploadFile(file, options) {
            return new WebapiFileUploader(this.client.api, file, options);
        }
        sendFeedback(message, attachments = [], options = {}) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.feedback.send(message, attachments, options);
            });
        }
        generateFeedbackData(message, attachments = []) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.feedback.generateData(message, attachments);
            });
        }
    }
    class FeedbackAction {
        constructor(client) {
            this.sendingLog = false;
            this.lastLogRequest = new Date(Date.now() -  10 * 60 * 60000);
            this.client = client;
            this.log = Log.of("feedback", this.client);
        }
        sendUnattended(commandId, message) {
            return __awaiter(this, void 0, void 0, function* () {
                const log = Log.of("commandReceiveNotificationHandler", this.client);
                const diff = Date.now() - this.lastLogRequest.getTime();
                if (diff >  60000) {
                    log.info(`last send feedback request, send more than 1 minute ago, start operation to send new log; message received: '${message}'`);
                    try {
                        const sendFeedback = yield this.generateAndSend(commandId, message);
                        if (sendFeedback) {
                            this.lastLogRequest = new Date();
                        }
                        else {
                            throw new Error("Request failed. Try again");
                        }
                    }
                    catch (e) {
                        log.error("error generateAndSend", e);
                    }
                }
                else {
                    log.warn("last send feedback request, send less than 1 minute, nothing to do, must waiting");
                    throw new Error("Request for user's log made less than a minute ago, must waiting");
                }
            });
        }
        send(message, attachments = [], options = {}) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.generateAndSend(undefined, message, attachments, options);
            });
        }
        generateAndSend(deviceCommandId, message, attachments = [], options = {}) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.sendingLog) {
                    throw new Error("Just one request for the same user's log is in progress, request failed");
                }
                this.log.info("start feedback generate and send");
                try {
                    this.sendingLog = true;
                    const feedbackData = yield this.generateData(message, attachments);
                    const feedbackFile = yield feedbackData.toZipFile(options.compress);
                    if (feedbackFile) {
                        this.log.info("upload file to server");
                        try {
                            yield this.client.action.uploadFile(feedbackFile, options.upload).upload();
                        }
                        catch (e) {
                            this.log.error("error on upload file to server", e);
                            throw e;
                        }
                    }
                    else {
                        this.log.warn("feedback file is empty, problems when genereting zip file");
                        throw new Error("error genereting zip file");
                    }
                    const sendFeedbackResult = yield this.client.api.methods.sendFeedback({ body: message, attachment: feedbackFile.name, deviceCommandId }, 15000);
                    if (sendFeedbackResult) {
                        this.log.info("feedback sent successfully");
                    }
                    else {
                        this.log.warn("send fedback request returned false!");
                    }
                    return sendFeedbackResult;
                }
                finally {
                    this.sendingLog = false;
                }
            });
        }
        generateData(message, attachments = []) {
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function* () {
                const feedbackComponet = new exports.Feedback.Data(this.client);
                feedbackComponet.attachments = attachments;
                const feedbackBody = [];
                feedbackBody.push(`SENT AT: ${feedbackComponet.time.toISOString()}`);
                feedbackBody.push(`USER: ${this.client.user.info.username}`);
                feedbackBody.push(`TVox SDK Version (in use) : ${SDK_VERSION} ${LIB_VERSION}`);
                feedbackBody.push(`Server URL (current) : ${this.client.configuration.url}`);
                feedbackBody.push(`Server Version (current) : ${(_a = this.client.loginData) === null || _a === void 0 ? void 0 : _a.serverVersion}`);
                feedbackBody.push(`Protocol version (current): ${(_b = this.client.loginData) === null || _b === void 0 ? void 0 : _b.apiVersion}`);
                feedbackBody.push("\n");
                feedbackBody.push(`document ----------------------------------------------------------------------- \n`);
                feedbackBody.push(`hasFocus: ${window.document.hasFocus()}`);
                feedbackBody.push(`hasStorageAccess: ${window.document.hasStorageAccess ? yield window.document.hasStorageAccess() : "unavailable"}`);
                feedbackBody.push("\n");
                feedbackBody.push(`navigator ---------------------------------------------------------------------- \n`);
                feedbackBody.push(`userAgent: ${navigator.userAgent}`);
                if (navigator.userAgentData) {
                    feedbackBody.push(`userAgentData: ${JSON.stringify(navigator.userAgentData)}`);
                }
                feedbackBody.push(`permission "microphone": ${yield getPermissionState("microphone")}`);
                feedbackBody.push(`permission "camera": ${yield getPermissionState("camera")}`);
                feedbackBody.push(`permission "storage-access": ${yield getPermissionState("storage-access")}`);
                feedbackBody.push(`permission "notifications": ${yield getPermissionState("notifications")}`);
                feedbackBody.push(`permission "push ": ${yield getPermissionState("push")}`);
                feedbackBody.push("\n");
                feedbackBody.push(`sdk data ------------------------------------------------------------------------ \n`);
                feedbackBody.push(`instance id: ${this.client.api.instanceId}`);
                feedbackBody.push(`phone managed by TVox client: ${this.client.phone.managedByTVoxClient}`);
                feedbackBody.push(`phone type: ${(_c = this.client.phone.device) === null || _c === void 0 ? void 0 : _c.type}`);
                feedbackBody.push(`--------------------------------------------------------------------------------- \n`);
                feedbackBody.push("\n");
                feedbackBody.push(message !== null && message !== void 0 ? message : "");
                feedbackComponet.body = feedbackBody.join("\n");
                this.log.info("start retrieve log from storage");
                let logsBlob;
                try {
                    logsBlob = new Blob(Array.from(yield this.client.api.logger.dumpStoredLogToIterable()).map((logLine) => logLine + "\n"), { type: "text/plain" });
                }
                catch (e) {
                    this.log.error("error during dump log", e);
                    throw e;
                }
                feedbackComponet.logFile = logsBlob;
                this.log.info("log from storage retrieved");
                return feedbackComponet;
            });
        }
    }
    exports.Feedback = void 0;
    (function (Feedback) {
        class Data {
            constructor(
            client) {
                this.client = client;
                this.time = new Date();
                this.log = Log.of("feedback:data", this.client);
                this.name = `${this.client.user.info.username}_feedback_${Math.floor(this.time.getTime() / 1000)}`;
            }
            toZipFile(options) {
                var _a, _b;
                return __awaiter(this, void 0, void 0, function* () {
                    if (this.zipFile) {
                        return this.zipFile;
                    }
                    const zipFile = new jszip_minExports();
                    zipFile.file("feedback.txt", this.body);
                    zipFile.file(`${this.name}.log`, this.logFile);
                    if (this.attachments && this.attachments.length) {
                        const attachmentsFolder = zipFile.folder("attachments");
                        if (attachmentsFolder) {
                            this.attachments.forEach((attachment) => {
                                attachmentsFolder.file(attachment.name, attachment);
                            });
                        }
                    }
                    let zipBlob;
                    this.log.info(`generate zip file ${this.name}.zip`);
                    try {
                        const fileComment = `username ${this.client.user.info.username}\ninstanceId ${this.client.api.instanceId}\ntime ${this.time}\nserver ${this.client.configuration.url}\ndocumentHasFocus ${window.document.hasFocus()}`;
                        const onProgress = ((_a = options === null || options === void 0 ? void 0 : options.callbacks) === null || _a === void 0 ? void 0 : _a.onProgress) ? (metadata) => options.callbacks.onProgress(metadata.percent) : undefined;
                        let compressionLevel = (_b = options === null || options === void 0 ? void 0 : options.level) !== null && _b !== void 0 ? _b : 0;
                        if (compressionLevel < 0) {
                            compressionLevel = 0;
                        }
                        else if (compressionLevel > 9) {
                            compressionLevel = 9;
                        }
                        zipBlob = yield zipFile.generateAsync({ type: "blob", compression: compressionLevel ? "DEFLATE" : "STORE", compressionOptions: compressionLevel ? { level: compressionLevel } : null, streamFiles: true, comment: fileComment }, onProgress);
                    }
                    catch (e) {
                        this.log.error("error while compressing. Error received", e);
                        throw e;
                    }
                    const file = new File([zipBlob], `${this.name}.zip`);
                    this.log.info(`zip file ${this.name}.zip created`);
                    this.zipFile = file;
                    return file;
                });
            }
        }
        Feedback.Data = Data;
    })(exports.Feedback || (exports.Feedback = {}));

    class Client extends EventEmitter {
        constructor(configuration) {
            super(Client.PKG);
            this._state = Client.ClientState.LOGIN_REQUIRED;
            this.commandReceived$ = new Subject();
            this.configuration = configuration;
            this.api = new WebapiClient(this.mapConfigurationToWebapiConfig());
            this._logger = new Client.ClientLogger(this.api.logger);
            this.init(this);
            this.api.webrtc = new WebRTCManager({ enabled: false, enabledOnChannel: [ChannelType.PhoneCall], selfManagedDeviceActivity: true, customUseDeviceHistoryStore: configuration.webrtc && configuration.webrtc.useDeviceHistoryStore ? new UseDeviceHistoryStoreWrapper(configuration.webrtc.useDeviceHistoryStore) : null });
            this.transport = new Transport(this);
            this.user = new User(this);
            this.phone = new Phone(this);
            this.action = new Action(this);
            this.on("login_in_progress", () => {
                this._state = Client.ClientState.LOGIN_IN_PROGRESS;
            });
            this.on("login_failed", () => {
                this._state = Client.ClientState.LOGIN_FAILED;
            });
            this.on("logged_out", () => {
                this._state = Client.ClientState.LOGIN_REQUIRED;
            });
            this.commandReceived$
                .pipe(filter((data) => data.command.command == ClientCommandRequest.SEND_FEEDBACK), concatMap(({ command, subscriber }) => __awaiter(this, void 0, void 0, function* () {
                const result = yield (() => __awaiter(this, void 0, void 0, function* () {
                    const sendFeedbackCommand = command;
                    try {
                        yield this.action.feedback.sendUnattended(sendFeedbackCommand.id, sendFeedbackCommand.message);
                        return { result: ClientCommandResult.OK };
                    }
                    catch (e) {
                        return { result: ClientCommandResult.FAILED, resultMessage: e instanceof Error ? e.message : typeof e === "string" ? e : "Unknown error on sendFeedback" };
                    }
                }))();
                subscriber.next(result);
                subscriber.complete();
            })), catchError((err, obs) => {
                this.log.error("Action error: ", err);
                return obs;
            }))
                .subscribe();
        }
        get state() {
            return this._state;
        }
        set state(status) {
            this._state = status;
        }
        get logConfigurator() {
            return this._logger;
        }
        get instanceId() {
            return this.api.instanceId;
        }
        get loginData() {
            return this._loginData;
        }
        mapConfigurationToWebapiConfig() {
            const configuration = this.configuration;
            const logConfig = Log.toWebapiConfig(configuration.log);
            if (!logConfig.storage) {
                if ("indexedDB" in window) {
                    if (!indexedDBLogStore) {
                        indexedDBLogStore = new IndexedDBLogStore({ enabled: true, clearLogIntervalMillis: 2 * 60 * 60 * 1000, logRetentionMillis: 2 * 60 * 60 * 1000 });
                    }
                    logConfig.storage = {
                        store: indexedDBLogStore.store.bind(indexedDBLogStore),
                        dump: indexedDBLogStore.dump.bind(indexedDBLogStore),
                    };
                }
            }
            return {
                url: configuration.url.endsWith("/clientproxy") ? configuration.url : `${configuration.url}/clientproxy`,
                userAgent: { type: "custom", version: SDK_VERSION, description: `TVox SDK ${SDK_VERSION} ${LIB_VERSION}` },
                remoteCommandHandler: this.remoteCommandHandler.bind(this),
                phoneManagerActive: !(this.configuration.phoneManagedByTVoxClient || false),
                selfManagedLogin: false,
                multisession: true,
                logConfig,
                retryOptions: configuration.retryOptions,
            };
        }
        login(credential) {
            var _a;
            return __awaiter(this, void 0, void 0, function* () {
                const rememberMe = (_a = this.api.options.rememberMe) !== null && _a !== void 0 ? _a : false;
                let validCredential = true;
                let loginProfile = null;
                try {
                    if (isBasicCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.serviceMethods.login(credential.username, credential.password, rememberMe);
                    }
                    else if (isBerearCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.serviceMethods.loginByAccessToken(credential.token, rememberMe);
                    }
                    else if (isExternalSessionIdCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.serviceMethods.loginCustom(credential.externalSessionId, rememberMe);
                    }
                    else if (isJwtCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.serviceMethods.loginByJwtToken(credential.jwt, rememberMe);
                    }
                    else {
                        validCredential = false;
                    }
                }
                catch (error) {
                    this.emit("login_failed", error, this.user);
                    throw error;
                }
                if (!validCredential) {
                    throw "invalid credential, only Basic or Bearer or ExternalSessionId is allowed";
                }
                if (loginProfile) {
                    this._loginData = new Client.LoginData(credential, loginProfile);
                }
                else {
                    throw "invalid response from login";
                }
            });
        }
        logout(reason, note) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.api.serviceMethods.logoutAndExit({ reason, note });
            });
        }
        isLogged() {
            var _a;
            if (isApiLoginProfileBehaviourSubject(this.api.loginProfile)) {
                return (_a = this.api.loginProfile.value.logged) !== null && _a !== void 0 ? _a : false;
            }
            else {
                return this.user.state === User.State.LOGGED;
            }
        }
        canDoRequest() {
            return __awaiter(this, void 0, void 0, function* () {
                if (Client.ClientState.READY === this.state) {
                    return;
                }
                else {
                    throw "Client is not ready to request data";
                }
            });
        }
        remoteCommandHandler(command) {
            return __awaiter(this, void 0, void 0, function* () {
                const timeoutValue = (() => {
                    switch (command.command) {
                        case ClientCommandRequest.SEND_FEEDBACK:
                            return 300000;
                        case ClientCommandRequest.DIAL:
                            return 60000;
                        default:
                            return 2000;
                    }
                })();
                return toPromise(new Observable((subscriber) => {
                    this.commandReceived$.next({ command, subscriber });
                }).pipe(timeout(timeoutValue)));
            });
        }
    }
    Client.ready = "ready";
    Client.logged_in = "logged_in";
    Client.logged_out = "logged_out";
    Client.login_in_progress = "login_in_progress";
    Client.login_failed = "login_failed";
    class UseDeviceHistoryStoreWrapper {
        constructor({ get, set }) {
            this.getProto = get;
            this.setProto = set;
        }
        get() {
            return __awaiter(this, void 0, void 0, function* () {
                return this.getProto();
            });
        }
        set(history) {
            return __awaiter(this, void 0, void 0, function* () {
                return this.setProto(history);
            });
        }
    }
    function isApiLoginProfileBehaviourSubject(observable) {
        return !!observable.value;
    }
    function isBasicCredential(credential) {
        return credential.username !== undefined;
    }
    function isBerearCredential(credential) {
        return credential.token !== undefined;
    }
    function isExternalSessionIdCredential(credential) {
        return credential.externalSessionId !== undefined;
    }
    function isJwtCredential(credential) {
        return credential.jwt !== undefined;
    }
    var indexedDBLogStore;
    (function (Client) {
        Client.PKG = "client";
        (function (ClientState) {
            ClientState["READY"] = "READY";
            ClientState["LOGIN_REQUIRED"] = "LOGIN_REQUIRED";
            ClientState["LOGIN_IN_PROGRESS"] = "LOGIN_IN_PROGRESS";
            ClientState["LOGIN_FAILED"] = "LOGIN_FAILED";
        })(Client.ClientState || (Client.ClientState = {}));
        class LoginData {
            constructor(credential, loginResult) {
                this.credential = credential;
                this.accessToken = loginResult.accessToken;
                this.serverVersion = loginResult.serverVersion;
                this.apiVersion = loginResult.apiVersion;
                this.sessionId = loginResult.sessionId;
            }
        }
        Client.LoginData = LoginData;
        class ClientLogger extends Log.Logger {
            constructor(
            apiLogger) {
                super();
                this.apiLogger = apiLogger;
            }
            get enabled() {
                return this.apiLogger.enabled;
            }
            set enabled(enabled) {
                this.apiLogger.enabled = enabled;
            }
            get objectToJson() {
                return this.apiLogger.objectToJson;
            }
            set objectToJson(objectToJson) {
                this.apiLogger.objectToJson = !!objectToJson;
            }
            set instanceIdLogged(instanceIdLogged) {
                this.apiLogger.instanceIdLogged = !!instanceIdLogged;
            }
            get instanceIdLogged() {
                return this.apiLogger.instanceIdLogged;
            }
            set logLevel(logLevel) {
                if (logLevel && logLevel >= Log.LogLevel.Verbose && logLevel <= Log.LogLevel.None) {
                    this.apiLogger.logLevel = logLevel;
                }
            }
            get logLevel() {
                return this.enabled ? this.apiLogger.logLevel : Log.LogLevel.None;
            }
            get prefix() {
                return this.apiLogger.prefix;
            }
            set prefix(prefix) {
                this.apiLogger.prefix = prefix;
            }
            get timestamp() {
                return this.apiLogger.timestamp;
            }
            set timestamp(timestamp) {
                this.apiLogger.timestamp = !!timestamp;
            }
        }
        Client.ClientLogger = ClientLogger;
    })(Client || (Client = {}));

    exports.Action = Action;
    exports.Call = Call$1;
    exports.CallSip = CallSip;
    exports.CallSipForTransfer = CallSipForTransfer;
    exports.CallWebrtc = CallWebrtc;
    exports.Client = Client;
    exports.Contact = Contact;
    exports.DeviceSip = DeviceSip;
    exports.DeviceWebrtc = DeviceWebrtc;
    exports.DeviceWebrtcMedia = DeviceWebrtcMedia;
    exports.EventEmitter = EventEmitter;
    exports.ExternalItemContact = ExternalItemContact;
    exports.ExternalOrganizationContact = ExternalOrganizationContact;
    exports.IndexedDBLogStore = IndexedDBLogStore;
    exports.IndexedDBService = IndexedDBService;
    exports.InternalServiceContact = InternalServiceContact;
    exports.InternalShortNumberContact = InternalShortNumberContact;
    exports.InternalUserContact = InternalUserContact;
    exports.LIB_VERSION = LIB_VERSION;
    exports.Log = Log;
    exports.PersonalContact = PersonalContact;
    exports.Phone = Phone;
    exports.Profile = Profile;
    exports.ProfileAgent = ProfileAgent;
    exports.SDK_VERSION = SDK_VERSION;
    exports.SearchResult = SearchResult;
    exports.Transport = Transport;
    exports.User = User;
    exports.UserStatusMonitor = UserStatusMonitor;
    exports.delayedChannelEventHandler = delayedChannelEventHandler;
    exports.emptyStringValue = emptyStringValue;
    exports.isContact = isContact;
    exports.isString = isString;
    exports.mergeObject = mergeObject;
    exports.toPromise = toPromise;

    return exports;

})({});
//# sourceMappingURL=index.js.map
