/**
 * TVox v1.3.0
 * Referenced: 22.1.0
 * 
 * Dependencies:
 * tslib -- 1.14.1
 * rxjs -- 6.6.7
 * ms -- 2.1.2
 * debug -- 4.3.4
 * lodash-es -- 4.17.21
 * cookie -- 0.4.2
 * webrtc-adapter -- 8.2.3
 * sdp -- 3.2.0
 * sdp-transform -- 2.14.1
 * detect-browser -- 5.3.0
 * retry -- 0.12.0
 * eventemitter3 -- 4.0.7
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define('TVox', ['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TVox = {}));
})(this, (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 (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends$m(d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign$5 = function() {
        __assign$5 = 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$5.apply(this, arguments);
    };
    function __awaiter$n(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 isFunction$1(x) {
        return typeof x === 'function';
    }

    var _enable_super_gross_mode_that_will_cause_bad_things = false;
    var config = {
        Promise: undefined,
        set useDeprecatedSynchronousErrorHandling(value) {
            if (value) {
                var error =  new Error();
                 console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
            }
            else if (_enable_super_gross_mode_that_will_cause_bad_things) {
                 console.log('RxJS: Back to a better error behavior. Thank you. <3');
            }
            _enable_super_gross_mode_that_will_cause_bad_things = value;
        },
        get useDeprecatedSynchronousErrorHandling() {
            return _enable_super_gross_mode_that_will_cause_bad_things;
        },
    };

    function hostReportError(err) {
        setTimeout(function () { throw err; }, 0);
    }

    var empty$1 = {
        closed: true,
        next: function (value) { },
        error: function (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                hostReportError(err);
            }
        },
        complete: function () { }
    };

    var isArray$2 =  (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();

    function isObject$2(x) {
        return x !== null && typeof x === 'object';
    }

    var UnsubscriptionErrorImpl =  (function () {
        function UnsubscriptionErrorImpl(errors) {
            Error.call(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;
            return this;
        }
        UnsubscriptionErrorImpl.prototype =  Object.create(Error.prototype);
        return UnsubscriptionErrorImpl;
    })();
    var UnsubscriptionError = UnsubscriptionErrorImpl;

    var Subscription =  (function () {
        function Subscription(unsubscribe) {
            this.closed = false;
            this._parentOrParents = null;
            this._subscriptions = null;
            if (unsubscribe) {
                this._ctorUnsubscribe = true;
                this._unsubscribe = unsubscribe;
            }
        }
        Subscription.prototype.unsubscribe = function () {
            var errors;
            if (this.closed) {
                return;
            }
            var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
            this.closed = true;
            this._parentOrParents = null;
            this._subscriptions = null;
            if (_parentOrParents instanceof Subscription) {
                _parentOrParents.remove(this);
            }
            else if (_parentOrParents !== null) {
                for (var index = 0; index < _parentOrParents.length; ++index) {
                    var parent_1 = _parentOrParents[index];
                    parent_1.remove(this);
                }
            }
            if (isFunction$1(_unsubscribe)) {
                if (_ctorUnsubscribe) {
                    this._unsubscribe = undefined;
                }
                try {
                    _unsubscribe.call(this);
                }
                catch (e) {
                    errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
                }
            }
            if (isArray$2(_subscriptions)) {
                var index = -1;
                var len = _subscriptions.length;
                while (++index < len) {
                    var sub = _subscriptions[index];
                    if (isObject$2(sub)) {
                        try {
                            sub.unsubscribe();
                        }
                        catch (e) {
                            errors = errors || [];
                            if (e instanceof UnsubscriptionError) {
                                errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                            }
                            else {
                                errors.push(e);
                            }
                        }
                    }
                }
            }
            if (errors) {
                throw new UnsubscriptionError(errors);
            }
        };
        Subscription.prototype.add = function (teardown) {
            var subscription = teardown;
            if (!teardown) {
                return Subscription.EMPTY;
            }
            switch (typeof teardown) {
                case 'function':
                    subscription = new Subscription(teardown);
                case 'object':
                    if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                        return subscription;
                    }
                    else if (this.closed) {
                        subscription.unsubscribe();
                        return subscription;
                    }
                    else if (!(subscription instanceof Subscription)) {
                        var tmp = subscription;
                        subscription = new Subscription();
                        subscription._subscriptions = [tmp];
                    }
                    break;
                default: {
                    throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
                }
            }
            var _parentOrParents = subscription._parentOrParents;
            if (_parentOrParents === null) {
                subscription._parentOrParents = this;
            }
            else if (_parentOrParents instanceof Subscription) {
                if (_parentOrParents === this) {
                    return subscription;
                }
                subscription._parentOrParents = [_parentOrParents, this];
            }
            else if (_parentOrParents.indexOf(this) === -1) {
                _parentOrParents.push(this);
            }
            else {
                return subscription;
            }
            var subscriptions = this._subscriptions;
            if (subscriptions === null) {
                this._subscriptions = [subscription];
            }
            else {
                subscriptions.push(subscription);
            }
            return subscription;
        };
        Subscription.prototype.remove = function (subscription) {
            var subscriptions = this._subscriptions;
            if (subscriptions) {
                var subscriptionIndex = subscriptions.indexOf(subscription);
                if (subscriptionIndex !== -1) {
                    subscriptions.splice(subscriptionIndex, 1);
                }
            }
        };
        Subscription.EMPTY = (function (empty) {
            empty.closed = true;
            return empty;
        }(new Subscription()));
        return Subscription;
    }());
    function flattenUnsubscriptionErrors(errors) {
        return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
    }

    var rxSubscriber =  (function () {
        return typeof Symbol === 'function'
            ?  Symbol('rxSubscriber')
            : '@@rxSubscriber_' +  Math.random();
    })();

    var Subscriber =  (function (_super) {
        __extends$m(Subscriber, _super);
        function Subscriber(destinationOrNext, error, complete) {
            var _this = _super.call(this) || this;
            _this.syncErrorValue = null;
            _this.syncErrorThrown = false;
            _this.syncErrorThrowable = false;
            _this.isStopped = false;
            switch (arguments.length) {
                case 0:
                    _this.destination = empty$1;
                    break;
                case 1:
                    if (!destinationOrNext) {
                        _this.destination = empty$1;
                        break;
                    }
                    if (typeof destinationOrNext === 'object') {
                        if (destinationOrNext instanceof Subscriber) {
                            _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                            _this.destination = destinationOrNext;
                            destinationOrNext.add(_this);
                        }
                        else {
                            _this.syncErrorThrowable = true;
                            _this.destination = new SafeSubscriber(_this, destinationOrNext);
                        }
                        break;
                    }
                default:
                    _this.syncErrorThrowable = true;
                    _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                    break;
            }
            return _this;
        }
        Subscriber.prototype[rxSubscriber] = function () { return this; };
        Subscriber.create = function (next, error, complete) {
            var subscriber = new Subscriber(next, error, complete);
            subscriber.syncErrorThrowable = false;
            return subscriber;
        };
        Subscriber.prototype.next = function (value) {
            if (!this.isStopped) {
                this._next(value);
            }
        };
        Subscriber.prototype.error = function (err) {
            if (!this.isStopped) {
                this.isStopped = true;
                this._error(err);
            }
        };
        Subscriber.prototype.complete = function () {
            if (!this.isStopped) {
                this.isStopped = true;
                this._complete();
            }
        };
        Subscriber.prototype.unsubscribe = function () {
            if (this.closed) {
                return;
            }
            this.isStopped = true;
            _super.prototype.unsubscribe.call(this);
        };
        Subscriber.prototype._next = function (value) {
            this.destination.next(value);
        };
        Subscriber.prototype._error = function (err) {
            this.destination.error(err);
            this.unsubscribe();
        };
        Subscriber.prototype._complete = function () {
            this.destination.complete();
            this.unsubscribe();
        };
        Subscriber.prototype._unsubscribeAndRecycle = function () {
            var _parentOrParents = this._parentOrParents;
            this._parentOrParents = null;
            this.unsubscribe();
            this.closed = false;
            this.isStopped = false;
            this._parentOrParents = _parentOrParents;
            return this;
        };
        return Subscriber;
    }(Subscription));
    var SafeSubscriber =  (function (_super) {
        __extends$m(SafeSubscriber, _super);
        function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
            var _this = _super.call(this) || this;
            _this._parentSubscriber = _parentSubscriber;
            var next;
            var context = _this;
            if (isFunction$1(observerOrNext)) {
                next = observerOrNext;
            }
            else if (observerOrNext) {
                next = observerOrNext.next;
                error = observerOrNext.error;
                complete = observerOrNext.complete;
                if (observerOrNext !== empty$1) {
                    context = Object.create(observerOrNext);
                    if (isFunction$1(context.unsubscribe)) {
                        _this.add(context.unsubscribe.bind(context));
                    }
                    context.unsubscribe = _this.unsubscribe.bind(_this);
                }
            }
            _this._context = context;
            _this._next = next;
            _this._error = error;
            _this._complete = complete;
            return _this;
        }
        SafeSubscriber.prototype.next = function (value) {
            if (!this.isStopped && this._next) {
                var _parentSubscriber = this._parentSubscriber;
                if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._next, value);
                }
                else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                    this.unsubscribe();
                }
            }
        };
        SafeSubscriber.prototype.error = function (err) {
            if (!this.isStopped) {
                var _parentSubscriber = this._parentSubscriber;
                var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
                if (this._error) {
                    if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                        this.__tryOrUnsub(this._error, err);
                        this.unsubscribe();
                    }
                    else {
                        this.__tryOrSetError(_parentSubscriber, this._error, err);
                        this.unsubscribe();
                    }
                }
                else if (!_parentSubscriber.syncErrorThrowable) {
                    this.unsubscribe();
                    if (useDeprecatedSynchronousErrorHandling) {
                        throw err;
                    }
                    hostReportError(err);
                }
                else {
                    if (useDeprecatedSynchronousErrorHandling) {
                        _parentSubscriber.syncErrorValue = err;
                        _parentSubscriber.syncErrorThrown = true;
                    }
                    else {
                        hostReportError(err);
                    }
                    this.unsubscribe();
                }
            }
        };
        SafeSubscriber.prototype.complete = function () {
            var _this = this;
            if (!this.isStopped) {
                var _parentSubscriber = this._parentSubscriber;
                if (this._complete) {
                    var wrappedComplete = function () { return _this._complete.call(_this._context); };
                    if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                        this.__tryOrUnsub(wrappedComplete);
                        this.unsubscribe();
                    }
                    else {
                        this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                        this.unsubscribe();
                    }
                }
                else {
                    this.unsubscribe();
                }
            }
        };
        SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
            try {
                fn.call(this._context, value);
            }
            catch (err) {
                this.unsubscribe();
                if (config.useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                else {
                    hostReportError(err);
                }
            }
        };
        SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
            if (!config.useDeprecatedSynchronousErrorHandling) {
                throw new Error('bad call');
            }
            try {
                fn.call(this._context, value);
            }
            catch (err) {
                if (config.useDeprecatedSynchronousErrorHandling) {
                    parent.syncErrorValue = err;
                    parent.syncErrorThrown = true;
                    return true;
                }
                else {
                    hostReportError(err);
                    return true;
                }
            }
            return false;
        };
        SafeSubscriber.prototype._unsubscribe = function () {
            var _parentSubscriber = this._parentSubscriber;
            this._context = null;
            this._parentSubscriber = null;
            _parentSubscriber.unsubscribe();
        };
        return SafeSubscriber;
    }(Subscriber));

    function canReportError(observer) {
        while (observer) {
            var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
            if (closed_1 || isStopped) {
                return false;
            }
            else if (destination && destination instanceof Subscriber) {
                observer = destination;
            }
            else {
                observer = null;
            }
        }
        return true;
    }

    function toSubscriber(nextOrObserver, error, complete) {
        if (nextOrObserver) {
            if (nextOrObserver instanceof Subscriber) {
                return nextOrObserver;
            }
            if (nextOrObserver[rxSubscriber]) {
                return nextOrObserver[rxSubscriber]();
            }
        }
        if (!nextOrObserver && !error && !complete) {
            return new Subscriber(empty$1);
        }
        return new Subscriber(nextOrObserver, error, complete);
    }

    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) {
            this._isScalar = false;
            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 operator = this.operator;
            var sink = toSubscriber(observerOrNext, error, complete);
            if (operator) {
                sink.add(operator.call(sink, this.source));
            }
            else {
                sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                    this._subscribe(sink) :
                    this._trySubscribe(sink));
            }
            if (config.useDeprecatedSynchronousErrorHandling) {
                if (sink.syncErrorThrowable) {
                    sink.syncErrorThrowable = false;
                    if (sink.syncErrorThrown) {
                        throw sink.syncErrorValue;
                    }
                }
            }
            return sink;
        };
        Observable.prototype._trySubscribe = function (sink) {
            try {
                return this._subscribe(sink);
            }
            catch (err) {
                if (config.useDeprecatedSynchronousErrorHandling) {
                    sink.syncErrorThrown = true;
                    sink.syncErrorValue = err;
                }
                if (canReportError(sink)) {
                    sink.error(err);
                }
                else {
                    console.warn(err);
                }
            }
        };
        Observable.prototype.forEach = function (next, promiseCtor) {
            var _this = this;
            promiseCtor = getPromiseCtor(promiseCtor);
            return new promiseCtor(function (resolve, reject) {
                var subscription;
                subscription = _this.subscribe(function (value) {
                    try {
                        next(value);
                    }
                    catch (err) {
                        reject(err);
                        if (subscription) {
                            subscription.unsubscribe();
                        }
                    }
                }, reject, resolve);
            });
        };
        Observable.prototype._subscribe = function (subscriber) {
            var source = this.source;
            return source && source.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];
            }
            if (operations.length === 0) {
                return this;
            }
            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) {
        if (!promiseCtor) {
            promiseCtor = config.Promise || Promise;
        }
        if (!promiseCtor) {
            throw new Error('no Promise impl found');
        }
        return promiseCtor;
    }

    var ObjectUnsubscribedErrorImpl =  (function () {
        function ObjectUnsubscribedErrorImpl() {
            Error.call(this);
            this.message = 'object unsubscribed';
            this.name = 'ObjectUnsubscribedError';
            return this;
        }
        ObjectUnsubscribedErrorImpl.prototype =  Object.create(Error.prototype);
        return ObjectUnsubscribedErrorImpl;
    })();
    var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;

    var SubjectSubscription =  (function (_super) {
        __extends$m(SubjectSubscription, _super);
        function SubjectSubscription(subject, subscriber) {
            var _this = _super.call(this) || this;
            _this.subject = subject;
            _this.subscriber = subscriber;
            _this.closed = false;
            return _this;
        }
        SubjectSubscription.prototype.unsubscribe = function () {
            if (this.closed) {
                return;
            }
            this.closed = true;
            var subject = this.subject;
            var observers = subject.observers;
            this.subject = null;
            if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
                return;
            }
            var subscriberIndex = observers.indexOf(this.subscriber);
            if (subscriberIndex !== -1) {
                observers.splice(subscriberIndex, 1);
            }
        };
        return SubjectSubscription;
    }(Subscription));

    var SubjectSubscriber =  (function (_super) {
        __extends$m(SubjectSubscriber, _super);
        function SubjectSubscriber(destination) {
            var _this = _super.call(this, destination) || this;
            _this.destination = destination;
            return _this;
        }
        return SubjectSubscriber;
    }(Subscriber));
    var Subject =  (function (_super) {
        __extends$m(Subject, _super);
        function Subject() {
            var _this = _super.call(this) || this;
            _this.observers = [];
            _this.closed = false;
            _this.isStopped = false;
            _this.hasError = false;
            _this.thrownError = null;
            return _this;
        }
        Subject.prototype[rxSubscriber] = function () {
            return new SubjectSubscriber(this);
        };
        Subject.prototype.lift = function (operator) {
            var subject = new AnonymousSubject(this, this);
            subject.operator = operator;
            return subject;
        };
        Subject.prototype.next = function (value) {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            if (!this.isStopped) {
                var observers = this.observers;
                var len = observers.length;
                var copy = observers.slice();
                for (var i = 0; i < len; i++) {
                    copy[i].next(value);
                }
            }
        };
        Subject.prototype.error = function (err) {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            this.hasError = true;
            this.thrownError = err;
            this.isStopped = true;
            var observers = this.observers;
            var len = observers.length;
            var copy = observers.slice();
            for (var i = 0; i < len; i++) {
                copy[i].error(err);
            }
            this.observers.length = 0;
        };
        Subject.prototype.complete = function () {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            this.isStopped = true;
            var observers = this.observers;
            var len = observers.length;
            var copy = observers.slice();
            for (var i = 0; i < len; i++) {
                copy[i].complete();
            }
            this.observers.length = 0;
        };
        Subject.prototype.unsubscribe = function () {
            this.isStopped = true;
            this.closed = true;
            this.observers = null;
        };
        Subject.prototype._trySubscribe = function (subscriber) {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            else {
                return _super.prototype._trySubscribe.call(this, subscriber);
            }
        };
        Subject.prototype._subscribe = function (subscriber) {
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            else if (this.hasError) {
                subscriber.error(this.thrownError);
                return Subscription.EMPTY;
            }
            else if (this.isStopped) {
                subscriber.complete();
                return Subscription.EMPTY;
            }
            else {
                this.observers.push(subscriber);
                return new SubjectSubscription(this, subscriber);
            }
        };
        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$m(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 destination = this.destination;
            if (destination && destination.next) {
                destination.next(value);
            }
        };
        AnonymousSubject.prototype.error = function (err) {
            var destination = this.destination;
            if (destination && destination.error) {
                this.destination.error(err);
            }
        };
        AnonymousSubject.prototype.complete = function () {
            var destination = this.destination;
            if (destination && destination.complete) {
                this.destination.complete();
            }
        };
        AnonymousSubject.prototype._subscribe = function (subscriber) {
            var source = this.source;
            if (source) {
                return this.source.subscribe(subscriber);
            }
            else {
                return Subscription.EMPTY;
            }
        };
        return AnonymousSubject;
    }(Subject));

    function refCount() {
        return function refCountOperatorFunction(source) {
            return source.lift(new RefCountOperator(source));
        };
    }
    var RefCountOperator =  (function () {
        function RefCountOperator(connectable) {
            this.connectable = connectable;
        }
        RefCountOperator.prototype.call = function (subscriber, source) {
            var connectable = this.connectable;
            connectable._refCount++;
            var refCounter = new RefCountSubscriber(subscriber, connectable);
            var subscription = source.subscribe(refCounter);
            if (!refCounter.closed) {
                refCounter.connection = connectable.connect();
            }
            return subscription;
        };
        return RefCountOperator;
    }());
    var RefCountSubscriber =  (function (_super) {
        __extends$m(RefCountSubscriber, _super);
        function RefCountSubscriber(destination, connectable) {
            var _this = _super.call(this, destination) || this;
            _this.connectable = connectable;
            return _this;
        }
        RefCountSubscriber.prototype._unsubscribe = function () {
            var connectable = this.connectable;
            if (!connectable) {
                this.connection = null;
                return;
            }
            this.connectable = null;
            var refCount = connectable._refCount;
            if (refCount <= 0) {
                this.connection = null;
                return;
            }
            connectable._refCount = refCount - 1;
            if (refCount > 1) {
                this.connection = null;
                return;
            }
            var connection = this.connection;
            var sharedConnection = connectable._connection;
            this.connection = null;
            if (sharedConnection && (!connection || sharedConnection === connection)) {
                sharedConnection.unsubscribe();
            }
        };
        return RefCountSubscriber;
    }(Subscriber));

    var ConnectableObservable =  (function (_super) {
        __extends$m(ConnectableObservable, _super);
        function ConnectableObservable(source, subjectFactory) {
            var _this = _super.call(this) || this;
            _this.source = source;
            _this.subjectFactory = subjectFactory;
            _this._refCount = 0;
            _this._isComplete = false;
            return _this;
        }
        ConnectableObservable.prototype._subscribe = function (subscriber) {
            return this.getSubject().subscribe(subscriber);
        };
        ConnectableObservable.prototype.getSubject = function () {
            var subject = this._subject;
            if (!subject || subject.isStopped) {
                this._subject = this.subjectFactory();
            }
            return this._subject;
        };
        ConnectableObservable.prototype.connect = function () {
            var connection = this._connection;
            if (!connection) {
                this._isComplete = false;
                connection = this._connection = new Subscription();
                connection.add(this.source
                    .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
                if (connection.closed) {
                    this._connection = null;
                    connection = Subscription.EMPTY;
                }
            }
            return connection;
        };
        ConnectableObservable.prototype.refCount = function () {
            return refCount()(this);
        };
        return ConnectableObservable;
    }(Observable));
    var connectableObservableDescriptor =  (function () {
        var connectableProto = ConnectableObservable.prototype;
        return {
            operator: { value: null },
            _refCount: { value: 0, writable: true },
            _subject: { value: null, writable: true },
            _connection: { value: null, writable: true },
            _subscribe: { value: connectableProto._subscribe },
            _isComplete: { value: connectableProto._isComplete, writable: true },
            getSubject: { value: connectableProto.getSubject },
            connect: { value: connectableProto.connect },
            refCount: { value: connectableProto.refCount }
        };
    })();
    var ConnectableSubscriber =  (function (_super) {
        __extends$m(ConnectableSubscriber, _super);
        function ConnectableSubscriber(destination, connectable) {
            var _this = _super.call(this, destination) || this;
            _this.connectable = connectable;
            return _this;
        }
        ConnectableSubscriber.prototype._error = function (err) {
            this._unsubscribe();
            _super.prototype._error.call(this, err);
        };
        ConnectableSubscriber.prototype._complete = function () {
            this.connectable._isComplete = true;
            this._unsubscribe();
            _super.prototype._complete.call(this);
        };
        ConnectableSubscriber.prototype._unsubscribe = function () {
            var connectable = this.connectable;
            if (connectable) {
                this.connectable = null;
                var connection = connectable._connection;
                connectable._refCount = 0;
                connectable._subject = null;
                connectable._connection = null;
                if (connection) {
                    connection.unsubscribe();
                }
            }
        };
        return ConnectableSubscriber;
    }(SubjectSubscriber));
    ((function (_super) {
        __extends$m(RefCountSubscriber, _super);
        function RefCountSubscriber(destination, connectable) {
            var _this = _super.call(this, destination) || this;
            _this.connectable = connectable;
            return _this;
        }
        RefCountSubscriber.prototype._unsubscribe = function () {
            var connectable = this.connectable;
            if (!connectable) {
                this.connection = null;
                return;
            }
            this.connectable = null;
            var refCount = connectable._refCount;
            if (refCount <= 0) {
                this.connection = null;
                return;
            }
            connectable._refCount = refCount - 1;
            if (refCount > 1) {
                this.connection = null;
                return;
            }
            var connection = this.connection;
            var sharedConnection = connectable._connection;
            this.connection = null;
            if (sharedConnection && (!connection || sharedConnection === connection)) {
                sharedConnection.unsubscribe();
            }
        };
        return RefCountSubscriber;
    })(Subscriber));

    var BehaviorSubject =  (function (_super) {
        __extends$m(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: true,
            configurable: true
        });
        BehaviorSubject.prototype._subscribe = function (subscriber) {
            var subscription = _super.prototype._subscribe.call(this, subscriber);
            if (subscription && !subscription.closed) {
                subscriber.next(this._value);
            }
            return subscription;
        };
        BehaviorSubject.prototype.getValue = function () {
            if (this.hasError) {
                throw this.thrownError;
            }
            else if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            else {
                return this._value;
            }
        };
        BehaviorSubject.prototype.next = function (value) {
            _super.prototype.next.call(this, this._value = value);
        };
        return BehaviorSubject;
    }(Subject));

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

    var AsyncAction =  (function (_super) {
        __extends$m(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) {
            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 = this.id || this.requestAsyncId(scheduler, this.id, delay);
            return this;
        };
        AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
            if (delay === void 0) {
                delay = 0;
            }
            return 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;
            }
            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 = undefined;
            try {
                this.work(state);
            }
            catch (e) {
                errored = true;
                errorValue = !!e && e || new Error(e);
            }
            if (errored) {
                this.unsubscribe();
                return errorValue;
            }
        };
        AsyncAction.prototype._unsubscribe = function () {
            var id = this.id;
            var scheduler = this.scheduler;
            var actions = scheduler.actions;
            var index = actions.indexOf(this);
            this.work = null;
            this.state = null;
            this.pending = false;
            this.scheduler = null;
            if (index !== -1) {
                actions.splice(index, 1);
            }
            if (id != null) {
                this.id = this.recycleAsyncId(scheduler, id, null);
            }
            this.delay = null;
        };
        return AsyncAction;
    }(Action));

    var QueueAction =  (function (_super) {
        __extends$m(QueueAction, _super);
        function QueueAction(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            return _this;
        }
        QueueAction.prototype.schedule = function (state, delay) {
            if (delay === void 0) {
                delay = 0;
            }
            if (delay > 0) {
                return _super.prototype.schedule.call(this, state, delay);
            }
            this.delay = delay;
            this.state = state;
            this.scheduler.flush(this);
            return this;
        };
        QueueAction.prototype.execute = function (state, delay) {
            return (delay > 0 || this.closed) ?
                _super.prototype.execute.call(this, state, delay) :
                this._execute(state, delay);
        };
        QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
            if (delay === void 0) {
                delay = 0;
            }
            if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
                return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
            }
            return scheduler.flush(this);
        };
        return QueueAction;
    }(AsyncAction));

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

    var AsyncScheduler =  (function (_super) {
        __extends$m(AsyncScheduler, _super);
        function AsyncScheduler(SchedulerAction, now) {
            if (now === void 0) {
                now = Scheduler.now;
            }
            var _this = _super.call(this, SchedulerAction, function () {
                if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {
                    return AsyncScheduler.delegate.now();
                }
                else {
                    return now();
                }
            }) || this;
            _this.actions = [];
            _this.active = false;
            _this.scheduled = undefined;
            return _this;
        }
        AsyncScheduler.prototype.schedule = function (work, delay, state) {
            if (delay === void 0) {
                delay = 0;
            }
            if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
                return AsyncScheduler.delegate.schedule(work, delay, state);
            }
            else {
                return _super.prototype.schedule.call(this, work, delay, state);
            }
        };
        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 QueueScheduler =  (function (_super) {
        __extends$m(QueueScheduler, _super);
        function QueueScheduler() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return QueueScheduler;
    }(AsyncScheduler));

    var queueScheduler =  new QueueScheduler(QueueAction);
    var queue = queueScheduler;

    var EMPTY =  new Observable(function (subscriber) { return subscriber.complete(); });
    function empty(scheduler) {
        return scheduler ? emptyScheduled(scheduler) : EMPTY;
    }
    function emptyScheduled(scheduler) {
        return new Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
    }

    function isScheduler(value) {
        return value && typeof value.schedule === 'function';
    }

    var subscribeToArray = function (array) {
        return function (subscriber) {
            for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
                subscriber.next(array[i]);
            }
            subscriber.complete();
        };
    };

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

    function fromArray(input, scheduler) {
        if (!scheduler) {
            return new Observable(subscribeToArray(input));
        }
        else {
            return scheduleArray(input, scheduler);
        }
    }

    function of() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var scheduler = args[args.length - 1];
        if (isScheduler(scheduler)) {
            args.pop();
            return scheduleArray(args, scheduler);
        }
        else {
            return fromArray(args);
        }
    }

    function throwError(error, scheduler) {
        if (!scheduler) {
            return new Observable(function (subscriber) { return subscriber.error(error); });
        }
        else {
            return new Observable(function (subscriber) { return scheduler.schedule(dispatch$1, 0, { error: error, subscriber: subscriber }); });
        }
    }
    function dispatch$1(_a) {
        var error = _a.error, subscriber = _a.subscriber;
        subscriber.error(error);
    }

    var NotificationKind;
     (function (NotificationKind) {
        NotificationKind["NEXT"] = "N";
        NotificationKind["ERROR"] = "E";
        NotificationKind["COMPLETE"] = "C";
    })(NotificationKind || (NotificationKind = {}));
    var Notification =  (function () {
        function Notification(kind, value, error) {
            this.kind = kind;
            this.value = value;
            this.error = error;
            this.hasValue = kind === 'N';
        }
        Notification.prototype.observe = function (observer) {
            switch (this.kind) {
                case 'N':
                    return observer.next && observer.next(this.value);
                case 'E':
                    return observer.error && observer.error(this.error);
                case 'C':
                    return observer.complete && observer.complete();
            }
        };
        Notification.prototype.do = function (next, error, complete) {
            var kind = this.kind;
            switch (kind) {
                case 'N':
                    return next && next(this.value);
                case 'E':
                    return error && error(this.error);
                case 'C':
                    return complete && complete();
            }
        };
        Notification.prototype.accept = function (nextOrObserver, error, complete) {
            if (nextOrObserver && typeof nextOrObserver.next === 'function') {
                return this.observe(nextOrObserver);
            }
            else {
                return this.do(nextOrObserver, error, complete);
            }
        };
        Notification.prototype.toObservable = function () {
            var kind = this.kind;
            switch (kind) {
                case 'N':
                    return of(this.value);
                case 'E':
                    return throwError(this.error);
                case 'C':
                    return empty();
            }
            throw new Error('unexpected notification kind value');
        };
        Notification.createNext = function (value) {
            if (typeof value !== 'undefined') {
                return new Notification('N', value);
            }
            return Notification.undefinedValueNotification;
        };
        Notification.createError = function (err) {
            return new Notification('E', undefined, err);
        };
        Notification.createComplete = function () {
            return Notification.completeNotification;
        };
        Notification.completeNotification = new Notification('C');
        Notification.undefinedValueNotification = new Notification('N', undefined);
        return Notification;
    }());

    var ObserveOnSubscriber =  (function (_super) {
        __extends$m(ObserveOnSubscriber, _super);
        function ObserveOnSubscriber(destination, scheduler, delay) {
            if (delay === void 0) {
                delay = 0;
            }
            var _this = _super.call(this, destination) || this;
            _this.scheduler = scheduler;
            _this.delay = delay;
            return _this;
        }
        ObserveOnSubscriber.dispatch = function (arg) {
            var notification = arg.notification, destination = arg.destination;
            notification.observe(destination);
            this.unsubscribe();
        };
        ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
            var destination = this.destination;
            destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
        };
        ObserveOnSubscriber.prototype._next = function (value) {
            this.scheduleMessage(Notification.createNext(value));
        };
        ObserveOnSubscriber.prototype._error = function (err) {
            this.scheduleMessage(Notification.createError(err));
            this.unsubscribe();
        };
        ObserveOnSubscriber.prototype._complete = function () {
            this.scheduleMessage(Notification.createComplete());
            this.unsubscribe();
        };
        return ObserveOnSubscriber;
    }(Subscriber));
    var ObserveOnMessage =  (function () {
        function ObserveOnMessage(notification, destination) {
            this.notification = notification;
            this.destination = destination;
        }
        return ObserveOnMessage;
    }());

    var ReplaySubject =  (function (_super) {
        __extends$m(ReplaySubject, _super);
        function ReplaySubject(bufferSize, windowTime, scheduler) {
            if (bufferSize === void 0) {
                bufferSize = Number.POSITIVE_INFINITY;
            }
            if (windowTime === void 0) {
                windowTime = Number.POSITIVE_INFINITY;
            }
            var _this = _super.call(this) || this;
            _this.scheduler = scheduler;
            _this._events = [];
            _this._infiniteTimeWindow = false;
            _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
            _this._windowTime = windowTime < 1 ? 1 : windowTime;
            if (windowTime === Number.POSITIVE_INFINITY) {
                _this._infiniteTimeWindow = true;
                _this.next = _this.nextInfiniteTimeWindow;
            }
            else {
                _this.next = _this.nextTimeWindow;
            }
            return _this;
        }
        ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {
            if (!this.isStopped) {
                var _events = this._events;
                _events.push(value);
                if (_events.length > this._bufferSize) {
                    _events.shift();
                }
            }
            _super.prototype.next.call(this, value);
        };
        ReplaySubject.prototype.nextTimeWindow = function (value) {
            if (!this.isStopped) {
                this._events.push(new ReplayEvent(this._getNow(), value));
                this._trimBufferThenGetEvents();
            }
            _super.prototype.next.call(this, value);
        };
        ReplaySubject.prototype._subscribe = function (subscriber) {
            var _infiniteTimeWindow = this._infiniteTimeWindow;
            var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
            var scheduler = this.scheduler;
            var len = _events.length;
            var subscription;
            if (this.closed) {
                throw new ObjectUnsubscribedError();
            }
            else if (this.isStopped || this.hasError) {
                subscription = Subscription.EMPTY;
            }
            else {
                this.observers.push(subscriber);
                subscription = new SubjectSubscription(this, subscriber);
            }
            if (scheduler) {
                subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
            }
            if (_infiniteTimeWindow) {
                for (var i = 0; i < len && !subscriber.closed; i++) {
                    subscriber.next(_events[i]);
                }
            }
            else {
                for (var i = 0; i < len && !subscriber.closed; i++) {
                    subscriber.next(_events[i].value);
                }
            }
            if (this.hasError) {
                subscriber.error(this.thrownError);
            }
            else if (this.isStopped) {
                subscriber.complete();
            }
            return subscription;
        };
        ReplaySubject.prototype._getNow = function () {
            return (this.scheduler || queue).now();
        };
        ReplaySubject.prototype._trimBufferThenGetEvents = function () {
            var now = this._getNow();
            var _bufferSize = this._bufferSize;
            var _windowTime = this._windowTime;
            var _events = this._events;
            var eventsCount = _events.length;
            var spliceCount = 0;
            while (spliceCount < eventsCount) {
                if ((now - _events[spliceCount].time) < _windowTime) {
                    break;
                }
                spliceCount++;
            }
            if (eventsCount > _bufferSize) {
                spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
            }
            if (spliceCount > 0) {
                _events.splice(0, spliceCount);
            }
            return _events;
        };
        return ReplaySubject;
    }(Subject));
    var ReplayEvent =  (function () {
        function ReplayEvent(time, value) {
            this.time = time;
            this.value = value;
        }
        return ReplayEvent;
    }());

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

    function noop$1() { }

    var ArgumentOutOfRangeErrorImpl =  (function () {
        function ArgumentOutOfRangeErrorImpl() {
            Error.call(this);
            this.message = 'argument out of range';
            this.name = 'ArgumentOutOfRangeError';
            return this;
        }
        ArgumentOutOfRangeErrorImpl.prototype =  Object.create(Error.prototype);
        return ArgumentOutOfRangeErrorImpl;
    })();
    var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;

    var EmptyErrorImpl =  (function () {
        function EmptyErrorImpl() {
            Error.call(this);
            this.message = 'no elements in sequence';
            this.name = 'EmptyError';
            return this;
        }
        EmptyErrorImpl.prototype =  Object.create(Error.prototype);
        return EmptyErrorImpl;
    })();
    var EmptyError = EmptyErrorImpl;

    var TimeoutErrorImpl =  (function () {
        function TimeoutErrorImpl() {
            Error.call(this);
            this.message = 'Timeout has occurred';
            this.name = 'TimeoutError';
            return this;
        }
        TimeoutErrorImpl.prototype =  Object.create(Error.prototype);
        return TimeoutErrorImpl;
    })();
    var TimeoutError = TimeoutErrorImpl;

    function map(project, thisArg) {
        return function mapOperation(source) {
            if (typeof project !== 'function') {
                throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
            }
            return source.lift(new MapOperator(project, thisArg));
        };
    }
    var MapOperator =  (function () {
        function MapOperator(project, thisArg) {
            this.project = project;
            this.thisArg = thisArg;
        }
        MapOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
        };
        return MapOperator;
    }());
    var MapSubscriber =  (function (_super) {
        __extends$m(MapSubscriber, _super);
        function MapSubscriber(destination, project, thisArg) {
            var _this = _super.call(this, destination) || this;
            _this.project = project;
            _this.count = 0;
            _this.thisArg = thisArg || _this;
            return _this;
        }
        MapSubscriber.prototype._next = function (value) {
            var result;
            try {
                result = this.project.call(this.thisArg, value, this.count++);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            this.destination.next(result);
        };
        return MapSubscriber;
    }(Subscriber));

    var OuterSubscriber =  (function (_super) {
        __extends$m(OuterSubscriber, _super);
        function OuterSubscriber() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
            this.destination.next(innerValue);
        };
        OuterSubscriber.prototype.notifyError = function (error, innerSub) {
            this.destination.error(error);
        };
        OuterSubscriber.prototype.notifyComplete = function (innerSub) {
            this.destination.complete();
        };
        return OuterSubscriber;
    }(Subscriber));

    var InnerSubscriber =  (function (_super) {
        __extends$m(InnerSubscriber, _super);
        function InnerSubscriber(parent, outerValue, outerIndex) {
            var _this = _super.call(this) || this;
            _this.parent = parent;
            _this.outerValue = outerValue;
            _this.outerIndex = outerIndex;
            _this.index = 0;
            return _this;
        }
        InnerSubscriber.prototype._next = function (value) {
            this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
        };
        InnerSubscriber.prototype._error = function (error) {
            this.parent.notifyError(error, this);
            this.unsubscribe();
        };
        InnerSubscriber.prototype._complete = function () {
            this.parent.notifyComplete(this);
            this.unsubscribe();
        };
        return InnerSubscriber;
    }(Subscriber));

    var subscribeToPromise = function (promise) {
        return function (subscriber) {
            promise.then(function (value) {
                if (!subscriber.closed) {
                    subscriber.next(value);
                    subscriber.complete();
                }
            }, function (err) { return subscriber.error(err); })
                .then(null, hostReportError);
            return subscriber;
        };
    };

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

    var subscribeToIterable = function (iterable) {
        return function (subscriber) {
            var iterator$1 = iterable[iterator]();
            do {
                var item = void 0;
                try {
                    item = iterator$1.next();
                }
                catch (err) {
                    subscriber.error(err);
                    return subscriber;
                }
                if (item.done) {
                    subscriber.complete();
                    break;
                }
                subscriber.next(item.value);
                if (subscriber.closed) {
                    break;
                }
            } while (true);
            if (typeof iterator$1.return === 'function') {
                subscriber.add(function () {
                    if (iterator$1.return) {
                        iterator$1.return();
                    }
                });
            }
            return subscriber;
        };
    };

    var subscribeToObservable = function (obj) {
        return function (subscriber) {
            var obs = obj[observable]();
            if (typeof obs.subscribe !== 'function') {
                throw new TypeError('Provided object does not correctly implement Symbol.observable');
            }
            else {
                return obs.subscribe(subscriber);
            }
        };
    };

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

    function isPromise(value) {
        return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
    }

    var subscribeTo = function (result) {
        if (!!result && typeof result[observable] === 'function') {
            return subscribeToObservable(result);
        }
        else if (isArrayLike$1(result)) {
            return subscribeToArray(result);
        }
        else if (isPromise(result)) {
            return subscribeToPromise(result);
        }
        else if (!!result && typeof result[iterator] === 'function') {
            return subscribeToIterable(result);
        }
        else {
            var value = isObject$2(result) ? 'an invalid object' : "'" + result + "'";
            var msg = "You provided " + value + " where a stream was expected."
                + ' You can provide an Observable, Promise, Array, or Iterable.';
            throw new TypeError(msg);
        }
    };

    function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) {
        if (innerSubscriber === void 0) {
            innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex);
        }
        if (innerSubscriber.closed) {
            return undefined;
        }
        if (result instanceof Observable) {
            return result.subscribe(innerSubscriber);
        }
        return subscribeTo(result)(innerSubscriber);
    }

    var NONE = {};
    function combineLatest() {
        var observables = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            observables[_i] = arguments[_i];
        }
        var resultSelector = undefined;
        var scheduler = undefined;
        if (isScheduler(observables[observables.length - 1])) {
            scheduler = observables.pop();
        }
        if (typeof observables[observables.length - 1] === 'function') {
            resultSelector = observables.pop();
        }
        if (observables.length === 1 && isArray$2(observables[0])) {
            observables = observables[0];
        }
        return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
    }
    var CombineLatestOperator =  (function () {
        function CombineLatestOperator(resultSelector) {
            this.resultSelector = resultSelector;
        }
        CombineLatestOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
        };
        return CombineLatestOperator;
    }());
    var CombineLatestSubscriber =  (function (_super) {
        __extends$m(CombineLatestSubscriber, _super);
        function CombineLatestSubscriber(destination, resultSelector) {
            var _this = _super.call(this, destination) || this;
            _this.resultSelector = resultSelector;
            _this.active = 0;
            _this.values = [];
            _this.observables = [];
            return _this;
        }
        CombineLatestSubscriber.prototype._next = function (observable) {
            this.values.push(NONE);
            this.observables.push(observable);
        };
        CombineLatestSubscriber.prototype._complete = function () {
            var observables = this.observables;
            var len = observables.length;
            if (len === 0) {
                this.destination.complete();
            }
            else {
                this.active = len;
                this.toRespond = len;
                for (var i = 0; i < len; i++) {
                    var observable = observables[i];
                    this.add(subscribeToResult(this, observable, undefined, i));
                }
            }
        };
        CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
            if ((this.active -= 1) === 0) {
                this.destination.complete();
            }
        };
        CombineLatestSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) {
            var values = this.values;
            var oldVal = values[outerIndex];
            var toRespond = !this.toRespond
                ? 0
                : oldVal === NONE ? --this.toRespond : this.toRespond;
            values[outerIndex] = innerValue;
            if (toRespond === 0) {
                if (this.resultSelector) {
                    this._tryResultSelector(values);
                }
                else {
                    this.destination.next(values.slice());
                }
            }
        };
        CombineLatestSubscriber.prototype._tryResultSelector = function (values) {
            var result;
            try {
                result = this.resultSelector.apply(this, values);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            this.destination.next(result);
        };
        return CombineLatestSubscriber;
    }(OuterSubscriber));

    function scheduleObservable(input, scheduler) {
        return new Observable(function (subscriber) {
            var sub = new Subscription();
            sub.add(scheduler.schedule(function () {
                var observable$1 = input[observable]();
                sub.add(observable$1.subscribe({
                    next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },
                    error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },
                    complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },
                }));
            }));
            return sub;
        });
    }

    function schedulePromise(input, scheduler) {
        return new Observable(function (subscriber) {
            var sub = new Subscription();
            sub.add(scheduler.schedule(function () {
                return input.then(function (value) {
                    sub.add(scheduler.schedule(function () {
                        subscriber.next(value);
                        sub.add(scheduler.schedule(function () { return subscriber.complete(); }));
                    }));
                }, function (err) {
                    sub.add(scheduler.schedule(function () { return subscriber.error(err); }));
                });
            }));
            return sub;
        });
    }

    function scheduleIterable(input, scheduler) {
        if (!input) {
            throw new Error('Iterable cannot be null');
        }
        return new Observable(function (subscriber) {
            var sub = new Subscription();
            var iterator$1;
            sub.add(function () {
                if (iterator$1 && typeof iterator$1.return === 'function') {
                    iterator$1.return();
                }
            });
            sub.add(scheduler.schedule(function () {
                iterator$1 = input[iterator]();
                sub.add(scheduler.schedule(function () {
                    if (subscriber.closed) {
                        return;
                    }
                    var value;
                    var done;
                    try {
                        var result = iterator$1.next();
                        value = result.value;
                        done = result.done;
                    }
                    catch (err) {
                        subscriber.error(err);
                        return;
                    }
                    if (done) {
                        subscriber.complete();
                    }
                    else {
                        subscriber.next(value);
                        this.schedule();
                    }
                }));
            }));
            return sub;
        });
    }

    function isInteropObservable(input) {
        return input && typeof input[observable] === 'function';
    }

    function isIterable(input) {
        return input && typeof input[iterator] === 'function';
    }

    function scheduled(input, scheduler) {
        if (input != null) {
            if (isInteropObservable(input)) {
                return scheduleObservable(input, scheduler);
            }
            else if (isPromise(input)) {
                return schedulePromise(input, scheduler);
            }
            else if (isArrayLike$1(input)) {
                return scheduleArray(input, scheduler);
            }
            else if (isIterable(input) || typeof input === 'string') {
                return scheduleIterable(input, scheduler);
            }
        }
        throw new TypeError((input !== null && typeof input || input) + ' is not observable');
    }

    function from(input, scheduler) {
        if (!scheduler) {
            if (input instanceof Observable) {
                return input;
            }
            return new Observable(subscribeTo(input));
        }
        else {
            return scheduled(input, scheduler);
        }
    }

    var SimpleInnerSubscriber =  (function (_super) {
        __extends$m(SimpleInnerSubscriber, _super);
        function SimpleInnerSubscriber(parent) {
            var _this = _super.call(this) || this;
            _this.parent = parent;
            return _this;
        }
        SimpleInnerSubscriber.prototype._next = function (value) {
            this.parent.notifyNext(value);
        };
        SimpleInnerSubscriber.prototype._error = function (error) {
            this.parent.notifyError(error);
            this.unsubscribe();
        };
        SimpleInnerSubscriber.prototype._complete = function () {
            this.parent.notifyComplete();
            this.unsubscribe();
        };
        return SimpleInnerSubscriber;
    }(Subscriber));
    ((function (_super) {
        __extends$m(ComplexInnerSubscriber, _super);
        function ComplexInnerSubscriber(parent, outerValue, outerIndex) {
            var _this = _super.call(this) || this;
            _this.parent = parent;
            _this.outerValue = outerValue;
            _this.outerIndex = outerIndex;
            return _this;
        }
        ComplexInnerSubscriber.prototype._next = function (value) {
            this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);
        };
        ComplexInnerSubscriber.prototype._error = function (error) {
            this.parent.notifyError(error);
            this.unsubscribe();
        };
        ComplexInnerSubscriber.prototype._complete = function () {
            this.parent.notifyComplete(this);
            this.unsubscribe();
        };
        return ComplexInnerSubscriber;
    })(Subscriber));
    var SimpleOuterSubscriber =  (function (_super) {
        __extends$m(SimpleOuterSubscriber, _super);
        function SimpleOuterSubscriber() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) {
            this.destination.next(innerValue);
        };
        SimpleOuterSubscriber.prototype.notifyError = function (err) {
            this.destination.error(err);
        };
        SimpleOuterSubscriber.prototype.notifyComplete = function () {
            this.destination.complete();
        };
        return SimpleOuterSubscriber;
    }(Subscriber));
    ((function (_super) {
        __extends$m(ComplexOuterSubscriber, _super);
        function ComplexOuterSubscriber() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ComplexOuterSubscriber.prototype.notifyNext = function (_outerValue, innerValue, _outerIndex, _innerSub) {
            this.destination.next(innerValue);
        };
        ComplexOuterSubscriber.prototype.notifyError = function (error) {
            this.destination.error(error);
        };
        ComplexOuterSubscriber.prototype.notifyComplete = function (_innerSub) {
            this.destination.complete();
        };
        return ComplexOuterSubscriber;
    })(Subscriber));
    function innerSubscribe(result, innerSubscriber) {
        if (innerSubscriber.closed) {
            return undefined;
        }
        if (result instanceof Observable) {
            return result.subscribe(innerSubscriber);
        }
        var subscription;
        try {
            subscription = subscribeTo(result)(innerSubscriber);
        }
        catch (error) {
            innerSubscriber.error(error);
        }
        return subscription;
    }

    function mergeMap(project, resultSelector, concurrent) {
        if (concurrent === void 0) {
            concurrent = Number.POSITIVE_INFINITY;
        }
        if (typeof resultSelector === 'function') {
            return function (source) { return source.pipe(mergeMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };
        }
        else if (typeof resultSelector === 'number') {
            concurrent = resultSelector;
        }
        return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };
    }
    var MergeMapOperator =  (function () {
        function MergeMapOperator(project, concurrent) {
            if (concurrent === void 0) {
                concurrent = Number.POSITIVE_INFINITY;
            }
            this.project = project;
            this.concurrent = concurrent;
        }
        MergeMapOperator.prototype.call = function (observer, source) {
            return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
        };
        return MergeMapOperator;
    }());
    var MergeMapSubscriber =  (function (_super) {
        __extends$m(MergeMapSubscriber, _super);
        function MergeMapSubscriber(destination, project, concurrent) {
            if (concurrent === void 0) {
                concurrent = Number.POSITIVE_INFINITY;
            }
            var _this = _super.call(this, destination) || this;
            _this.project = project;
            _this.concurrent = concurrent;
            _this.hasCompleted = false;
            _this.buffer = [];
            _this.active = 0;
            _this.index = 0;
            return _this;
        }
        MergeMapSubscriber.prototype._next = function (value) {
            if (this.active < this.concurrent) {
                this._tryNext(value);
            }
            else {
                this.buffer.push(value);
            }
        };
        MergeMapSubscriber.prototype._tryNext = function (value) {
            var result;
            var index = this.index++;
            try {
                result = this.project(value, index);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            this.active++;
            this._innerSub(result);
        };
        MergeMapSubscriber.prototype._innerSub = function (ish) {
            var innerSubscriber = new SimpleInnerSubscriber(this);
            var destination = this.destination;
            destination.add(innerSubscriber);
            var innerSubscription = innerSubscribe(ish, innerSubscriber);
            if (innerSubscription !== innerSubscriber) {
                destination.add(innerSubscription);
            }
        };
        MergeMapSubscriber.prototype._complete = function () {
            this.hasCompleted = true;
            if (this.active === 0 && this.buffer.length === 0) {
                this.destination.complete();
            }
            this.unsubscribe();
        };
        MergeMapSubscriber.prototype.notifyNext = function (innerValue) {
            this.destination.next(innerValue);
        };
        MergeMapSubscriber.prototype.notifyComplete = function () {
            var buffer = this.buffer;
            this.active--;
            if (buffer.length > 0) {
                this._next(buffer.shift());
            }
            else if (this.active === 0 && this.hasCompleted) {
                this.destination.complete();
            }
        };
        return MergeMapSubscriber;
    }(SimpleOuterSubscriber));

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

    function defer(observableFactory) {
        return new Observable(function (subscriber) {
            var input;
            try {
                input = observableFactory();
            }
            catch (err) {
                subscriber.error(err);
                return undefined;
            }
            var source = input ? from(input) : empty();
            return source.subscribe(subscriber);
        });
    }

    function fromEvent(target, eventName, options, resultSelector) {
        if (isFunction$1(options)) {
            resultSelector = options;
            options = undefined;
        }
        if (resultSelector) {
            return fromEvent(target, eventName, options).pipe(map(function (args) { return isArray$2(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
        }
        return new Observable(function (subscriber) {
            function handler(e) {
                if (arguments.length > 1) {
                    subscriber.next(Array.prototype.slice.call(arguments));
                }
                else {
                    subscriber.next(e);
                }
            }
            setupSubscription(target, eventName, handler, subscriber, options);
        });
    }
    function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
        var unsubscribe;
        if (isEventTarget(sourceObj)) {
            var source_1 = sourceObj;
            sourceObj.addEventListener(eventName, handler, options);
            unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
        }
        else if (isJQueryStyleEventEmitter(sourceObj)) {
            var source_2 = sourceObj;
            sourceObj.on(eventName, handler);
            unsubscribe = function () { return source_2.off(eventName, handler); };
        }
        else if (isNodeStyleEventEmitter(sourceObj)) {
            var source_3 = sourceObj;
            sourceObj.addListener(eventName, handler);
            unsubscribe = function () { return source_3.removeListener(eventName, handler); };
        }
        else if (sourceObj && sourceObj.length) {
            for (var i = 0, len = sourceObj.length; i < len; i++) {
                setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
            }
        }
        else {
            throw new TypeError('Invalid event target');
        }
        subscriber.add(unsubscribe);
    }
    function isNodeStyleEventEmitter(sourceObj) {
        return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
    }
    function isJQueryStyleEventEmitter(sourceObj) {
        return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
    }
    function isEventTarget(sourceObj) {
        return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
    }

    function isNumeric(val) {
        return !isArray$2(val) && (val - parseFloat(val) + 1) >= 0;
    }

    function interval(period, scheduler) {
        if (period === void 0) {
            period = 0;
        }
        if (scheduler === void 0) {
            scheduler = async;
        }
        if (!isNumeric(period) || period < 0) {
            period = 0;
        }
        if (!scheduler || typeof scheduler.schedule !== 'function') {
            scheduler = async;
        }
        return new Observable(function (subscriber) {
            subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period }));
            return subscriber;
        });
    }
    function dispatch(state) {
        var subscriber = state.subscriber, counter = state.counter, period = state.period;
        subscriber.next(counter);
        this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period);
    }

    function merge() {
        var observables = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            observables[_i] = arguments[_i];
        }
        var concurrent = Number.POSITIVE_INFINITY;
        var scheduler = null;
        var last = observables[observables.length - 1];
        if (isScheduler(last)) {
            scheduler = observables.pop();
            if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
                concurrent = observables.pop();
            }
        }
        else if (typeof last === 'number') {
            concurrent = observables.pop();
        }
        if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {
            return observables[0];
        }
        return mergeAll(concurrent)(fromArray(observables, scheduler));
    }

    function not(pred, thisArg) {
        function notPred() {
            return !(notPred.pred.apply(notPred.thisArg, arguments));
        }
        notPred.pred = pred;
        notPred.thisArg = thisArg;
        return notPred;
    }

    function filter(predicate, thisArg) {
        return function filterOperatorFunction(source) {
            return source.lift(new FilterOperator(predicate, thisArg));
        };
    }
    var FilterOperator =  (function () {
        function FilterOperator(predicate, thisArg) {
            this.predicate = predicate;
            this.thisArg = thisArg;
        }
        FilterOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
        };
        return FilterOperator;
    }());
    var FilterSubscriber =  (function (_super) {
        __extends$m(FilterSubscriber, _super);
        function FilterSubscriber(destination, predicate, thisArg) {
            var _this = _super.call(this, destination) || this;
            _this.predicate = predicate;
            _this.thisArg = thisArg;
            _this.count = 0;
            return _this;
        }
        FilterSubscriber.prototype._next = function (value) {
            var result;
            try {
                result = this.predicate.call(this.thisArg, value, this.count++);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            if (result) {
                this.destination.next(value);
            }
        };
        return FilterSubscriber;
    }(Subscriber));

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

    function catchError(selector) {
        return function catchErrorOperatorFunction(source) {
            var operator = new CatchOperator(selector);
            var caught = source.lift(operator);
            return (operator.caught = caught);
        };
    }
    var CatchOperator =  (function () {
        function CatchOperator(selector) {
            this.selector = selector;
        }
        CatchOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
        };
        return CatchOperator;
    }());
    var CatchSubscriber =  (function (_super) {
        __extends$m(CatchSubscriber, _super);
        function CatchSubscriber(destination, selector, caught) {
            var _this = _super.call(this, destination) || this;
            _this.selector = selector;
            _this.caught = caught;
            return _this;
        }
        CatchSubscriber.prototype.error = function (err) {
            if (!this.isStopped) {
                var result = void 0;
                try {
                    result = this.selector(err, this.caught);
                }
                catch (err2) {
                    _super.prototype.error.call(this, err2);
                    return;
                }
                this._unsubscribeAndRecycle();
                var innerSubscriber = new SimpleInnerSubscriber(this);
                this.add(innerSubscriber);
                var innerSubscription = innerSubscribe(result, innerSubscriber);
                if (innerSubscription !== innerSubscriber) {
                    this.add(innerSubscription);
                }
            }
        };
        return CatchSubscriber;
    }(SimpleOuterSubscriber));

    function concatMap(project, resultSelector) {
        return mergeMap(project, resultSelector, 1);
    }

    function debounceTime(dueTime, scheduler) {
        if (scheduler === void 0) {
            scheduler = async;
        }
        return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
    }
    var DebounceTimeOperator =  (function () {
        function DebounceTimeOperator(dueTime, scheduler) {
            this.dueTime = dueTime;
            this.scheduler = scheduler;
        }
        DebounceTimeOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
        };
        return DebounceTimeOperator;
    }());
    var DebounceTimeSubscriber =  (function (_super) {
        __extends$m(DebounceTimeSubscriber, _super);
        function DebounceTimeSubscriber(destination, dueTime, scheduler) {
            var _this = _super.call(this, destination) || this;
            _this.dueTime = dueTime;
            _this.scheduler = scheduler;
            _this.debouncedSubscription = null;
            _this.lastValue = null;
            _this.hasValue = false;
            return _this;
        }
        DebounceTimeSubscriber.prototype._next = function (value) {
            this.clearDebounce();
            this.lastValue = value;
            this.hasValue = true;
            this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$1, this.dueTime, this));
        };
        DebounceTimeSubscriber.prototype._complete = function () {
            this.debouncedNext();
            this.destination.complete();
        };
        DebounceTimeSubscriber.prototype.debouncedNext = function () {
            this.clearDebounce();
            if (this.hasValue) {
                var lastValue = this.lastValue;
                this.lastValue = null;
                this.hasValue = false;
                this.destination.next(lastValue);
            }
        };
        DebounceTimeSubscriber.prototype.clearDebounce = function () {
            var debouncedSubscription = this.debouncedSubscription;
            if (debouncedSubscription !== null) {
                this.remove(debouncedSubscription);
                debouncedSubscription.unsubscribe();
                this.debouncedSubscription = null;
            }
        };
        return DebounceTimeSubscriber;
    }(Subscriber));
    function dispatchNext$1(subscriber) {
        subscriber.debouncedNext();
    }

    function defaultIfEmpty(defaultValue) {
        if (defaultValue === void 0) {
            defaultValue = null;
        }
        return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
    }
    var DefaultIfEmptyOperator =  (function () {
        function DefaultIfEmptyOperator(defaultValue) {
            this.defaultValue = defaultValue;
        }
        DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
        };
        return DefaultIfEmptyOperator;
    }());
    var DefaultIfEmptySubscriber =  (function (_super) {
        __extends$m(DefaultIfEmptySubscriber, _super);
        function DefaultIfEmptySubscriber(destination, defaultValue) {
            var _this = _super.call(this, destination) || this;
            _this.defaultValue = defaultValue;
            _this.isEmpty = true;
            return _this;
        }
        DefaultIfEmptySubscriber.prototype._next = function (value) {
            this.isEmpty = false;
            this.destination.next(value);
        };
        DefaultIfEmptySubscriber.prototype._complete = function () {
            if (this.isEmpty) {
                this.destination.next(this.defaultValue);
            }
            this.destination.complete();
        };
        return DefaultIfEmptySubscriber;
    }(Subscriber));

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

    function delay(delay, scheduler) {
        if (scheduler === void 0) {
            scheduler = async;
        }
        var absoluteDelay = isDate(delay);
        var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
        return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
    }
    var DelayOperator =  (function () {
        function DelayOperator(delay, scheduler) {
            this.delay = delay;
            this.scheduler = scheduler;
        }
        DelayOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
        };
        return DelayOperator;
    }());
    var DelaySubscriber =  (function (_super) {
        __extends$m(DelaySubscriber, _super);
        function DelaySubscriber(destination, delay, scheduler) {
            var _this = _super.call(this, destination) || this;
            _this.delay = delay;
            _this.scheduler = scheduler;
            _this.queue = [];
            _this.active = false;
            _this.errored = false;
            return _this;
        }
        DelaySubscriber.dispatch = function (state) {
            var source = state.source;
            var queue = source.queue;
            var scheduler = state.scheduler;
            var destination = state.destination;
            while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
                queue.shift().notification.observe(destination);
            }
            if (queue.length > 0) {
                var delay_1 = Math.max(0, queue[0].time - scheduler.now());
                this.schedule(state, delay_1);
            }
            else {
                this.unsubscribe();
                source.active = false;
            }
        };
        DelaySubscriber.prototype._schedule = function (scheduler) {
            this.active = true;
            var destination = this.destination;
            destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
                source: this, destination: this.destination, scheduler: scheduler
            }));
        };
        DelaySubscriber.prototype.scheduleNotification = function (notification) {
            if (this.errored === true) {
                return;
            }
            var scheduler = this.scheduler;
            var message = new DelayMessage(scheduler.now() + this.delay, notification);
            this.queue.push(message);
            if (this.active === false) {
                this._schedule(scheduler);
            }
        };
        DelaySubscriber.prototype._next = function (value) {
            this.scheduleNotification(Notification.createNext(value));
        };
        DelaySubscriber.prototype._error = function (err) {
            this.errored = true;
            this.queue = [];
            this.destination.error(err);
            this.unsubscribe();
        };
        DelaySubscriber.prototype._complete = function () {
            this.scheduleNotification(Notification.createComplete());
            this.unsubscribe();
        };
        return DelaySubscriber;
    }(Subscriber));
    var DelayMessage =  (function () {
        function DelayMessage(time, notification) {
            this.time = time;
            this.notification = notification;
        }
        return DelayMessage;
    }());

    function distinctUntilChanged(compare, keySelector) {
        return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
    }
    var DistinctUntilChangedOperator =  (function () {
        function DistinctUntilChangedOperator(compare, keySelector) {
            this.compare = compare;
            this.keySelector = keySelector;
        }
        DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
        };
        return DistinctUntilChangedOperator;
    }());
    var DistinctUntilChangedSubscriber =  (function (_super) {
        __extends$m(DistinctUntilChangedSubscriber, _super);
        function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
            var _this = _super.call(this, destination) || this;
            _this.keySelector = keySelector;
            _this.hasKey = false;
            if (typeof compare === 'function') {
                _this.compare = compare;
            }
            return _this;
        }
        DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
            return x === y;
        };
        DistinctUntilChangedSubscriber.prototype._next = function (value) {
            var key;
            try {
                var keySelector = this.keySelector;
                key = keySelector ? keySelector(value) : value;
            }
            catch (err) {
                return this.destination.error(err);
            }
            var result = false;
            if (this.hasKey) {
                try {
                    var compare = this.compare;
                    result = compare(this.key, key);
                }
                catch (err) {
                    return this.destination.error(err);
                }
            }
            else {
                this.hasKey = true;
            }
            if (!result) {
                this.key = key;
                this.destination.next(value);
            }
        };
        return DistinctUntilChangedSubscriber;
    }(Subscriber));

    function throwIfEmpty(errorFactory) {
        if (errorFactory === void 0) {
            errorFactory = defaultErrorFactory;
        }
        return function (source) {
            return source.lift(new ThrowIfEmptyOperator(errorFactory));
        };
    }
    var ThrowIfEmptyOperator =  (function () {
        function ThrowIfEmptyOperator(errorFactory) {
            this.errorFactory = errorFactory;
        }
        ThrowIfEmptyOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));
        };
        return ThrowIfEmptyOperator;
    }());
    var ThrowIfEmptySubscriber =  (function (_super) {
        __extends$m(ThrowIfEmptySubscriber, _super);
        function ThrowIfEmptySubscriber(destination, errorFactory) {
            var _this = _super.call(this, destination) || this;
            _this.errorFactory = errorFactory;
            _this.hasValue = false;
            return _this;
        }
        ThrowIfEmptySubscriber.prototype._next = function (value) {
            this.hasValue = true;
            this.destination.next(value);
        };
        ThrowIfEmptySubscriber.prototype._complete = function () {
            if (!this.hasValue) {
                var err = void 0;
                try {
                    err = this.errorFactory();
                }
                catch (e) {
                    err = e;
                }
                this.destination.error(err);
            }
            else {
                return this.destination.complete();
            }
        };
        return ThrowIfEmptySubscriber;
    }(Subscriber));
    function defaultErrorFactory() {
        return new EmptyError();
    }

    function take(count) {
        return function (source) {
            if (count === 0) {
                return empty();
            }
            else {
                return source.lift(new TakeOperator(count));
            }
        };
    }
    var TakeOperator =  (function () {
        function TakeOperator(total) {
            this.total = total;
            if (this.total < 0) {
                throw new ArgumentOutOfRangeError;
            }
        }
        TakeOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new TakeSubscriber(subscriber, this.total));
        };
        return TakeOperator;
    }());
    var TakeSubscriber =  (function (_super) {
        __extends$m(TakeSubscriber, _super);
        function TakeSubscriber(destination, total) {
            var _this = _super.call(this, destination) || this;
            _this.total = total;
            _this.count = 0;
            return _this;
        }
        TakeSubscriber.prototype._next = function (value) {
            var total = this.total;
            var count = ++this.count;
            if (count <= total) {
                this.destination.next(value);
                if (count === total) {
                    this.destination.complete();
                    this.unsubscribe();
                }
            }
        };
        return TakeSubscriber;
    }(Subscriber));

    function finalize(callback) {
        return function (source) { return source.lift(new FinallyOperator(callback)); };
    }
    var FinallyOperator =  (function () {
        function FinallyOperator(callback) {
            this.callback = callback;
        }
        FinallyOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new FinallySubscriber(subscriber, this.callback));
        };
        return FinallyOperator;
    }());
    var FinallySubscriber =  (function (_super) {
        __extends$m(FinallySubscriber, _super);
        function FinallySubscriber(destination, callback) {
            var _this = _super.call(this, destination) || this;
            _this.add(new Subscription(callback));
            return _this;
        }
        return FinallySubscriber;
    }(Subscriber));

    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 function takeLastOperatorFunction(source) {
            if (count === 0) {
                return empty();
            }
            else {
                return source.lift(new TakeLastOperator(count));
            }
        };
    }
    var TakeLastOperator =  (function () {
        function TakeLastOperator(total) {
            this.total = total;
            if (this.total < 0) {
                throw new ArgumentOutOfRangeError;
            }
        }
        TakeLastOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
        };
        return TakeLastOperator;
    }());
    var TakeLastSubscriber =  (function (_super) {
        __extends$m(TakeLastSubscriber, _super);
        function TakeLastSubscriber(destination, total) {
            var _this = _super.call(this, destination) || this;
            _this.total = total;
            _this.ring = new Array();
            _this.count = 0;
            return _this;
        }
        TakeLastSubscriber.prototype._next = function (value) {
            var ring = this.ring;
            var total = this.total;
            var count = this.count++;
            if (ring.length < total) {
                ring.push(value);
            }
            else {
                var index = count % total;
                ring[index] = value;
            }
        };
        TakeLastSubscriber.prototype._complete = function () {
            var destination = this.destination;
            var count = this.count;
            if (count > 0) {
                var total = this.count >= this.total ? this.total : this.count;
                var ring = this.ring;
                for (var i = 0; i < total; i++) {
                    var idx = (count++) % total;
                    destination.next(ring[idx]);
                }
            }
            destination.complete();
        };
        return TakeLastSubscriber;
    }(Subscriber));

    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 multicast(subjectOrSubjectFactory, selector) {
        return function multicastOperatorFunction(source) {
            var subjectFactory;
            if (typeof subjectOrSubjectFactory === 'function') {
                subjectFactory = subjectOrSubjectFactory;
            }
            else {
                subjectFactory = function subjectFactory() {
                    return subjectOrSubjectFactory;
                };
            }
            if (typeof selector === 'function') {
                return source.lift(new MulticastOperator(subjectFactory, selector));
            }
            var connectable = Object.create(source, connectableObservableDescriptor);
            connectable.source = source;
            connectable.subjectFactory = subjectFactory;
            return connectable;
        };
    }
    var MulticastOperator =  (function () {
        function MulticastOperator(subjectFactory, selector) {
            this.subjectFactory = subjectFactory;
            this.selector = selector;
        }
        MulticastOperator.prototype.call = function (subscriber, source) {
            var selector = this.selector;
            var subject = this.subjectFactory();
            var subscription = selector(subject).subscribe(subscriber);
            subscription.add(source.subscribe(subject));
            return subscription;
        };
        return MulticastOperator;
    }());

    function pairwise() {
        return function (source) { return source.lift(new PairwiseOperator()); };
    }
    var PairwiseOperator =  (function () {
        function PairwiseOperator() {
        }
        PairwiseOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new PairwiseSubscriber(subscriber));
        };
        return PairwiseOperator;
    }());
    var PairwiseSubscriber =  (function (_super) {
        __extends$m(PairwiseSubscriber, _super);
        function PairwiseSubscriber(destination) {
            var _this = _super.call(this, destination) || this;
            _this.hasPrev = false;
            return _this;
        }
        PairwiseSubscriber.prototype._next = function (value) {
            var pair;
            if (this.hasPrev) {
                pair = [this.prev, value];
            }
            else {
                this.hasPrev = true;
            }
            this.prev = value;
            if (pair) {
                this.destination.next(pair);
            }
        };
        return PairwiseSubscriber;
    }(Subscriber));

    function shareSubjectFactory() {
        return new Subject();
    }
    function share() {
        return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); };
    }

    function shareReplay(configOrBufferSize, windowTime, scheduler) {
        var config;
        if (configOrBufferSize && typeof configOrBufferSize === 'object') {
            config = configOrBufferSize;
        }
        else {
            config = {
                bufferSize: configOrBufferSize,
                windowTime: windowTime,
                refCount: false,
                scheduler: scheduler,
            };
        }
        return function (source) { return source.lift(shareReplayOperator(config)); };
    }
    function shareReplayOperator(_a) {
        var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler;
        var subject;
        var refCount = 0;
        var subscription;
        var hasError = false;
        var isComplete = false;
        return function shareReplayOperation(source) {
            refCount++;
            var innerSub;
            if (!subject || hasError) {
                hasError = false;
                subject = new ReplaySubject(bufferSize, windowTime, scheduler);
                innerSub = subject.subscribe(this);
                subscription = source.subscribe({
                    next: function (value) {
                        subject.next(value);
                    },
                    error: function (err) {
                        hasError = true;
                        subject.error(err);
                    },
                    complete: function () {
                        isComplete = true;
                        subscription = undefined;
                        subject.complete();
                    },
                });
                if (isComplete) {
                    subscription = undefined;
                }
            }
            else {
                innerSub = subject.subscribe(this);
            }
            this.add(function () {
                refCount--;
                innerSub.unsubscribe();
                innerSub = undefined;
                if (subscription && !isComplete && useRefCount && refCount === 0) {
                    subscription.unsubscribe();
                    subscription = undefined;
                    subject = undefined;
                }
            });
        };
    }

    function skip(count) {
        return function (source) { return source.lift(new SkipOperator(count)); };
    }
    var SkipOperator =  (function () {
        function SkipOperator(total) {
            this.total = total;
        }
        SkipOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new SkipSubscriber(subscriber, this.total));
        };
        return SkipOperator;
    }());
    var SkipSubscriber =  (function (_super) {
        __extends$m(SkipSubscriber, _super);
        function SkipSubscriber(destination, total) {
            var _this = _super.call(this, destination) || this;
            _this.total = total;
            _this.count = 0;
            return _this;
        }
        SkipSubscriber.prototype._next = function (x) {
            if (++this.count > this.total) {
                this.destination.next(x);
            }
        };
        return SkipSubscriber;
    }(Subscriber));

    function switchMap(project, resultSelector) {
        if (typeof resultSelector === 'function') {
            return function (source) { return source.pipe(switchMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
        }
        return function (source) { return source.lift(new SwitchMapOperator(project)); };
    }
    var SwitchMapOperator =  (function () {
        function SwitchMapOperator(project) {
            this.project = project;
        }
        SwitchMapOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
        };
        return SwitchMapOperator;
    }());
    var SwitchMapSubscriber =  (function (_super) {
        __extends$m(SwitchMapSubscriber, _super);
        function SwitchMapSubscriber(destination, project) {
            var _this = _super.call(this, destination) || this;
            _this.project = project;
            _this.index = 0;
            return _this;
        }
        SwitchMapSubscriber.prototype._next = function (value) {
            var result;
            var index = this.index++;
            try {
                result = this.project(value, index);
            }
            catch (error) {
                this.destination.error(error);
                return;
            }
            this._innerSub(result);
        };
        SwitchMapSubscriber.prototype._innerSub = function (result) {
            var innerSubscription = this.innerSubscription;
            if (innerSubscription) {
                innerSubscription.unsubscribe();
            }
            var innerSubscriber = new SimpleInnerSubscriber(this);
            var destination = this.destination;
            destination.add(innerSubscriber);
            this.innerSubscription = innerSubscribe(result, innerSubscriber);
            if (this.innerSubscription !== innerSubscriber) {
                destination.add(this.innerSubscription);
            }
        };
        SwitchMapSubscriber.prototype._complete = function () {
            var innerSubscription = this.innerSubscription;
            if (!innerSubscription || innerSubscription.closed) {
                _super.prototype._complete.call(this);
            }
            this.unsubscribe();
        };
        SwitchMapSubscriber.prototype._unsubscribe = function () {
            this.innerSubscription = undefined;
        };
        SwitchMapSubscriber.prototype.notifyComplete = function () {
            this.innerSubscription = undefined;
            if (this.isStopped) {
                _super.prototype._complete.call(this);
            }
        };
        SwitchMapSubscriber.prototype.notifyNext = function (innerValue) {
            this.destination.next(innerValue);
        };
        return SwitchMapSubscriber;
    }(SimpleOuterSubscriber));

    function tap(nextOrObserver, error, complete) {
        return function tapOperatorFunction(source) {
            return source.lift(new DoOperator(nextOrObserver, error, complete));
        };
    }
    var DoOperator =  (function () {
        function DoOperator(nextOrObserver, error, complete) {
            this.nextOrObserver = nextOrObserver;
            this.error = error;
            this.complete = complete;
        }
        DoOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
        };
        return DoOperator;
    }());
    var TapSubscriber =  (function (_super) {
        __extends$m(TapSubscriber, _super);
        function TapSubscriber(destination, observerOrNext, error, complete) {
            var _this = _super.call(this, destination) || this;
            _this._tapNext = noop$1;
            _this._tapError = noop$1;
            _this._tapComplete = noop$1;
            _this._tapError = error || noop$1;
            _this._tapComplete = complete || noop$1;
            if (isFunction$1(observerOrNext)) {
                _this._context = _this;
                _this._tapNext = observerOrNext;
            }
            else if (observerOrNext) {
                _this._context = observerOrNext;
                _this._tapNext = observerOrNext.next || noop$1;
                _this._tapError = observerOrNext.error || noop$1;
                _this._tapComplete = observerOrNext.complete || noop$1;
            }
            return _this;
        }
        TapSubscriber.prototype._next = function (value) {
            try {
                this._tapNext.call(this._context, value);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            this.destination.next(value);
        };
        TapSubscriber.prototype._error = function (err) {
            try {
                this._tapError.call(this._context, err);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            this.destination.error(err);
        };
        TapSubscriber.prototype._complete = function () {
            try {
                this._tapComplete.call(this._context);
            }
            catch (err) {
                this.destination.error(err);
                return;
            }
            return this.destination.complete();
        };
        return TapSubscriber;
    }(Subscriber));

    var defaultThrottleConfig = {
        leading: true,
        trailing: false
    };
    function throttle(durationSelector, config) {
        if (config === void 0) {
            config = defaultThrottleConfig;
        }
        return function (source) { return source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing)); };
    }
    var ThrottleOperator =  (function () {
        function ThrottleOperator(durationSelector, leading, trailing) {
            this.durationSelector = durationSelector;
            this.leading = leading;
            this.trailing = trailing;
        }
        ThrottleOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
        };
        return ThrottleOperator;
    }());
    var ThrottleSubscriber =  (function (_super) {
        __extends$m(ThrottleSubscriber, _super);
        function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
            var _this = _super.call(this, destination) || this;
            _this.destination = destination;
            _this.durationSelector = durationSelector;
            _this._leading = _leading;
            _this._trailing = _trailing;
            _this._hasValue = false;
            return _this;
        }
        ThrottleSubscriber.prototype._next = function (value) {
            this._hasValue = true;
            this._sendValue = value;
            if (!this._throttled) {
                if (this._leading) {
                    this.send();
                }
                else {
                    this.throttle(value);
                }
            }
        };
        ThrottleSubscriber.prototype.send = function () {
            var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
            if (_hasValue) {
                this.destination.next(_sendValue);
                this.throttle(_sendValue);
            }
            this._hasValue = false;
            this._sendValue = undefined;
        };
        ThrottleSubscriber.prototype.throttle = function (value) {
            var duration = this.tryDurationSelector(value);
            if (!!duration) {
                this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
            }
        };
        ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
            try {
                return this.durationSelector(value);
            }
            catch (err) {
                this.destination.error(err);
                return null;
            }
        };
        ThrottleSubscriber.prototype.throttlingDone = function () {
            var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
            if (_throttled) {
                _throttled.unsubscribe();
            }
            this._throttled = undefined;
            if (_trailing) {
                this.send();
            }
        };
        ThrottleSubscriber.prototype.notifyNext = function () {
            this.throttlingDone();
        };
        ThrottleSubscriber.prototype.notifyComplete = function () {
            this.throttlingDone();
        };
        return ThrottleSubscriber;
    }(SimpleOuterSubscriber));

    function throttleTime(duration, scheduler, config) {
        if (scheduler === void 0) {
            scheduler = async;
        }
        if (config === void 0) {
            config = defaultThrottleConfig;
        }
        return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
    }
    var ThrottleTimeOperator =  (function () {
        function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
            this.duration = duration;
            this.scheduler = scheduler;
            this.leading = leading;
            this.trailing = trailing;
        }
        ThrottleTimeOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
        };
        return ThrottleTimeOperator;
    }());
    var ThrottleTimeSubscriber =  (function (_super) {
        __extends$m(ThrottleTimeSubscriber, _super);
        function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
            var _this = _super.call(this, destination) || this;
            _this.duration = duration;
            _this.scheduler = scheduler;
            _this.leading = leading;
            _this.trailing = trailing;
            _this._hasTrailingValue = false;
            _this._trailingValue = null;
            return _this;
        }
        ThrottleTimeSubscriber.prototype._next = function (value) {
            if (this.throttled) {
                if (this.trailing) {
                    this._trailingValue = value;
                    this._hasTrailingValue = true;
                }
            }
            else {
                this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
                if (this.leading) {
                    this.destination.next(value);
                }
                else if (this.trailing) {
                    this._trailingValue = value;
                    this._hasTrailingValue = true;
                }
            }
        };
        ThrottleTimeSubscriber.prototype._complete = function () {
            if (this._hasTrailingValue) {
                this.destination.next(this._trailingValue);
                this.destination.complete();
            }
            else {
                this.destination.complete();
            }
        };
        ThrottleTimeSubscriber.prototype.clearThrottle = function () {
            var throttled = this.throttled;
            if (throttled) {
                if (this.trailing && this._hasTrailingValue) {
                    this.destination.next(this._trailingValue);
                    this._trailingValue = null;
                    this._hasTrailingValue = false;
                }
                throttled.unsubscribe();
                this.remove(throttled);
                this.throttled = null;
            }
        };
        return ThrottleTimeSubscriber;
    }(Subscriber));
    function dispatchNext(arg) {
        var subscriber = arg.subscriber;
        subscriber.clearThrottle();
    }

    function timeoutWith(due, withObservable, scheduler) {
        if (scheduler === void 0) {
            scheduler = async;
        }
        return function (source) {
            var absoluteTimeout = isDate(due);
            var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
            return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
        };
    }
    var TimeoutWithOperator =  (function () {
        function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
            this.waitFor = waitFor;
            this.absoluteTimeout = absoluteTimeout;
            this.withObservable = withObservable;
            this.scheduler = scheduler;
        }
        TimeoutWithOperator.prototype.call = function (subscriber, source) {
            return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
        };
        return TimeoutWithOperator;
    }());
    var TimeoutWithSubscriber =  (function (_super) {
        __extends$m(TimeoutWithSubscriber, _super);
        function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
            var _this = _super.call(this, destination) || this;
            _this.absoluteTimeout = absoluteTimeout;
            _this.waitFor = waitFor;
            _this.withObservable = withObservable;
            _this.scheduler = scheduler;
            _this.scheduleTimeout();
            return _this;
        }
        TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
            var withObservable = subscriber.withObservable;
            subscriber._unsubscribeAndRecycle();
            subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));
        };
        TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
            var action = this.action;
            if (action) {
                this.action = action.schedule(this, this.waitFor);
            }
            else {
                this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
            }
        };
        TimeoutWithSubscriber.prototype._next = function (value) {
            if (!this.absoluteTimeout) {
                this.scheduleTimeout();
            }
            _super.prototype._next.call(this, value);
        };
        TimeoutWithSubscriber.prototype._unsubscribe = function () {
            this.action = undefined;
            this.scheduler = null;
            this.withObservable = null;
        };
        return TimeoutWithSubscriber;
    }(SimpleOuterSubscriber));

    function timeout(due, scheduler) {
        if (scheduler === void 0) {
            scheduler = async;
        }
        return timeoutWith(due, throwError(new TimeoutError()), scheduler);
    }

    var __awaiter$m = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$m = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    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 = {}));
    var 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"],
    ]);
    var multiChannelIdMapper = (function initMultiChannelIdMapper() {
        var map = new Map();
        multiChannelMapper.forEach(function (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;
    }
    var asyncTimeout = function (timeout) { return __awaiter$m(void 0, void 0, void 0, function () { return __generator$m(this, function (_a) {
        return [2 , new Promise(function (resolve) { return setTimeout(resolve, timeout); })];
    }); }); };
    function MapOrSet_toJSON(key, value) {
        if (value && typeof value === "object") {
            if (value instanceof Set) {
                var result_1 = [];
                value.forEach(function (m) { return result_1.push(m); });
                return result_1;
            }
            else if (value instanceof Map) {
                var result_2 = {};
                value.forEach(function (value, key) {
                    result_2[key] = value;
                });
                return result_2;
            }
        }
        return value;
    }

    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 = {}));
    var HierarchyMessage =  (function () {
        function HierarchyMessage(master, slave) {
            this.connectionFutureMaster = null;
            this.connectionMaster = master;
            this.connectionSlave = slave;
        }
        return HierarchyMessage;
    }());
    var RegisterRequestObj =  (function () {
        function RegisterRequestObj(idSlaves, request, requestIdentifierNotification) {
            this.id_slaves = idSlaves;
            this.request = request;
            this.requestIdentifierNotification = requestIdentifierNotification;
            this.lastResponse = new Array();
        }
        return RegisterRequestObj;
    }());
    var ToWsMessage =  (function () {
        function ToWsMessage(from_id, data) {
            this.from_id = from_id;
            this.data = data;
        }
        ToWsMessage.fromStringMessage = function (data) {
            var msg = JSON.parse(data);
            return new ToWsMessage(msg.from_id, new StorageMessage(msg.data.connection_id, msg.data.message));
        };
        return ToWsMessage;
    }());
    var FromWsMessage =  (function () {
        function FromWsMessage(to_id, data) {
            this.to_ids = to_id;
            this.data = data;
        }
        FromWsMessage.fromStringMessage = function (data) {
            var msg = JSON.parse(data);
            return new FromWsMessage(msg.to_ids, new StorageMessage(msg.data.connection_id, msg.data.message));
        };
        return FromWsMessage;
    }());
    var StorageMessage =  (function () {
        function StorageMessage(connection_id, message) {
            this.connection_id = connection_id;
            this.message = message;
        }
        StorageMessage.fromStringMessage = function (data) {
            var msg = JSON.parse(data);
            return new StorageMessage(msg.connection_id, msg.message);
        };
        return StorageMessage;
    }());

    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 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["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 || (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_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 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 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 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 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 || (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 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 || (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 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 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 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["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 || (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["CUSTOMER_JOURNEY"] = "CUSTOMER_JOURNEY";
        LicenseModule["INSIGHT"] = "INSIGHT";
    })(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 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 || (Operator = {}));
    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 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 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 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 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["ADDRESSBOOK_PERSONAL"] = "ADDRESSBOOK_PERSONAL";
        UserOfGenericType["AUTH_APPLICATION"] = "AUTH_APPLICATION";
    })(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";
    }

    var __extends$l = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 WebAPI =  (function () {
        function WebAPI(data) {
            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;
        }
        return WebAPI;
    }());
    var GenericObject =  (function (_super) {
        __extends$l(GenericObject, _super);
        function GenericObject(data) {
            var _this = _super.call(this, data) || this;
            _this.value = data.value;
            _this.field = data.field;
            _this.className = data.className || "GenericObjectException";
            return _this;
        }
        return GenericObject;
    }(WebAPI));
    var NoRouteToHost =  (function (_super) {
        __extends$l(NoRouteToHost, _super);
        function NoRouteToHost(data) {
            var _this = _super.call(this, data) || this;
            _this.exceptionName = data.exceptionName || "NoRouteToHostException";
            return _this;
        }
        return NoRouteToHost;
    }(WebAPI));
    var ReconnectingInProgress =  (function (_super) {
        __extends$l(ReconnectingInProgress, _super);
        function ReconnectingInProgress(data) {
            var _this = _super.call(this, data) || this;
            _this.exceptionName = data.exceptionName || "ReconnectingInProgressException";
            return _this;
        }
        return ReconnectingInProgress;
    }(WebAPI));
    var SocketClosed =  (function (_super) {
        __extends$l(SocketClosed, _super);
        function SocketClosed(data) {
            var _this = _super.call(this, data) || this;
            _this.exceptionName = data.exceptionName || "SocketClosedException";
            return _this;
        }
        return SocketClosed;
    }(WebAPI));
    var StopOpenSocket =  (function (_super) {
        __extends$l(StopOpenSocket, _super);
        function StopOpenSocket(data) {
            var _this = _super.call(this, data) || this;
            _this.exceptionName = data.exceptionName || "StopOpenSocketException";
            return _this;
        }
        return StopOpenSocket;
    }(WebAPI));
    var AuthorizationRequired =  (function (_super) {
        __extends$l(AuthorizationRequired, _super);
        function AuthorizationRequired(data) {
            var _this = _super.call(this, data) || this;
            _this.sessionId = data.sessionId;
            _this.exceptionName = data.exceptionName || "AuthorizationRequiredException";
            return _this;
        }
        AuthorizationRequired.CODE = 401;
        return AuthorizationRequired;
    }(WebAPI));
    var InternalServerError =  (function (_super) {
        __extends$l(InternalServerError, _super);
        function InternalServerError(data) {
            var _this = _super.call(this, data) || this;
            _this.exceptionName = data.exceptionName || "InternalServerErrorException";
            return _this;
        }
        InternalServerError.CODE = 500;
        return InternalServerError;
    }(WebAPI));
    var PasswordExpired =  (function (_super) {
        __extends$l(PasswordExpired, _super);
        function PasswordExpired() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PasswordExpired.newInstance = function (username, checkPasswordSecurityEnabled) {
            var result = new PasswordExpired({
                clazz: null,
                code: PasswordExpired.CODE,
                exceptionName: "PasswordExpiredException",
                message: "Password expired",
            });
            result.username = username;
            result.checkPasswordSecurityEnabled = checkPasswordSecurityEnabled;
            return result;
        };
        PasswordExpired.CODE = 403;
        return PasswordExpired;
    }(WebAPI));
    var UserNotEnabledOnMcs =  (function (_super) {
        __extends$l(UserNotEnabledOnMcs, _super);
        function UserNotEnabledOnMcs() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UserNotEnabledOnMcs.newInstance = function (username) {
            var result = new UserNotEnabledOnMcs({
                clazz: null,
                code: UserNotEnabledOnMcs.CODE,
                exceptionName: "UserNotEnabledOnMcsException",
                message: "Login via MCS not enabled for user",
            });
            result.username = username;
            return result;
        };
        UserNotEnabledOnMcs.CODE = 497;
        return UserNotEnabledOnMcs;
    }(WebAPI));
    var UserNotEnabled =  (function (_super) {
        __extends$l(UserNotEnabled, _super);
        function UserNotEnabled() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UserNotEnabled.newInstance = function (username) {
            var result = new UserNotEnabled({
                clazz: null,
                code: UserNotEnabled.CODE,
                exceptionName: "UserNotEnabled",
                message: "Login not enabled for user",
            });
            result.username = username;
            return result;
        };
        UserNotEnabled.CODE = 498;
        return UserNotEnabled;
    }(WebAPI));
    var CallInProgress =  (function (_super) {
        __extends$l(CallInProgress, _super);
        function CallInProgress() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CallInProgress.newInstance = function (callId) {
            var result = new CallInProgress({
                clazz: null,
                code: 803,
                exceptionName: "CallInProgressException",
                message: "Call is in progress",
            });
            result.callId = callId;
            return result;
        };
        return CallInProgress;
    }(WebAPI));
    var TimeoutResponse =  (function (_super) {
        __extends$l(TimeoutResponse, _super);
        function TimeoutResponse() {
            return _super.call(this, {
                code: 1003,
                clazz: null,
                exceptionName: "TimeoutResponseException",
                message: "Timeout has occurred",
            }) || this;
        }
        TimeoutResponse.newInstance = function (message) {
            var result = new TimeoutResponse();
            if (message) {
                result.message = message;
            }
            return result;
        };
        return TimeoutResponse;
    }(WebAPI));
    var CacheLimitSizeExceeded =  (function (_super) {
        __extends$l(CacheLimitSizeExceeded, _super);
        function CacheLimitSizeExceeded(data) {
            var _this = _super.call(this, data) || this;
            _this.exceededByte = data.exceededByte;
            return _this;
        }
        return CacheLimitSizeExceeded;
    }(WebAPI));
    var GenericObjectExists =  (function (_super) {
        __extends$l(GenericObjectExists, _super);
        function GenericObjectExists(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectExists;
    }(GenericObject));
    var GenericObjectFormat =  (function (_super) {
        __extends$l(GenericObjectFormat, _super);
        function GenericObjectFormat(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectFormat;
    }(GenericObject));
    var GenericObjectIsInUse =  (function (_super) {
        __extends$l(GenericObjectIsInUse, _super);
        function GenericObjectIsInUse(data) {
            var _this = _super.call(this, data) || this;
            _this.users = data.users;
            return _this;
        }
        return GenericObjectIsInUse;
    }(GenericObject));
    var GenericObjectMinSize =  (function (_super) {
        __extends$l(GenericObjectMinSize, _super);
        function GenericObjectMinSize(data) {
            var _this = _super.call(this, data) || this;
            _this.minSize = data.minSize;
            return _this;
        }
        return GenericObjectMinSize;
    }(GenericObject));
    var GenericObjectMaxSize =  (function (_super) {
        __extends$l(GenericObjectMaxSize, _super);
        function GenericObjectMaxSize(data) {
            var _this = _super.call(this, data) || this;
            _this.maxSize = data.maxSize;
            return _this;
        }
        return GenericObjectMaxSize;
    }(GenericObject));
    var GenericObjectRangeValue =  (function (_super) {
        __extends$l(GenericObjectRangeValue, _super);
        function GenericObjectRangeValue(data) {
            var _this = _super.call(this, data) || this;
            _this.minValue = data.minValue;
            _this.maxValue = data.maxValue;
            return _this;
        }
        return GenericObjectRangeValue;
    }(GenericObject));
    var GenericObjectMaxValue =  (function (_super) {
        __extends$l(GenericObjectMaxValue, _super);
        function GenericObjectMaxValue(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectMaxValue;
    }(GenericObjectRangeValue));
    var GenericObjectMinValue =  (function (_super) {
        __extends$l(GenericObjectMinValue, _super);
        function GenericObjectMinValue(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectMinValue;
    }(GenericObjectRangeValue));
    var GenericObjectRequiredDigitValue =  (function (_super) {
        __extends$l(GenericObjectRequiredDigitValue, _super);
        function GenericObjectRequiredDigitValue(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectRequiredDigitValue;
    }(GenericObject));
    var GenericObjectRequiredNumberValue =  (function (_super) {
        __extends$l(GenericObjectRequiredNumberValue, _super);
        function GenericObjectRequiredNumberValue(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectRequiredNumberValue;
    }(GenericObject));
    var GenericObjectSameSize =  (function (_super) {
        __extends$l(GenericObjectSameSize, _super);
        function GenericObjectSameSize(data) {
            var _this = _super.call(this, data) || this;
            _this.maxSize = data.maxSize;
            return _this;
        }
        return GenericObjectSameSize;
    }(GenericObject));
    var GenericObjectUnchangeable =  (function (_super) {
        __extends$l(GenericObjectUnchangeable, _super);
        function GenericObjectUnchangeable(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectUnchangeable;
    }(GenericObject));
    var LogoutNotEnable =  (function (_super) {
        __extends$l(LogoutNotEnable, _super);
        function LogoutNotEnable(data) {
            return _super.call(this, data) || this;
        }
        return LogoutNotEnable;
    }(GenericObject));
    var UseOfAgExternalNotEnableCauseNoMobilePhone =  (function (_super) {
        __extends$l(UseOfAgExternalNotEnableCauseNoMobilePhone, _super);
        function UseOfAgExternalNotEnableCauseNoMobilePhone(data) {
            return _super.call(this, data) || this;
        }
        return UseOfAgExternalNotEnableCauseNoMobilePhone;
    }(GenericObject));
    var GenericObjectWasNotFound =  (function (_super) {
        __extends$l(GenericObjectWasNotFound, _super);
        function GenericObjectWasNotFound(data) {
            return _super.call(this, data) || this;
        }
        return GenericObjectWasNotFound;
    }(GenericObject));
    var InvalidArgument =  (function (_super) {
        __extends$l(InvalidArgument, _super);
        function InvalidArgument(data) {
            return _super.call(this, data) || this;
        }
        return InvalidArgument;
    }(GenericObject));
    var InvalidAction =  (function (_super) {
        __extends$l(InvalidAction, _super);
        function InvalidAction(data) {
            return _super.call(this, data) || this;
        }
        return InvalidAction;
    }(GenericObject));
    var InvalidLicence =  (function (_super) {
        __extends$l(InvalidLicence, _super);
        function InvalidLicence(data) {
            return _super.call(this, data) || this;
        }
        return InvalidLicence;
    }(WebAPI));
    var LicenceExceeded =  (function (_super) {
        __extends$l(LicenceExceeded, _super);
        function LicenceExceeded(data) {
            return _super.call(this, data) || this;
        }
        return LicenceExceeded;
    }(WebAPI));
    var MaxRetryExceeded =  (function (_super) {
        __extends$l(MaxRetryExceeded, _super);
        function MaxRetryExceeded(data) {
            return _super.call(this, data) || this;
        }
        return MaxRetryExceeded;
    }(WebAPI));
    var NoFileOnCache =  (function (_super) {
        __extends$l(NoFileOnCache, _super);
        function NoFileOnCache(data) {
            var _this = _super.call(this, data) || this;
            _this.fileName = data.fileName;
            return _this;
        }
        return NoFileOnCache;
    }(WebAPI));
    var OperationIsNotAllowedToUser =  (function (_super) {
        __extends$l(OperationIsNotAllowedToUser, _super);
        function OperationIsNotAllowedToUser(data) {
            var _this = _super.call(this, data) || this;
            _this.sessionId = data.sessionId;
            _this.mandatoryPermission = data.mandatoryPermission;
            return _this;
        }
        return OperationIsNotAllowedToUser;
    }(GenericObject));
    var WriteOperationIsNotAllowedToUser =  (function (_super) {
        __extends$l(WriteOperationIsNotAllowedToUser, _super);
        function WriteOperationIsNotAllowedToUser(data) {
            return _super.call(this, data) || this;
        }
        return WriteOperationIsNotAllowedToUser;
    }(OperationIsNotAllowedToUser));
    var WrongSessionId =  (function (_super) {
        __extends$l(WrongSessionId, _super);
        function WrongSessionId(data) {
            var _this = _super.call(this, data) || this;
            _this.sessionId = data.sessionId;
            _this.newSessionId = data.newSessionId;
            return _this;
        }
        return WrongSessionId;
    }(WebAPI));
    var WrongVersion =  (function (_super) {
        __extends$l(WrongVersion, _super);
        function WrongVersion(data) {
            var _this = _super.call(this, data) || this;
            _this.sessionId = data.sessionId;
            _this.versionRequired = data.versionRequired;
            return _this;
        }
        return WrongVersion;
    }(WebAPI));
    var ConvertFile =  (function (_super) {
        __extends$l(ConvertFile, _super);
        function ConvertFile(data) {
            var _this = _super.call(this, data) || this;
            _this.reason = data.reason;
            return _this;
        }
        return ConvertFile;
    }(WebAPI));
    var GenericObjectRequired =  (function (_super) {
        __extends$l(GenericObjectRequired, _super);
        function GenericObjectRequired(data) {
            var _this = _super.call(this, data) || this;
            _this.mandatoryFields = data.mandatoryFields;
            return _this;
        }
        return GenericObjectRequired;
    }(GenericObject));
    var DeviceRequestFailed =  (function (_super) {
        __extends$l(DeviceRequestFailed, _super);
        function DeviceRequestFailed(data) {
            return _super.call(this, data) || this;
        }
        return DeviceRequestFailed;
    }(WebAPI));
    var DeviceClosed =  (function (_super) {
        __extends$l(DeviceClosed, _super);
        function DeviceClosed(data) {
            return _super.call(this, data) || this;
        }
        return DeviceClosed;
    }(WebAPI));
    var DeviceTimeout =  (function (_super) {
        __extends$l(DeviceTimeout, _super);
        function DeviceTimeout(data) {
            return _super.call(this, data) || this;
        }
        return DeviceTimeout;
    }(WebAPI));
    var TTS =  (function (_super) {
        __extends$l(TTS, _super);
        function TTS(data) {
            var _this = _super.call(this, data) || this;
            _this.result = data.result;
            return _this;
        }
        return TTS;
    }(WebAPI));
    var WidgetFormUpdate =  (function (_super) {
        __extends$l(WidgetFormUpdate, _super);
        function WidgetFormUpdate(data) {
            return _super.call(this, data) || this;
        }
        return WidgetFormUpdate;
    }(WebAPI));
    var ConfigurationError =  (function (_super) {
        __extends$l(ConfigurationError, _super);
        function ConfigurationError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ConfigurationError.newInstance = function (parameter, value, data) {
            var result = new ConfigurationError({
                clazz: null,
                code: 498,
                exceptionName: "ConfigurationErrorException",
                message: value ? "Invalid value ".concat(JSON.stringify(value, MapOrSet_toJSON), " for parameter \"").concat(parameter, "\"") : "Missing parameter: ".concat(parameter),
            });
            result.parameter = parameter;
            result.value = value;
            result.data = data;
            return result;
        };
        return ConfigurationError;
    }(WebAPI));

    function arrayConcat() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var result = [];
        if (args && args.length) {
            args.forEach(function (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));
    }
    var functionCheck = function (value) {
        return typeof value == "function" ? value : undefined;
    };
    var objectCheck = function (value) {
        return typeof value == "object" ? value : undefined;
    };
    var stringCheck = function (value) {
        return typeof value == "string" ? value : undefined;
    };
    var numberCheck = function (value) {
        return typeof value == "number" ? value : undefined;
    };
    var booleanCheck = function (value) {
        return typeof value == "boolean" ? value : undefined;
    };
    function loadConfig(prefix, checks, destination, source) {
        if (prefix === void 0) { prefix = []; }
        if (source == null || typeof source !== "object") {
            throw new Error("Configuration is not valid object");
        }
        prefix = arrayConcat(prefix);
        for (var parameter in checks.mandatory) {
            if (!source.hasOwnProperty(parameter)) {
                throw ConfigurationError.newInstance(arrayConcat(prefix, [parameter]).join("."));
            }
            else {
                var value = source[parameter];
                try {
                    var checked_value = checks.mandatory[parameter](value, destination[parameter], 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 (var parameter in checks.optional) {
            if (source.hasOwnProperty(parameter)) {
                var value = source[parameter];
                if (isEmpty(value)) {
                    continue;
                }
                try {
                    var checked_value = checks.optional[parameter](value, destination[parameter], 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(function (mediaParam, callMedia) {
            if (callMedia) {
                mediaParam[callMedia.trim().toLowerCase()] = true;
            }
            return mediaParam;
        }, {}));
    }
    var MediaParamImpl =  (function () {
        function MediaParamImpl(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;
            }
        }
        MediaParamImpl.prototype._hasMedia = function () {
            return this.audio || this.video || this.desktop;
        };
        MediaParamImpl.prototype.toCallMedia = function () {
            var 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;
        };
        return MediaParamImpl;
    }());
    var RetryOptions =  (function () {
        function RetryOptions(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,
            },
        };
        return RetryOptions;
    }());

    function unwrapExports (x) {
    	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
    }

    function createCommonjsModule(fn, basedir, module) {
    	return module = {
    	  path: basedir,
    	  exports: {},
    	  require: function (path, base) {
          return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
        }
    	}, fn(module, module.exports), module.exports;
    }

    function commonjsRequire () {
    	throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
    }

    var s = 1000;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    var ms = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === 'string' && val.length > 0) {
        return parse$2(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$2(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' : '');
    }

    function setup(env) {
    	createDebug.debug = createDebug;
    	createDebug.default = createDebug;
    	createDebug.coerce = coerce;
    	createDebug.disable = disable;
    	createDebug.enable = enable;
    	createDebug.enabled = enabled;
    	createDebug.humanize = ms;
    	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;

    var browser$1 = createCommonjsModule(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;
    	}
    };
    });
    var debug$1 = browser$1;
    browser$1.formatArgs;
    browser$1.save;
    browser$1.load;
    browser$1.useColors;
    browser$1.storage;
    browser$1.destroy;
    browser$1.colors;
    browser$1.log;

    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 = {}));
    var LogConfig =  (function () {
        function LogConfig(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: function (logLevel) {
                    if (logLevel && logLevel >= LogLevel.Verbose && logLevel <= LogLevel.None) {
                        return logLevel;
                    }
                    else {
                        return undefined;
                    }
                },
            },
        };
        return LogConfig;
    }());

    var __extends$k = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __());
        };
    })();
    debug$1.formatters.j = function (obj) {
        try {
            return undefined === obj ? "" : JSON.stringify(obj, MapOrSet_toJSON);
        }
        catch (error) {
            return "[UnexpectedJSONParseError]: " + error.message;
        }
    };
    var LogConfigurator =  (function () {
        function LogConfigurator() {
        }
        return LogConfigurator;
    }());
    var DefaultLogConfigurator =  (function (_super) {
        __extends$k(DefaultLogConfigurator, _super);
        function DefaultLogConfigurator(
        conf) {
            var _this = _super.call(this) || this;
            _this.conf = conf;
            return _this;
        }
        Object.defineProperty(DefaultLogConfigurator.prototype, "objectToJson", {
            get: function () {
                var _a;
                return (_a = this.conf.objectToJson) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.objectToJson;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DefaultLogConfigurator.prototype, "instanceIdLogged", {
            get: function () {
                var _a;
                return (_a = this.conf.instanceIdLogged) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.instanceIdLogged;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DefaultLogConfigurator.prototype, "logLevel", {
            get: function () {
                var _a;
                return (_a = this.conf.logLevel) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.logLevel;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DefaultLogConfigurator.prototype, "prefix", {
            get: function () {
                var _a;
                return (_a = this.conf.prefix) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.prefix;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DefaultLogConfigurator.prototype, "timestamp", {
            get: function () {
                var _a;
                return (_a = this.conf.timestamp) !== null && _a !== void 0 ? _a : DefaultLogConfigInstance.timestamp;
            },
            enumerable: false,
            configurable: true
        });
        return DefaultLogConfigurator;
    }(LogConfigurator));
    var DefaultLogConfigInstance = new LogConfig();
    var DefaultLogConfiguratorInstance = new DefaultLogConfigurator(DefaultLogConfigInstance);
    var Log$1 =  (function () {
        function Log(
        _pkg,
        _instanceId,
        _config) {
            var _this = this;
            this._pkg = _pkg;
            this._instanceId = _instanceId;
            this._config = _config;
            this.debugMethods = new Map();
            this.verbose = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Verbose, null, args);
            };
            this.debug = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Debug, null, args);
            };
            this.info = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Info, null, args);
            };
            this.warn = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Warn, null, args);
            };
            this.error = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Error, null, args);
            };
            this.fatal = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this._log(LogLevel.Fatal, null, args);
            };
            if (!_instanceId) {
                this._instanceId = "";
            }
            if (!_config) {
                this._config = DefaultLogConfiguratorInstance;
            }
        }
        Log.of = function (pkg, client) {
            var logger = Log.create(pkg);
            logger.client = client;
            return logger;
        };
        Log.create = function (pkg, instanceId, config) {
            return new Log(pkg, instanceId, config);
        };
        Log.getPrefixTimestamp = function (timestamp) {
            return format$1("{0}-{1}-{2} {3}:{4}:{5}.{6}", [timestamp.getFullYear(), zeroLeftPad(timestamp.getMonth() + 1), zeroLeftPad(timestamp.getDate()), zeroLeftPad(timestamp.getHours()), zeroLeftPad(timestamp.getMinutes()), zeroLeftPad(timestamp.getSeconds()), zeroLeftPad(timestamp.getMilliseconds(), 3)]);
        };
        Object.defineProperty(Log.prototype, "client", {
            set: function (client) {
                if (client) {
                    this.instanceId = client.instanceId;
                    this.config = client.logConfigurator;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Log.prototype, "config", {
            get: function () {
                return this._config;
            },
            set: function (config) {
                if (config) {
                    this._config = config;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Log.prototype, "instanceId", {
            get: function () {
                return this._instanceId;
            },
            set: function (instanceId) {
                this._instanceId = instanceId || "";
            },
            enumerable: false,
            configurable: true
        });
        Log.prototype.getDebugMethod = function (level) {
            var packageName = "".concat(this._config.prefix).concat(this._config.instanceIdLogged ? "_" + this._instanceId : "").concat(this._pkg ? ":".concat(this._pkg) : "");
            switch (level) {
                case LogLevel.Verbose:
                    packageName += ":VERBOSE";
                    break;
                case LogLevel.Debug:
                    packageName += ":DEBUG";
                    break;
                case LogLevel.Info:
                    packageName += ":INFO";
                    break;
                case LogLevel.Warn:
                    packageName += ":WARN";
                    break;
                case LogLevel.Error:
                    packageName += ":ERROR";
                    break;
                case LogLevel.Fatal:
                    packageName += ":FATAL";
                    break;
            }
            var debugMethod = this.debugMethods.get(packageName);
            if (!debugMethod) {
                debugMethod = debug$1(packageName);
                this.debugMethods.set(packageName, debugMethod);
            }
            return debugMethod;
        };
        Log.prototype._log = function (level, timestamp) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            if (level && level < LogLevel.None && level >= this._config.logLevel) {
                var args0 = [this._config.timestamp ? Log.getPrefixTimestamp(timestamp !== null && timestamp !== void 0 ? timestamp : new Date()) : ""];
                if (args && args.length) {
                    if (typeof args[0] !== "string") {
                        args = [].slice.call(args[0]);
                    }
                    var strArg0 = "".concat(args[0]);
                    if (strArg0.length) {
                        args0.push(strArg0);
                    }
                    args[0] = args0.join("");
                }
                else {
                    args = args0;
                }
                if (this._config.objectToJson) {
                    args[0] += (args[0].length ? " " : "") + "%j";
                }
                this.getDebugMethod(level).apply(debug$1, args);
            }
        };
        Log.prototype.log = function (level) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            this._log(level, null, args);
        };
        Log.prototype.logWithTimestamp = function (level, timestamp) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            this._log(level, timestamp, args);
        };
        return Log;
    }());
    var zeroLeftPad = function (value, len) {
        if (len === void 0) { len = 2; }
        var val = value.toString();
        try {
            return val.padStart(len, "0");
        }
        catch (e) {
            return val.length < len ? "0".concat(val) : val;
        }
    };
    var format$1 = function (format, args) {
        return format.replace(/{(\d+)}/g, function (match, number) {
            if (args[number] != null) {
                return args[number];
            }
            return match;
        });
    };

    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$1(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$1(value)) {
        var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
        value = isObject$1(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$1(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$1(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$1(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;

    var __extends$j = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$l = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$l = (undefined && undefined.__generator) || function (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 (_) 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 (_super) {
        __extends$j(ObservablePromise, _super);
        function ObservablePromise() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ObservablePromise;
    })(Observable));
    var LiveResultPromiseWrapper =  (function () {
        function LiveResultPromiseWrapper( liveResult) {
            this.liveResult = liveResult;
        }
        Object.defineProperty(LiveResultPromiseWrapper.prototype, "result", {
            get: function () {
                return this.liveResult.result.toPromise();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LiveResultPromiseWrapper.prototype, "notification", {
            get: function () {
                return this.liveResult.notification;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LiveResultPromiseWrapper.prototype, "resultSync", {
            get: function () {
                return this.liveResult.resultSync.pipe(map(function (result) { return result.pipe(take(1)).toPromise(); }));
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LiveResultPromiseWrapper.prototype, "stopResult", {
            get: function () {
                return this.liveResult.stopResult;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LiveResultPromiseWrapper.prototype, "stopNotification", {
            get: function () {
                return this.liveResult.stopNotification;
            },
            enumerable: false,
            configurable: true
        });
        return LiveResultPromiseWrapper;
    }());
    var DialParams =  (function () {
        function DialParams(params) {
            this.params = {
                privateCall: false,
                channelId: ChannelType.PhoneCall,
            };
            if (params && isObject$1(params)) {
                for (var key in params) {
                    this.params[key] = params[key];
                }
            }
            this.params.media = new MediaParamImpl(this.params.media);
        }
        DialParams.prototype.equals = function (builder) {
            if (!builder) {
                return false;
            }
            for (var key in builder.params) {
                if (builder.params[key] !== this.params[key]) {
                    return false;
                }
            }
            return true;
        };
        DialParams.prototype.isForApp = function () {
            var _a, _b;
            return (_b = (_a = this.params.fromDevice) === null || _a === void 0 ? void 0 : _a.startsWith("_app_")) !== null && _b !== void 0 ? _b : false;
        };
        DialParams.prototype.toRequestParams = function (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,
            ];
        };
        return DialParams;
    }());
    var Methods =  (function () {
        function Methods(client) {
            this.client = client;
            this.log = Log$1.of("methods", client);
            this.transport = client.transport;
        }
        Methods.prototype.requestPromise = function (method, params, options) {
            return this.requestObservable(method, params, options).pipe(take(1));
        };
        Methods.prototype.requestObservable = function (method, params, options) {
            return this.requestInternal(method, params, options, false, false).response.result;
        };
        Methods.prototype.requestChunked = function (method, params, options) {
            return this.requestInternal(method, params, options, true, false).response.result;
        };
        Methods.prototype.requestPromiseUpdate = function (method, params, options) {
            var request = this.requestObservableUpdate(method, params, options);
            request.response.result = request.response.result.pipe(take(1));
            request.response.resultSync = request.response.resultSync.pipe(map(function (result) { return result.pipe(take(1)); }));
            return {
                response: request.response,
                toLiveResult: function () { return new LiveResultPromiseWrapper(request.toLiveResult()); },
            };
        };
        Methods.prototype.requestObservableUpdate = function (method, params, options) {
            return this.requestInternal(method, params, options, false, true);
        };
        Methods.prototype.requestChunkedUpdate = function (method, params, options) {
            return this.requestInternal(method, params, options, true, true);
        };
        Methods.prototype.requestInternal = function (method, params, options, responseIsChunked, activateNotification) {
            try {
                this.loadTransport();
            }
            catch (error) {
                return this.transport.emitError(error, activateNotification);
            }
            this.log.info("Call method: ".concat(method), params);
            return this.transport.request(method, params, options, responseIsChunked, activateNotification);
        };
        Methods.prototype.loadTransport = function () {
            var _a;
            if (!this.transport.loading && !this.transport.connected && (!this.transport.getCrossStorage() || ((_a = this.transport.getCrossStorage()) === null || _a === void 0 ? void 0 : _a.getLevel()) == Storagelevel.master)) {
                this.transport.load();
            }
        };
        Methods.prototype.restartSessionId = function (requestTimeout) {
            return this.requestPromise("restartSessionId", [], { requestTimeout: requestTimeout });
        };
        return Methods;
    }());
    var NotificationManager =  (function () {
        function NotificationManager(client, notificationId, request, result, modifyNotification) {
            this.client = client;
            this.request = request;
            this.result = result;
            this.modifyNotification = modifyNotification;
            this._started = false;
            this.notificationSubscription = Subscription.EMPTY;
            this.log = Log$1.of("NotificationManager:".concat(notificationId), client);
        }
        Object.defineProperty(NotificationManager.prototype, "started", {
            get: function () {
                return this._started;
            },
            enumerable: false,
            configurable: true
        });
        NotificationManager.prototype.start = function (requestTimeout) {
            return __awaiter$l(this, void 0, void 0, function () {
                var stopResult, response_1, notify;
                var _this = this;
                return __generator$l(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , this.stop()];
                        case 1:
                            stopResult = _a.sent();
                            if (stopResult) {
                                response_1 = this.request(requestTimeout);
                                notify = new Promise(function (resolve, reject) {
                                    response_1.resultSync.pipe(concatMap(function (response) { return response; })).subscribe(resolve, reject);
                                });
                                this.notificationSubscription = response_1.notification
                                    .pipe(map(function (data) { return _this.modifyNotification(data); }), catchError(function (e) {
                                    _this.log.warn("Error on modifyNotification", e);
                                    return of(null);
                                }))
                                    .subscribe(function (data) {
                                    if (data) {
                                        try {
                                            _this.result.next(data);
                                        }
                                        catch (e) {
                                            _this.log.error("Error on handle notification", e);
                                        }
                                    }
                                });
                                this._started = true;
                                return [2 , notify];
                            }
                            else {
                                return [2 , stopResult];
                            }
                    }
                });
            });
        };
        NotificationManager.prototype.stop = function () {
            return __awaiter$l(this, void 0, void 0, function () {
                return __generator$l(this, function (_a) {
                    this.notificationSubscription.unsubscribe();
                    this._started = false;
                    return [2 , true];
                });
            });
        };
        return NotificationManager;
    }());

    var __extends$i = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 ExtenUsedBy =  (function (_super) {
        __extends$i(ExtenUsedBy, _super);
        function ExtenUsedBy(data) {
            var _this = _super.call(this, data) || this;
            _this.exten = data.exten;
            _this.extenType = data.extenType;
            _this.usedBy = data.usedBy;
            _this.nameUsedBy = data.nameUsedBy;
            return _this;
        }
        return ExtenUsedBy;
    }(WebAPI));
    var InternalErrorWebAPI =  (function (_super) {
        __extends$i(InternalErrorWebAPI, _super);
        function InternalErrorWebAPI(data) {
            return _super.call(this, data) || this;
        }
        return InternalErrorWebAPI;
    }(WebAPI));
    var FeatureNotSupported =  (function (_super) {
        __extends$i(FeatureNotSupported, _super);
        function FeatureNotSupported(data) {
            return _super.call(this, data) || this;
        }
        return FeatureNotSupported;
    }(WebAPI));
    var FeatureNotAllowed =  (function (_super) {
        __extends$i(FeatureNotAllowed, _super);
        function FeatureNotAllowed(data) {
            return _super.call(this, data) || this;
        }
        return FeatureNotAllowed;
    }(WebAPI));
    var InvalidDateRange =  (function (_super) {
        __extends$i(InvalidDateRange, _super);
        function InvalidDateRange(data) {
            return _super.call(this, data) || this;
        }
        return InvalidDateRange;
    }(WebAPI));
    var MobileAccessNotSupported =  (function (_super) {
        __extends$i(MobileAccessNotSupported, _super);
        function MobileAccessNotSupported(data) {
            return _super.call(this, data) || this;
        }
        return MobileAccessNotSupported;
    }(WebAPI));
    var NRUserExcedeed =  (function (_super) {
        __extends$i(NRUserExcedeed, _super);
        function NRUserExcedeed(data) {
            return _super.call(this, data) || this;
        }
        return NRUserExcedeed;
    }(WebAPI));

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

    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 version = { "version": "22.1.78" }.version;
    var LIB_VERSION$1 = version;

    var parse_1 = parse$1;
    var serialize_1 = serialize;
    var decode = decodeURIComponent;
    var encode$1 = encodeURIComponent;
    var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
    function parse$1(str, options) {
      if (typeof str !== 'string') {
        throw new TypeError('argument str must be a string');
      }
      var obj = {};
      var opt = options || {};
      var pairs = str.split(';');
      var dec = opt.decode || decode;
      for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i];
        var index = pair.indexOf('=');
        if (index < 0) {
          continue;
        }
        var key = pair.substring(0, index).trim();
        if (undefined == obj[key]) {
          var val = pair.substring(index + 1, pair.length).trim();
          if (val[0] === '"') {
            val = val.slice(1, -1);
          }
          obj[key] = tryDecode(val, dec);
        }
      }
      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) {
        if (typeof opt.expires.toUTCString !== 'function') {
          throw new TypeError('option expires is invalid');
        }
        str += '; Expires=' + opt.expires.toUTCString();
      }
      if (opt.httpOnly) {
        str += '; HttpOnly';
      }
      if (opt.secure) {
        str += '; Secure';
      }
      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 tryDecode(str, decode) {
      try {
        return decode(str);
      } catch (e) {
        return str;
      }
    }

    var __extends$h = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 WebapiConfig =  (function () {
        function WebapiConfig(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.requestTimeout = 15000;
            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: function (urlValue) {
                    var 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: function (userAgentConfig, destination, prefix) {
                    var userAgent = objectCheck(userAgentConfig);
                    return userAgent ? new WebapiUserAgentConfig(userAgent, arrayConcat(prefix, ["agent"])) : userAgent;
                },
            },
            optional: {
                sessionParams: function (value) {
                    var objectValue = typeof value == "object" ? value : undefined;
                    if (!!objectValue) {
                        delete value["force"];
                        delete value["access_token"];
                        delete value["deviceid"];
                        delete value["jsessionid"];
                    }
                    return objectValue;
                },
                storageUrl: function (url) { return WebapiConfig.CHECK_OPTIONS.mandatory.url(url); },
                retryOptions: function (retry, destination, prefix) {
                    var 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,
                loginTimeout: numberCheck,
                cookie_path: stringCheck,
                logConfig: function (retry, destination, prefix) {
                    var value = objectCheck(retry);
                    return value ? new WebapiClientLogConfig(value, arrayConcat(prefix, ["logConfig"])) : value;
                },
            },
        };
        return WebapiConfig;
    }());
    var WebapiClientLogConfig =  (function (_super) {
        __extends$h(WebapiClientLogConfig, _super);
        function WebapiClientLogConfig(options, prefix) {
            return _super.call(this, options, prefix) || this;
        }
        return WebapiClientLogConfig;
    }(LogConfig));
    var WebapiUserAgentConfig =  (function () {
        function WebapiUserAgentConfig(options, prefix) {
            if (!options)
                return;
            loadConfig(prefix, WebapiUserAgentConfig.CHECK_OPTIONS, this, options);
        }
        WebapiUserAgentConfig.CHECK_OPTIONS = {
            mandatory: {
                type: stringCheck,
                version: stringCheck,
            },
            optional: {
                description: stringCheck,
            },
        };
        return WebapiUserAgentConfig;
    }());

    var WebRTCMediaField =  (function () {
        function WebRTCMediaField(config, prefix) {
            this.loop = false;
            this.volume = 100;
            this.maxlength = null;
            this.interval = null;
            if (!config)
                return;
            loadConfig(prefix, WebRTCMediaField.CHECK_OPTIONS, this, config);
        }
        WebRTCMediaField.CHECK_OPTIONS = {
            mandatory: {
                src: stringCheck,
            },
            optional: {
                loop: booleanCheck,
                volume: function (volume) {
                    var 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,
            },
        };
        return WebRTCMediaField;
    }());

    var ring = "data:audio/webm; codecs=opus;base64, ";
    var ringback = "data:audio/webm; codecs=opus;base64, ";
    var ringAdvertising = "data:audio/webm; codecs=opus;base64, ";
    var busy = "data:audio/webm; codecs=opus;base64, ";
    var congestion = "data:audio/webm; codecs=opus;base64, ";
    var defaultPhoneSignal = {
        ring: {
            src: ring,
            loop: true,
            interval: 500,
        },
        ringback: {
            src: ringback,
            loop: true,
            interval: 3700,
        },
        ringAdvertising: {
            src: ringAdvertising,
            volume: 15,
            loop: true,
            interval: 3000,
        },
        busy: {
            src: busy,
            loop: true,
            maxlength: 3000,
        },
        congestion: {
            src: congestion,
            loop: true,
            maxlength: 3000,
        },
        dialtone: null,
        hold: null,
        dtmf: null,
    };

    var WebRTCMediaAudioSignal =  (function () {
        function WebRTCMediaAudioSignal(config, prefix) {
            var _a, _b, _c;
            this.ring = defaultPhoneSignal.ring;
            this.ringback = defaultPhoneSignal.ringback;
            this.ringAdvertising = defaultPhoneSignal.ringAdvertising;
            this.dialtone = (_a = defaultPhoneSignal.dialtone) !== null && _a !== void 0 ? _a : undefined;
            this.busy = defaultPhoneSignal.busy;
            this.congestion = defaultPhoneSignal.congestion;
            this.hold = (_b = defaultPhoneSignal.hold) !== null && _b !== void 0 ? _b : undefined;
            this.dtmf = (_c = defaultPhoneSignal.dtmf) !== null && _c !== void 0 ? _c : undefined;
            if (!config)
                return;
            for (var tone in config) {
                if (!this.hasOwnProperty(tone)) {
                    throw ConfigurationError.newInstance(arrayConcat(prefix).join("."), config[tone], new Error("".concat(tone, " is not valid media audio signal")));
                }
            }
            loadConfig(prefix, WebRTCMediaAudioSignal.CHECK_OPTIONS, this, config);
        }
        WebRTCMediaAudioSignal.CHECK_OPTIONS = {
            mandatory: {},
            optional: {
                ring: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["ring"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                ringback: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["ringback"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                ringAdvertising: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["ringAdvertising"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                dialtone: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["dialtone"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                busy: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["busy"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                congestion: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["congestion"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                hold: function (source, destination, prefix) { return loadConfig(arrayConcat(prefix, ["hold"]), WebRTCMediaField.CHECK_OPTIONS, destination, source); },
                dtmf: function (source, destination, prefix) {
                    for (var dtmf in source) {
                        if (destination.hasOwnProperty(dtmf)) {
                            if (source[dtmf]) {
                                loadConfig(arrayConcat(prefix, ["dtmf", dtmf]), WebRTCMediaField.CHECK_OPTIONS, destination[dtmf], source[dtmf]);
                            }
                            else {
                                destination[dtmf] = null;
                            }
                        }
                        else {
                            throw ConfigurationError.newInstance(arrayConcat(prefix, ["dtmf"]).join("."), source[dtmf], new Error("".concat(dtmf, " is not valid dtmf")));
                        }
                    }
                },
            },
        };
        return WebRTCMediaAudioSignal;
    }());
    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 = {}));

    var WebRTCMediaSignal =  (function () {
        function WebRTCMediaSignal(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: function (volume) {
                    var 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: function (volume) {
                    var 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: function (volume) {
                    var 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: function (audio, destination, prefix) {
                    var value = objectCheck(audio);
                    return value ? new WebRTCMediaAudioSignal(value, arrayConcat(prefix, ["audio"])) : value;
                },
            },
        };
        return WebRTCMediaSignal;
    }());

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

    var __extends$g = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 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$g(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 __awaiter$k = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$k = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    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$k(this, void 0, void 0, function () {
            var _audioContext, closeAudioContext, audioContextState;
            return __generator$k(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$k(this, void 0, void 0, function () {
            var audioSilence, autoPlayAllowed, mediaElement, error_1;
            return __generator$k(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$k(this, void 0, void 0, function () {
            var result, response;
            return __generator$k(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$k(void 0, void 0, void 0, function () {
        return __generator$k(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$k(void 0, void 0, void 0, function () {
        return __generator$k(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 ];
            }
        });
    }); })();

    var __awaiter$j = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$j = (undefined && undefined.__generator) || function (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 (_) 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 vuMeterOfMediaStream(mediaStream, onLevel, updateIntervalInMS) {
        if (updateIntervalInMS === void 0) { updateIntervalInMS = 25; }
        return __awaiter$j(this, void 0, void 0, function () {
            var audioContext;
            return __generator$j(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$j(this, void 0, void 0, function () {
            var audioContext, node;
            return __generator$j(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 __awaiter$i = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$i = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var supportedFeature = {
        setSinkId: null,
        createMediaStreamDestination: null,
    };
    function setSinkOutput(element, deviceId) {
        return __awaiter$i(this, void 0, void 0, function () {
            var e_1;
            return __generator$i(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 __awaiter$h = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$h = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var __spreadArray$4 = (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 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$h(this, void 0, void 0, function () {
                var _b, _c, listener;
                return __generator$h(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            _b = 0, _c = __spreadArray$4([], ((_a = this.listeners[event]) !== null && _a !== void 0 ? _a : []), true);
                            _d.label = 1;
                        case 1:
                            if (!(_b < _c.length)) return [3 , 4];
                            listener = _c[_b];
                            if (listener.once)
                                listener.dispose();
                            return [4 , listener.fn.apply(listener.context, args)];
                        case 2:
                            _d.sent();
                            _d.label = 3;
                        case 3:
                            _b++;
                            return [3 , 1];
                        case 4: return [2 ];
                    }
                });
            });
        };
        Emitter.prototype.dispose = function () {
            for (var event_1 in this.listeners) {
                for (var _i = 0, _a = __spreadArray$4([], this.listeners[event_1], true); _i < _a.length; _i++) {
                    var listener = _a[_i];
                    listener.dispose();
                }
                delete this.listeners[event_1];
            }
        };
        return Emitter;
    }());

    var __extends$f = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$g = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$g = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var WebRtcMedia =  (function (_super) {
        __extends$f(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$g(this, void 0, void 0, function () {
                var width, height, canvas, context, image;
                return __generator$g(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(val) {
      return Object.prototype.toString.call(val) === '[object Object]';
    }
    function compactObject(data) {
      if (!isObject(data)) {
        return data;
      }
      return Object.keys(data).reduce(function(accumulator, key) {
        const isObj = isObject(data[key]);
        const value = isObj ? compactObject(data[key]) : data[key];
        const isEmptyObject = isObj && !Object.keys(value).length;
        if (value === undefined || isEmptyObject) {
          return accumulator;
        }
        return Object.assign(accumulator, {[key]: value});
      }, {});
    }
    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,
        shimMediaStream: shimMediaStream,
        shimOnTrack: shimOnTrack$1,
        shimGetSendersWithDtmf: shimGetSendersWithDtmf,
        shimGetStats: shimGetStats,
        shimSenderReceiverGetStats: shimSenderReceiverGetStats,
        shimAddTrackRemoveTrackWithNative: shimAddTrackRemoveTrackWithNative,
        shimAddTrackRemoveTrack: shimAddTrackRemoveTrack,
        shimPeerConnection: shimPeerConnection$1,
        fixNegotiationNeeded: fixNegotiationNeeded,
        shimGetUserMedia: shimGetUserMedia$2,
        shimGetDisplayMedia: shimGetDisplayMedia$1
    });

    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,
        shimOnTrack: shimOnTrack,
        shimPeerConnection: shimPeerConnection,
        shimSenderGetStats: shimSenderGetStats,
        shimReceiverGetStats: shimReceiverGetStats,
        shimRemoveStream: shimRemoveStream,
        shimRTCDataChannel: shimRTCDataChannel,
        shimAddTransceiver: shimAddTransceiver,
        shimGetParameters: shimGetParameters,
        shimCreateOffer: shimCreateOffer,
        shimCreateAnswer: shimCreateAnswer,
        shimGetUserMedia: shimGetUserMedia$1,
        shimGetDisplayMedia: shimGetDisplayMedia
    });

    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,
        shimLocalStreamsAPI: shimLocalStreamsAPI,
        shimRemoteStreamsAPI: shimRemoteStreamsAPI,
        shimCallbacksAPI: shimCallbacksAPI,
        shimGetUserMedia: shimGetUserMedia,
        shimConstraints: shimConstraints,
        shimRTCIceServerUrls: shimRTCIceServerUrls,
        shimTrackEventTransceiver: shimTrackEventTransceiver,
        shimCreateOfferLegacy: shimCreateOfferLegacy,
        shimAudioContext: shimAudioContext
    });

    var sdp = createCommonjsModule(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;
    }
    });

    var sdp$1 = /*#__PURE__*/_mergeNamespaces({
        __proto__: null,
        'default': sdp,
        __moduleExports: sdp
    }, [sdp]);

    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 = sdp.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 = sdp.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 = sdp.splitSections(description.sdp);
        sections.shift();
        return sections.some(mediaSection => {
          const mLine = sdp.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 = sdp.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,
        shimRTCIceCandidate: shimRTCIceCandidate,
        shimRTCIceCandidateRelayProtocol: shimRTCIceCandidateRelayProtocol,
        shimMaxMessageSize: shimMaxMessageSize,
        shimSendThrowTypeError: shimSendThrowTypeError,
        shimConnectionState: shimConnectionState,
        removeExtmapAllowMixed: removeExtmapAllowMixed,
        shimAddIceCandidateNullOrEmpty: shimAddIceCandidateNullOrEmpty,
        shimParameterlessSetLocalDescription: shimParameterlessSetLocalDescription
    });

    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: sdp$1,
      };
      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 __extends$e = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$f = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$f = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var MediaSink =  (function (_super) {
        __extends$e(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) {
                _this._container.append(videoSink.htmlElement);
                _this._videoStarted = true;
            });
            _this.on("videoStop", function (videoSink) {
                if (_this._videoStarted) {
                    _this._videoStarted = false;
                    _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$f(this, void 0, void 0, function () {
                return __generator$f(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$f(this, void 0, void 0, function () {
                var audioTracks, videoTracks;
                return __generator$f(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , this.stopTrack()];
                        case 1:
                            _a.sent();
                            if (!stream) return [3 , 11];
                            audioTracks = stream.getAudioTracks();
                            if (!(audioTracks && audioTracks.length)) return [3 , 6];
                            if (!!(this._audio.stream && this._audio.stream === stream)) return [3 , 6];
                            return [4 , this._audio.stop()];
                        case 2:
                            _a.sent();
                            return [4 , this._audio.setStream(stream)];
                        case 3:
                            _a.sent();
                            if (!!isGestureRequiredForPlay()) return [3 , 5];
                            return [4 , this._audio.play()];
                        case 4:
                            _a.sent();
                            _a.label = 5;
                        case 5:
                            this.emit("audioStart", this._audio);
                            _a.label = 6;
                        case 6:
                            videoTracks = stream.getVideoTracks();
                            if (!(videoTracks && videoTracks.length)) return [3 , 11];
                            if (!!(this._video.stream && this._video.stream === stream)) return [3 , 11];
                            return [4 , this._video.stop()];
                        case 7:
                            _a.sent();
                            return [4 , this._video.setStream(stream)];
                        case 8:
                            _a.sent();
                            if (!!isGestureRequiredForPlay()) return [3 , 10];
                            return [4 , this._video.play()];
                        case 9:
                            _a.sent();
                            _a.label = 10;
                        case 10:
                            this.emit("videoStart", this._video);
                            _a.label = 11;
                        case 11: return [2 ];
                    }
                });
            });
        };
        MediaSink.prototype.stopTrack = function () {
            return __awaiter$f(this, void 0, void 0, function () {
                return __generator$f(this, function (_a) {
                    if (this._audio && this._audio.stream) {
                        this._audio.setStream();
                        this.emit("audioStop", this._audio);
                    }
                    if (this._video && this._video.stream) {
                        this._video.setStream();
                        this.emit("videoStop", this._video);
                    }
                    return [2 ];
                });
            });
        };
        return MediaSink;
    }(Emitter));
    var LocalMediaSink =  (function (_super) {
        __extends$e(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 (prev, curr, constraints) {
                return _this.replaceTrack(_this._localMedia.stream);
            });
            (_d = _this._localMedia) === null || _d === void 0 ? void 0 : _d.on("changeAudioOutput", function (audioOutput) { return __awaiter$f(_this, void 0, void 0, function () {
                return __generator$f(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$f(this, void 0, void 0, function () {
                return __generator$f(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, _e, _f;
            if (((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.constraints) && ((_b = this._localMedia) === null || _b === void 0 ? void 0 : _b.constraints.video)) {
                if (typeof ((_c = this._localMedia) === null || _c === void 0 ? void 0 : _c.constraints.video) === "boolean" && typeof ((_d = this._localMedia) === null || _d === void 0 ? void 0 : _d.constraints.video)) {
                    if (this._video) {
                        this._video.viewMirror = true;
                    }
                }
                else if (typeof ((_e = this._localMedia) === null || _e === void 0 ? void 0 : _e.constraints.video) === "object") {
                    var videoConstraints = (_f = this._localMedia) === null || _f === void 0 ? void 0 : _f.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";
                    }
                }
            }
        };
        return LocalMediaSink;
    }(MediaSink));
    var RemoteMediaSink =  (function (_super) {
        __extends$e(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$f(_this, void 0, void 0, function () {
                return __generator$f(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$f(this, void 0, void 0, function () {
                return __generator$f(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$f(this, void 0, void 0, function () {
                var stream, _a;
                return __generator$f(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$f(this, void 0, void 0, function () {
                return __generator$f(this, function (_a) {
                    switch (track.kind) {
                        case "audio":
                            if (this._audio && this._audio.stream) {
                                this._audio.setStream();
                                this.emit("audioStop", this._audio);
                            }
                            break;
                        case "video":
                            if (this._video && this._video.stream) {
                                this._video.setStream();
                                this.emit("videoStop", this._video);
                            }
                            break;
                    }
                    return [2 ];
                });
            });
        };
        return RemoteMediaSink;
    }(MediaSink));
    var HTMLMediaElementSink =  (function (_super) {
        __extends$e(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$f(this, void 0, void 0, function () {
                return __generator$f(this, function (_a) {
                    return [2 , this.htmlElement.play()];
                });
            });
        };
        HTMLMediaElementSink.prototype.stop = function () {
            return __awaiter$f(this, void 0, void 0, function () {
                return __generator$f(this, function (_a) {
                    return [2 , this.htmlElement.pause()];
                });
            });
        };
        HTMLMediaElementSink.prototype.setSinkId = function (deviceId) {
            return __awaiter$f(this, void 0, void 0, function () {
                return __generator$f(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$f(this, void 0, void 0, function () {
                return __generator$f(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$e(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$e(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 __extends$d = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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$4 = (undefined && undefined.__assign) || function () {
        __assign$4 = Object.assign || function(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$4.apply(this, arguments);
    };
    var __awaiter$e = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$e = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var LocalMedia =  (function (_super) {
        __extends$d(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 (previousTracks) {
                if (previousTracks && previousTracks.length) {
                    previousTracks.forEach(function (track) { return track.stop(); });
                }
                _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$e(this, void 0, void 0, function () {
                return __generator$e(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$e(this, void 0, void 0, function () {
                var _a, e_1;
                return __generator$e(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$e(this, void 0, void 0, function () {
                return __generator$e(this, function (_c) {
                    try {
                        (_a = this._stream) === null || _a === void 0 ? void 0 : _a.getTracks().forEach(function (track) { return track.stop(); });
                    }
                    catch (e) { }
                    (_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$e(this, void 0, void 0, function () {
                return __generator$e(this, function (_a) {
                    return [2 , this.changeConstraints(this.buildConstraints(audioInput, videoInput))];
                });
            });
        };
        LocalMedia.prototype.buildConstraints = function (audioInput, videoInput) {
            var _a, _b, _c, _d, _e, _f;
            var constraints = {};
            if (audioInput) {
                if ((_a = this._constraints) === null || _a === void 0 ? void 0 : _a.audio) {
                    if (typeof this._constraints.audio === "boolean") {
                        if (typeof audioInput === "boolean") {
                            constraints.audio = audioInput;
                        }
                        else if (audioInput.kind === "audioinput") {
                            constraints.audio = { deviceId: { exact: audioInput.deviceId } };
                        }
                        else {
                            throw new TLinkError("error on LocalMedia.buildConstraints, audioInput.kind is ".concat(audioInput.kind));
                        }
                    }
                    else {
                        if (typeof audioInput === "boolean") {
                            if (audioInput === true) {
                                constraints.audio = true;
                            }
                        }
                        else if (audioInput.kind === "audioinput") {
                            constraints.audio = __assign$4(__assign$4({}, this._constraints.audio), { deviceId: { exact: audioInput.deviceId } });
                        }
                        else {
                            throw new TLinkError("error on LocalMedia.buildConstraints, audioInput.kind is ".concat(audioInput.kind));
                        }
                    }
                }
                else {
                    constraints.audio = audioInput;
                }
            }
            else {
                constraints.audio = (_b = this.constraints) === null || _b === void 0 ? void 0 : _b.video;
                if ((audioInput !== undefined && (audioInput !== null && audioInput !== void 0 ? audioInput : false)) || false === false) {
                    if (((_c = this._constraints) === null || _c === void 0 ? void 0 : _c.audio) && typeof this._constraints.audio === "object") {
                        delete constraints.audio.deviceId;
                    }
                }
            }
            if (videoInput) {
                if ((_d = this._constraints) === null || _d === void 0 ? void 0 : _d.video) {
                    if (typeof this._constraints.video === "boolean") {
                        if (typeof videoInput === "boolean") {
                            constraints.video = videoInput;
                        }
                        else if (videoInput.kind === "videoinput") {
                            constraints.video = { deviceId: { exact: videoInput.deviceId } };
                        }
                        else {
                            throw new TLinkError("error on LocalMedia.buildConstraints, videoInput.kind is ".concat(videoInput.kind));
                        }
                    }
                    else {
                        if (typeof videoInput === "boolean") {
                            if (videoInput === true) {
                                constraints.video = true;
                            }
                        }
                        else if (videoInput.kind === "videoinput") {
                            constraints.video = __assign$4(__assign$4({}, this._constraints.video), { deviceId: { exact: videoInput.deviceId } });
                        }
                        else {
                            throw new TLinkError("error on LocalMedia.buildConstraints, videoInput.kind is ".concat(videoInput.kind));
                        }
                    }
                }
                else {
                    constraints.video = videoInput;
                }
            }
            else {
                constraints.video = (_e = this.constraints) === null || _e === void 0 ? void 0 : _e.video;
                if ((videoInput !== undefined && (videoInput !== null && videoInput !== void 0 ? videoInput : false)) || false === false) {
                    if (((_f = this._constraints) === null || _f === void 0 ? void 0 : _f.video) && typeof this._constraints.video === "object") {
                        delete constraints.video.deviceId;
                    }
                }
            }
            if (constraints.video && typeof constraints.video === "object") {
                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$e(this, void 0, void 0, function () {
                return __generator$e(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) {
            return __awaiter$e(this, void 0, void 0, function () {
                var constraint, constraint, stream, previousTracks, i, track, currentTracks, i, track;
                return __generator$e(this, function (_a) {
                    switch (_a.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];
                                    }
                                }
                            }
                            this._constraints = constraints;
                            if (!this.started) return [3 , 3];
                            return [4 , navigator.mediaDevices.getUserMedia(this._constraints)];
                        case 1:
                            stream = _a.sent();
                            previousTracks = this._stream.getTracks();
                            if (previousTracks) {
                                for (i = 0; i < previousTracks.length; i++) {
                                    track = previousTracks[i];
                                    this._stream.removeTrack(track);
                                }
                            }
                            currentTracks = stream.getTracks();
                            if (currentTracks) {
                                for (i = 0; i < currentTracks.length; i++) {
                                    track = currentTracks[i];
                                    this._stream.addTrack(track);
                                }
                            }
                            return [4 , this.emit("replaceTrack", previousTracks, currentTracks, constraints)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [2 ];
                    }
                });
            });
        };
        LocalMedia.prototype.grabVideoFrame = function () {
            return __awaiter$e(this, void 0, void 0, function () {
                return __generator$e(this, function (_a) {
                    return [2 , _super.prototype.grabVideoFrame.call(this, this._sink.videoSink)];
                });
            });
        };
        return LocalMedia;
    }(WebRtcMedia));

    var __extends$c = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$d = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$d = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    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, "kind", {
            get: function () {
                return this.device.kind;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DeviceInfo.prototype, "label", {
            get: function () {
                return this.device.label;
            },
            enumerable: false,
            configurable: true
        });
        DeviceInfo.prototype.toJSON = function () {
            return this.device.toJSON();
        };
        return DeviceInfo;
    }());
    var AudioInput =  (function (_super) {
        __extends$c(AudioInput, _super);
        function AudioInput(device) {
            return _super.call(this, device) || this;
        }
        return AudioInput;
    }(DeviceInfo));
    var VideoInput =  (function (_super) {
        __extends$c(VideoInput, _super);
        function VideoInput(device) {
            return _super.call(this, device) || this;
        }
        return VideoInput;
    }(DeviceInfo));
    var AudioOutput =  (function (_super) {
        __extends$c(AudioOutput, _super);
        function AudioOutput(device) {
            return _super.call(this, device) || this;
        }
        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$c(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());
            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$d(this, void 0, void 0, function () {
                var localStream, mediaDevice, devices;
                return __generator$d(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 (d) { return d.deviceId !== "default" && d.deviceId !== "communications"; }).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 __extends$b = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$c = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$c = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var RemoteMedia =  (function (_super) {
        __extends$b(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$c(this, void 0, void 0, function () {
                return __generator$c(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$c(this, void 0, void 0, function () {
                return __generator$c(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$c(this, void 0, void 0, function () {
                var prevAudioOutput, e_1;
                return __generator$c(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$c(this, void 0, void 0, function () {
                return __generator$c(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 grammar_1 = createCommonjsModule(function (module) {
    var grammar = module.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).forEach(function (key) {
      var objs = grammar[key];
      objs.forEach(function (obj) {
        if (!obj.reg) {
          obj.reg = /(.*)/;
        }
        if (!obj.format) {
          obj.format = '%s';
        }
      });
    });
    });
    grammar_1.v;
    grammar_1.o;
    grammar_1.s;
    grammar_1.i;
    grammar_1.u;
    grammar_1.e;
    grammar_1.p;
    grammar_1.z;
    grammar_1.r;
    grammar_1.t;
    grammar_1.c;
    grammar_1.b;
    grammar_1.m;
    grammar_1.a;

    var parser = createCommonjsModule(function (module, 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 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_1[type] || []).length; j += 1) {
          var obj = grammar_1[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.parse;
    parser.parseParams;
    parser.parseFmtpConfig;
    parser.parsePayloads;
    parser.parseRemoteCandidates;
    parser.parseImageAttributes;
    parser.parseSimulcastStreamList;

    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 = 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_1[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_1.m[0], mLine));
        innerOrder.forEach(function (type) {
          grammar_1[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 write = writer;
    var parse = parser.parse;
    parser.parseParams;
    parser.parseFmtpConfig;
    parser.parsePayloads;
    parser.parseRemoteCandidates;
    parser.parseImageAttributes;
    parser.parseSimulcastStreamList;

    var SessionDescription =  (function () {
        function SessionDescription(sdp, type) {
            this._sdp = sdp ? parse(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 __extends$a = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$b = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$b = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var StatsGatherer =  (function (_super) {
        __extends$a(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$b(this, void 0, void 0, function () {
                var _a;
                return __generator$b(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 __extends$9 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$a = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$a = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var __spreadArray$3 = (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 Connection =  (function (_super) {
        __extends$9(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$a(this, void 0, void 0, function () {
                var _this = this;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var _b, _c, e_1;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var _b, _c, e_2;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var prevSignallingState, newSignallingState, e_3;
                var _this = this;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var prevSignallingState, newSignallingState, e_4;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var candidateByType, candidate;
                var _this = this;
                return __generator$a(this, function (_a) {
                    candidateByType = __spreadArray$3([], candidates.filter(function (c) { return !!c; }), true).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$3(__spreadArray$3(__spreadArray$3([], (candidateByType.get(Candidate.Type.Host) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    }), true), (candidateByType.get(Candidate.Type.Srflx) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    }), true), (candidateByType.get(Candidate.Type.Relay) || []).sort(function (c1, c2) {
                        return c1.parts.protocol > c2.parts.protocol ? -1 : 1;
                    }), true);
                    return [2 , Promise.all(candidate.map(function (candidate) { return _this.addRemoteCandidate(candidate); }))];
                });
            });
        };
        Connection.prototype.addRemoteCandidate = function (candidate) {
            var _a;
            return __awaiter$a(this, void 0, void 0, function () {
                var e_5;
                return __generator$a(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$a(this, void 0, void 0, function () {
                var senderKind, tracksKind, _c, _d, _i, kind, tracks, sender, _e, tracks_1, track;
                var _this = this;
                return __generator$a(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 , 9];
                            kind = _c[_i];
                            tracks = tracksKind[kind];
                            sender = senderKind[kind];
                            if (!(tracks && tracks.length)) return [3 , 7];
                            _e = 0, tracks_1 = tracks;
                            _f.label = 2;
                        case 2:
                            if (!(_e < tracks_1.length)) return [3 , 6];
                            track = tracks_1[_e];
                            if (!sender) return [3 , 4];
                            return [4 , sender.replaceTrack(track)];
                        case 3:
                            _f.sent();
                            return [3 , 5];
                        case 4:
                            this._pc.addTrack(track, this.localMedia.stream);
                            _f.label = 5;
                        case 5:
                            _e++;
                            return [3 , 2];
                        case 6: return [3 , 8];
                        case 7:
                            if (sender) {
                                this._pc.removeTrack(sender);
                            }
                            _f.label = 8;
                        case 8:
                            _i++;
                            return [3 , 1];
                        case 9: 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 () {
            if (this.localDescription) {
                var medias = this.localDescription.sdp.media;
                for (var _i = 0, _a = this._discoveredCandidates; _i < _a.length; _i++) {
                    var candidate = _a[_i];
                    var media = medias[candidate.parts.sdpMLineIndex];
                    if (!media.candidates) {
                        media.candidates = [];
                    }
                    media.candidates.push(candidate.toParts());
                }
            }
        };
        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$a(this, void 0, void 0, function () {
                return __generator$a(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 __extends$8 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 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$8(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));

    var __awaiter$9 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$9 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var featurelog = Log$1.of("webrtc:phonesignal:feature");
    var audioContextInstance = null;
    var dtmfValidator = /^[0-9#\*abcdABCD]+$/;
    var 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]],
    ]);
    var DefaultOptions = new WebRTCMediaSignal();
    var SIGNAL_TEST_CALLID = "";
    var PhoneSignalManager =  (function () {
        function PhoneSignalManager(
        webrtcManager) {
            this.webrtcManager = webrtcManager;
            this.testerMediaSignal = null;
            this.log = Log$1.of("webrtc:phonesignal", webrtcManager.client);
            this.callMediaSignal = new CallMediaSignalPlayerStore(this);
            this.setConfig(webrtcManager.options.mediaSignal, true);
        }
        Object.defineProperty(PhoneSignalManager.prototype, "webrtc", {
            get: function () {
                return this.webrtcManager;
            },
            enumerable: false,
            configurable: true
        });
        PhoneSignalManager.prototype.getAudioContext = function () {
            if (audioContextInstance == null) {
                audioContextInstance = newAudioContext();
            }
            return audioContextInstance;
        };
        PhoneSignalManager.prototype.setConfig = function (options, resetDefault) {
            var 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")) {
                mediaSignal.audio = resetDefault ? Object.assign({}, DefaultOptions.audio) : this.signalOptions.audio;
                this.callMediaSignal.reloadConfig();
            }
            else {
                this.setAudioSignalConfig(options.audio, resetDefault);
            }
        };
        PhoneSignalManager.prototype.setAudioSignalConfig = function (options, resetDefault) {
            if (options) {
                for (var key in DefaultOptions.audio) {
                    if (options.hasOwnProperty(key)) {
                        this.signalOptions.audio[key] = Object.assign({}, resetDefault ? DefaultOptions.audio[key] : options[key] ? options[key] : DefaultOptions.audio[key]);
                        if (options[key] && options[key].hasOwnProperty("volume")) {
                            this.changeVolume(options[key].volume, key);
                        }
                    }
                }
            }
            this.callMediaSignal.reloadConfig();
            if (this.testerMediaSignal) {
                this.testerMediaSignal.stop(true);
                this.testerMediaSignal = null;
            }
        };
        PhoneSignalManager.prototype.getConfig = function () {
            return this.signalOptions;
        };
        PhoneSignalManager.prototype.getAudioSignalConfig = function () {
            return this.signalOptions.audio;
        };
        PhoneSignalManager.prototype.getCurrentPlay = function (callId) {
            return this.callMediaSignal.getCurrentPlay(callId);
        };
        PhoneSignalManager.prototype.playDTMF = function (callId, dtmf, duration, interToneGap) {
            return __awaiter$9(this, void 0, void 0, function () {
                var call;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            call = this.webrtcManager.retriveCall(callId);
                            if (!(call && call.toneSignalEnabled)) return [3 , 2];
                            return [4 , this.callMediaSignal.playDTMF(callId, dtmf, duration || this.signalOptions.dtmfDuration, interToneGap || this.signalOptions.dtmfInterToneGap)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 ];
                    }
                });
            });
        };
        PhoneSignalManager.prototype.play = function (callId, mediaSignal) {
            return __awaiter$9(this, void 0, void 0, function () {
                var call;
                return __generator$9(this, function (_a) {
                    if (this.callMediaSignal.getCurrentPlay(callId) != mediaSignal) {
                        call = this.webrtcManager.retriveCall(callId);
                        if (call && call.toneSignalEnabled) {
                            return [2 , this.callMediaSignal.play(callId, mediaSignal)];
                        }
                        else {
                            return [2 ];
                        }
                    }
                    else {
                        return [2 ];
                    }
                });
            });
        };
        PhoneSignalManager.prototype.stop = function (callId, force) {
            return __awaiter$9(this, void 0, void 0, function () {
                var call, ex_1;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.callMediaSignal.getCurrentPlay(callId)) return [3 , 4];
                            this.callMediaSignal.stop(callId, force);
                            this.callMediaSignal.delete(callId);
                            call = this.webrtcManager.retriveCall(callId);
                            if (!(call && call.toneSignalEnabled)) return [3 , 4];
                            if (call.signalingState == CallState.NEW_INBOUND || call.signalingState == CallState.CONNECTED) {
                                this.log.debug("stopSingleInstancePlayerIfNeedle - ".concat(MediaSignal.ring, " - ").concat(callId));
                                this.callMediaSignal.stopSingleInstancePlayerIfNeedle(MediaSignal.ring);
                                this.log.debug("stopSingleInstancePlayerIfNeedle - ".concat(MediaSignal.ringAdvertising, " - ").concat(callId));
                                this.callMediaSignal.stopSingleInstancePlayerIfNeedle(MediaSignal.ringAdvertising);
                            }
                            if (!(this.callMediaSignal.size() === 0)) return [3 , 4];
                            this.callMediaSignal.stopSingleInstancePlayerIfNeedle();
                            if (!audioContextInstance) return [3 , 4];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , audioContextInstance.close()];
                        case 2:
                            _a.sent();
                            audioContextInstance = null;
                            return [3 , 4];
                        case 3:
                            ex_1 = _a.sent();
                            this.log.error("Could not destroy AudioContext.", ex_1);
                            return [3 , 4];
                        case 4: return [2 ];
                    }
                });
            });
        };
        PhoneSignalManager.prototype.setSinkOutput = function (element, deviceId) {
            return __awaiter$9(this, void 0, void 0, function () {
                var e_1;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            return [4 , setSinkOutput(element, deviceId)];
                        case 1: return [2 , _a.sent()];
                        case 2:
                            e_1 = _a.sent();
                            if (e_1 instanceof DOMException) {
                                featurelog.error("setSinkOutput - no permission to use output device ".concat(deviceId), e_1);
                            }
                            else {
                                featurelog.debug("setSinkId is not supported, play to default output device");
                            }
                            return [2 , false];
                        case 3: return [2 ];
                    }
                });
            });
        };
        PhoneSignalManager.prototype.changeVolume = function (volume, mediaSignal, callId) {
            var conf = this.getConfig();
            var 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);
            }
        };
        PhoneSignalManager.prototype.getVolume = function (mediaSignal, configuration) {
            var volume = 100;
            var conf = this.getConfig();
            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;
        };
        PhoneSignalManager.prototype.playSignalTest = function (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);
        };
        PhoneSignalManager.prototype.stopSignalTest = function (mediaSignal) {
            if (this.testerMediaSignal) {
                if (mediaSignal) {
                    var player = this.testerMediaSignal.getMediaSignalPlayerTest(mediaSignal);
                    if (player) {
                        player.stop(true);
                    }
                }
                else {
                    this.testerMediaSignal.stop(true);
                }
            }
        };
        PhoneSignalManager.prototype.convertRingAdvertisingToRingIfNeedle = function () {
            this.callMediaSignal.convertRingAdvertisingToRingIfNeedle();
        };
        return PhoneSignalManager;
    }());
    var DtmfPlayer =  (function () {
        function DtmfPlayer(
        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);
        }
        DtmfPlayer.prototype.initDestination = function () {
            return __awaiter$9(this, void 0, void 0, function () {
                var outputDevice, audioContext;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            try {
                                outputDevice = this.instance.webrtc.device.audioOutput;
                            }
                            catch (e) { }
                            if (!(outputDevice && outputDevice.deviceId)) return [3 , 3];
                            if (!(supportedFeature.createMediaStreamDestination !== false && supportedFeature.setSinkId !== false && !this.mediaStreamDestination && !this.audioElement.srcObject)) return [3 , 2];
                            try {
                                audioContext = this.instance.getAudioContext();
                                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) return [3 , 2];
                            return [4 , this.instance.setSinkOutput(this.audioElement, outputDevice.deviceId)];
                        case 1:
                            if (_a.sent()) {
                                return [2 , true];
                            }
                            else {
                                this.mediaStreamDestination = null;
                                this.audioElement.srcObject = null;
                                return [2 , false];
                            }
                        case 2: return [3 , 4];
                        case 3:
                            this.mediaStreamDestination = null;
                            this.audioElement.srcObject = null;
                            _a.label = 4;
                        case 4: return [2 , true];
                    }
                });
            });
        };
        DtmfPlayer.prototype._createOscillator = function () {
            var audioContext = this.instance.getAudioContext();
            if (audioContext) {
                var gainNode = audioContext.createGain();
                var 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 null;
            }
        };
        DtmfPlayer.prototype.spoolDTMF = function () {
            return __awaiter$9(this, void 0, void 0, function () {
                var dtmfElement, dtmfTone, signalOptions;
                var _this = this;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.dtmfPlayerElement) return [3 , 6];
                            dtmfElement = this.dtmfPlayerElement;
                            dtmfTone = dtmfElement.dtmf.charAt(0).toUpperCase();
                            dtmfElement.stats = true;
                            dtmfElement.dtmf = dtmfElement.dtmf.substring(1);
                            if (!dtmfValidator.test(dtmfTone)) return [3 , 5];
                            signalOptions = this.instance.getConfig().audio.dtmf;
                            if (dtmfElement && signalOptions && signalOptions[dtmfTone] && signalOptions[dtmfTone].src && !dtmfElement.audioElement) {
                                dtmfElement.audioElement = new Audio();
                            }
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this.playDtmfTone(dtmfElement, dtmfTone)];
                        case 2:
                            _a.sent();
                            return [3 , 4];
                        case 3:
                            _a.sent();
                            return [3 , 4];
                        case 4:
                            setTimeout(function () { return __awaiter$9(_this, void 0, void 0, function () {
                                return __generator$9(this, function (_a) {
                                    this.spoolDTMF();
                                    return [2 ];
                                });
                            }); }, this.interToneGap);
                            return [3 , 6];
                        case 5:
                            if (dtmfElement.dtmf.length) {
                                this.spoolDTMF();
                            }
                            else {
                                this.dtmfPlayerElement = null;
                                this.playerNotifier.complete();
                            }
                            _a.label = 6;
                        case 6: return [2 ];
                    }
                });
            });
        };
        DtmfPlayer.prototype.playDtmfTone = function (dtmfElement, dtmfTone) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                try {
                    _this.playerNotifier.next(dtmfTone);
                    var signalOptions = _this.instance.getConfig().audio.dtmf;
                    if (dtmfElement.audioElement && signalOptions && signalOptions[dtmfTone] && signalOptions[dtmfTone].src) {
                        fromEvent(dtmfElement.audioElement, "ended")
                            .pipe(timeout(_this.duration), take(1), catchError(function (err) { return of(true); }),
                        switchMap(function () { return dtmfElement.audioElementPlay; }), catchError(function (e) {
                            _this.log.error("Error on play dtmf from src", e);
                            return of(false);
                        }))
                            .subscribe(function () {
                            dtmfElement.audioElement.pause();
                            dtmfElement.audioElement.currentTime = 0;
                        });
                        dtmfElement.audioElement.src = signalOptions[dtmfTone].src;
                        dtmfElement.audioElement.loop = true;
                        dtmfElement.audioElementPlay = dtmfElement.audioElement.play();
                    }
                    else {
                        var 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(function () { return __awaiter$9(_this, void 0, void 0, function () {
                                var e_2;
                                return __generator$9(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            _a.trys.push([0, 2, , 3]);
                                            return [4 , this.audioElementPlay];
                                        case 1:
                                            _a.sent();
                                            if (dtmfElement.oscillator1) {
                                                dtmfElement.oscillator1.stop();
                                                dtmfElement.oscillator1.disconnect();
                                            }
                                            if (dtmfElement.oscillator2) {
                                                dtmfElement.oscillator2.stop();
                                                dtmfElement.oscillator2.disconnect();
                                            }
                                            dtmfElement.oscillator1 = null;
                                            dtmfElement.oscillator2 = null;
                                            this.audioElement.pause();
                                            this.audioElement.currentTime = 0;
                                            resolve(true);
                                            return [3 , 3];
                                        case 2:
                                            e_2 = _a.sent();
                                            this.log.error("Error on play dtmf", e_2);
                                            return [3 , 3];
                                        case 3: return [2 ];
                                    }
                                });
                            }); }, _this.duration);
                        }
                        else {
                            reject("Invalid DTMF \"".concat(dtmfTone, "\""));
                        }
                    }
                }
                catch (e) {
                    reject(e);
                }
            });
        };
        DtmfPlayer.prototype.destroy = function () {
            this.mediaStreamDestination = null;
            this.audioElement.srcObject = null;
        };
        DtmfPlayer.prototype.playDTMF = function (dtmf) {
            if (typeof dtmf === "string" && this.instance.getConfig().audioenabled && dtmf) {
                var dtmfElement = this.dtmfPlayerElement;
                if (dtmfElement) {
                    dtmfElement.dtmf += dtmf;
                }
                else {
                    dtmfElement = {
                        audioElement: null,
                        audioElementPlay: null,
                        oscillator1: null,
                        oscillator2: null,
                        stats: false,
                        dtmf: dtmf,
                    };
                    this.dtmfPlayerElement = dtmfElement;
                }
                if (!dtmfElement.stats) {
                    this.spoolDTMF();
                }
            }
            else {
                this.playerNotifier.complete();
            }
            return this.playerNotifier.asObservable();
        };
        return DtmfPlayer;
    }());
    var MediaSignalPlayer =  (function () {
        function MediaSignalPlayer(signal,
        phoneSignalManager) {
            var _this = this;
            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(function () { return _this.stopAudioElement(); }));
            this.log = Log$1.of("webrtc:phonesignal", phoneSignalManager.webrtc.client);
            var signalOptions = phoneSignalManager.getConfig();
            this.signal = signal;
            this.conf = signalOptions.audio && signalOptions.audio[signal] ? signalOptions.audio[signal] : undefined;
            this.phoneSignalAudioElement.autoplay = true;
            this.phoneSignalAudioElement.loop = true;
            this.changeVolume(phoneSignalManager.getVolume(signal, this.conf));
        }
        MediaSignalPlayer.prototype.stopAudioElement = function () {
            return __awaiter$9(this, void 0, void 0, function () {
                var e_3;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.phoneSignalAudioElementPlay) return [3 , 5];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this.phoneSignalAudioElementPlay];
                        case 2:
                            _a.sent();
                            return [3 , 4];
                        case 3:
                            e_3 = _a.sent();
                            this.log.error("Error on play", e_3);
                            return [3 , 4];
                        case 4:
                            this.phoneSignalAudioElement.pause();
                            this.phoneSignalAudioElement.currentTime = 0;
                            _a.label = 5;
                        case 5: return [2 ];
                    }
                });
            });
        };
        MediaSignalPlayer.prototype.setOutputDevice = function (outputDevice) {
            return this.phoneSignalManager.setSinkOutput(this.phoneSignalAudioElement, outputDevice && outputDevice.deviceId ? outputDevice.deviceId : undefined);
        };
        MediaSignalPlayer.prototype.setConfiguration = function (conf) {
            this.conf = conf;
        };
        MediaSignalPlayer.prototype.getSignal = function () {
            return this.signal;
        };
        MediaSignalPlayer.prototype.changeVolume = function (volume) {
            this.phoneSignalAudioElement.volume = volume >= 0 && volume <= 100 ? volume / 100 : 1;
        };
        MediaSignalPlayer.prototype.getVolume = function () {
            return this.phoneSignalAudioElement.volume * 100;
        };
        MediaSignalPlayer.prototype.stop = function (immediate) {
            if (this.playInProgress) {
                this.log.debug("MediaSignalPlayer - stop - ".concat(this.signal));
                this.playInProgress = false;
                if (immediate) {
                    this.stopAudioElement();
                }
            }
            this.phoneSignalEndedSubscription.unsubscribe();
        };
        MediaSignalPlayer.prototype.playInternal = function () {
            try {
                if (isGestureRequiredForPlay()) {
                    this.phoneSignalAudioElementPlay = Promise.reject("Unable to play, user gesture on page is required");
                    this.log.error("Unable to play, user gesture on page is required");
                }
                else {
                    this.phoneSignalAudioElementPlay = Promise.resolve(this.phoneSignalAudioElement.play());
                }
            }
            catch (e) {
                this.log.error("Error on playInternal", e);
            }
        };
        MediaSignalPlayer.prototype.play = function (ignoreLoop, resolveOnSignalEnd) {
            var _this = this;
            this.log.debug("MediaSignalPlayer - play - ".concat(this.signal));
            if (!this.playInProgress) {
                var audio = this.conf;
                if (audio && audio.src) {
                    var loop_1 = !!audio.loop;
                    this.phoneSignalAudioElement.src = audio.src;
                    this.phoneSignalAudioElement.loop = loop_1;
                    if (loop_1 && audio.interval) {
                        this.phoneSignalAudioElement.loop = false;
                        this.phoneSignalEndedSubscription = this.phoneSignalEndedObservable
                            .pipe(delay(audio.interval), filter(function () { return _this.playInProgress; }))
                            .subscribe(function () {
                            _this.playInternal();
                        });
                    }
                    else {
                        this.phoneSignalEndedSubscription = new Subscription(function () {
                            if (loop_1) {
                                _this.phoneSignalAudioElement.loop = false;
                                switch (_this.signal) {
                                    case MediaSignal.ringback:
                                    case MediaSignal.ring:
                                        _this.stopAudioElement();
                                        break;
                                    default:
                                        _this.phoneSignalEndedObservable.pipe(first()).subscribe(function () { return _this.stopAudioElement(); });
                                        break;
                                }
                            }
                            else {
                                _this.stopAudioElement();
                            }
                        });
                    }
                    if (audio.maxlength) {
                        var phoneSignalTimer_1 = setTimeout(function () {
                            phoneSignalTimer_1 = null;
                            _this.stop(true);
                        }, audio.maxlength);
                        this.phoneSignalEndedSubscription.add(function () {
                            if (phoneSignalTimer_1) {
                                clearTimeout(phoneSignalTimer_1);
                                phoneSignalTimer_1 = null;
                            }
                        });
                    }
                    if (ignoreLoop) {
                        this.phoneSignalEndedObservable.pipe(first()).subscribe(function () { return _this.stop(true); });
                    }
                    this.playInternal();
                }
                this.playInProgress = true;
            }
            return resolveOnSignalEnd
                ? new Promise(function (resolve) {
                    _this.phoneSignalEndedSubscription.add(resolve);
                })
                : Promise.resolve();
        };
        return MediaSignalPlayer;
    }());
    var CallMediaSignalPlayer =  (function () {
        function CallMediaSignalPlayer(
        log,
        callId,
        phoneSignal,
        singleInstancePlayer) {
            this.log = log;
            this.callId = callId;
            this.phoneSignal = phoneSignal;
            this.singleInstancePlayer = singleInstancePlayer;
            this.dtmfPlayer = [];
            this.signalPlayed = new Map();
            this.currentPlay = null;
            this.isTestPlayer = callId === SIGNAL_TEST_CALLID;
        }
        Object.defineProperty(CallMediaSignalPlayer.prototype, "canPlay", {
            get: function () {
                var _a;
                return this.isTestPlayer || !!((_a = this.phoneSignal.webrtc.retriveCall(this.callId)) === null || _a === void 0 ? void 0 : _a.mediaOwnedByCurrentInstance);
            },
            enumerable: false,
            configurable: true
        });
        CallMediaSignalPlayer.prototype.getOutputDeviceBySignal = function (signal) {
            return signal === MediaSignal.ring ? this.phoneSignal.webrtc.device.audioSignalOutput : this.phoneSignal.webrtc.device.audioOutput;
        };
        CallMediaSignalPlayer.prototype.buildPhoneSignal = function (signal, conf, device) {
            return __awaiter$9(this, void 0, void 0, function () {
                var signalPlayer;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            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.setConfiguration(conf);
                                signalPlayer.changeVolume(this.phoneSignal.getVolume(signal, conf));
                            }
                            return [4 , signalPlayer.setOutputDevice(device ? device : this.getOutputDeviceBySignal(signal))];
                        case 1:
                            _a.sent();
                            return [2 , signalPlayer];
                    }
                });
            });
        };
        CallMediaSignalPlayer.prototype.changeVolume = function (volume, mediaSignal) {
            this.signalPlayed.forEach(function (signalPlayer) {
                if (!mediaSignal || signalPlayer.getSignal() == mediaSignal) {
                    signalPlayer.changeVolume(volume);
                }
            });
        };
        CallMediaSignalPlayer.prototype.getCurrentPlay = function () {
            return this.currentPlay;
        };
        CallMediaSignalPlayer.prototype.getMediaSignalPlayer = function (type) {
            var player = this.singleInstancePlayer.get(type);
            return player ? player : this.signalPlayed.get(type);
        };
        CallMediaSignalPlayer.prototype.getMediaSignalPlayerTest = function (type) {
            return this.signalPlayed.get(type);
        };
        CallMediaSignalPlayer.prototype.stop = function (immediate) {
            this.log.debug("CallMediaSignalPlayer - request stop - immediate: ".concat(immediate));
            this.currentPlay = null;
            if (this.signalPlayed.size) {
                this.signalPlayed.forEach(function (signalPlayer) {
                    signalPlayer.stop(immediate);
                });
                this.signalPlayed.clear();
            }
            if (this.dtmfPlayer && this.dtmfPlayer.length) {
                this.dtmfPlayer.forEach(function (dtmfPlayer) {
                    dtmfPlayer.destroy();
                });
                this.dtmfPlayer = [];
            }
        };
        CallMediaSignalPlayer.prototype.playDTMF = function (dtmf, duration, interToneGap) {
            return __awaiter$9(this, void 0, void 0, function () {
                var dtmfPlayer_1;
                var _this = this;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canPlay) return [3 , 2];
                            dtmfPlayer_1 = new DtmfPlayer(this.phoneSignal, duration, interToneGap);
                            this.dtmfPlayer.push(dtmfPlayer_1);
                            return [4 , dtmfPlayer_1.initDestination()];
                        case 1:
                            _a.sent();
                            dtmfPlayer_1
                                .playDTMF(dtmf)
                                .pipe(finalize(function () {
                                dtmfPlayer_1.destroy();
                                var indexOfPlayer = _this.dtmfPlayer.indexOf(dtmfPlayer_1);
                                if (indexOfPlayer > -1) {
                                    _this.dtmfPlayer.splice(indexOfPlayer, 1);
                                }
                            }))
                                .subscribe();
                            _a.label = 2;
                        case 2: return [2 , true];
                    }
                });
            });
        };
        CallMediaSignalPlayer.prototype.play = function (type, conf, ignoreLoop, device, resolveOnSignalEnd) {
            return __awaiter$9(this, void 0, void 0, function () {
                var phoneSignalPlayer;
                return __generator$9(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.log.debug("CallMediaSignalPlayer - request play - ".concat(type));
                            this.currentPlay = type;
                            return [4 , this.buildPhoneSignal(type, conf, device)];
                        case 1:
                            phoneSignalPlayer = _a.sent();
                            if (this.currentPlay === type) {
                                if (type === MediaSignal.ring || this.canPlay) {
                                    return [2 , phoneSignalPlayer.play(ignoreLoop, !!resolveOnSignalEnd)];
                                }
                                else {
                                    return [2 ];
                                }
                            }
                            else {
                                this.log.debug("CallMediaSignalPlayer - block play ".concat(type, " - current play '").concat(this.currentPlay, "' is different from '").concat(type, "'"));
                            }
                            return [2 ];
                    }
                });
            });
        };
        return CallMediaSignalPlayer;
    }());
    var CallMediaSignalPlayerStore =  (function () {
        function CallMediaSignalPlayerStore(
        instance) {
            this.instance = instance;
            this.log = Log$1.of("webrtc:phonesignal", instance.webrtc.client);
            this.currentPhoneSignal = new Map();
            this.singleInstancePlayer = new Map();
        }
        CallMediaSignalPlayerStore.prototype.reloadConfig = function () {
            var signalOptions = this.instance.getConfig();
            if (signalOptions) {
                this.stopSingleInstancePlayerIfNeedle();
                this.singleInstancePlayer.set(MediaSignal.ring, new MediaSignalPlayer(MediaSignal.ring, this.instance));
                this.singleInstancePlayer.set(MediaSignal.ringAdvertising, new MediaSignalPlayer(MediaSignal.ringAdvertising, this.instance));
            }
        };
        CallMediaSignalPlayerStore.prototype.createNewIfNotSet = function (callId) {
            var phoneSignalPlayer = this.currentPhoneSignal.get(callId);
            if (!phoneSignalPlayer) {
                phoneSignalPlayer = new CallMediaSignalPlayer(this.log, callId, this.instance, this.singleInstancePlayer);
                this.currentPhoneSignal.set(callId, phoneSignalPlayer);
            }
            return phoneSignalPlayer;
        };
        CallMediaSignalPlayerStore.prototype.get = function (callId) {
            return this.createNewIfNotSet(callId);
        };
        CallMediaSignalPlayerStore.prototype.getCurrentPlay = function (callId) {
            var phoneSignalPlayer = this.currentPhoneSignal.get(callId);
            return phoneSignalPlayer ? phoneSignalPlayer.getCurrentPlay() : null;
        };
        CallMediaSignalPlayerStore.prototype.playDTMF = function (callId, dtmf, duration, interToneGap) {
            this.log.info("callid: ".concat(callId, " - playDTMF: ").concat(dtmf));
            return this.get(callId).playDTMF(dtmf, duration, interToneGap);
        };
        CallMediaSignalPlayerStore.prototype.play = function (callId, type) {
            this.log.info("callid: ".concat(callId, " - play: ").concat(type));
            return this.get(callId).play(type, null, false, null, false);
        };
        CallMediaSignalPlayerStore.prototype.stop = function (callId, immediate) {
            this.log.info("callid: ".concat(callId, " - stop all"));
            this.get(callId).stop(immediate);
        };
        CallMediaSignalPlayerStore.prototype.delete = function (callId) {
            this.get(callId).stop(true);
            this.currentPhoneSignal.delete(callId);
        };
        CallMediaSignalPlayerStore.prototype.keys = function () {
            return this.currentPhoneSignal.keys();
        };
        CallMediaSignalPlayerStore.prototype.size = function () {
            return this.currentPhoneSignal.size;
        };
        CallMediaSignalPlayerStore.prototype.changeVolume = function (volume, mediaSignal, callId) {
            this.currentPhoneSignal.forEach(function (signalPlayed, idcall) {
                if (!callId || idcall === callId) {
                    signalPlayed.changeVolume(volume, mediaSignal);
                }
            });
            this.singleInstancePlayer.forEach(function (signalPlayer) {
                if (!mediaSignal || signalPlayer.getSignal() == mediaSignal) {
                    signalPlayer.changeVolume(volume);
                }
            });
        };
        CallMediaSignalPlayerStore.prototype.stopSingleInstancePlayerIfNeedle = function (signal) {
            var _a;
            if (signal) {
                if (this.singleInstancePlayer.has(signal)) {
                    var otherCallSameSignal_1 = 0;
                    this.currentPhoneSignal.forEach(function (callPhoneSignalPlayer) {
                        var currentPlay = callPhoneSignalPlayer.getCurrentPlay();
                        if (currentPlay && currentPlay == signal) {
                            otherCallSameSignal_1++;
                        }
                    });
                    if (otherCallSameSignal_1 === 0) {
                        this.log.debug("stopSingleInstancePlayerIfNeedle - no other call is play ".concat(signal, ", stop now"));
                        (_a = this.singleInstancePlayer.get(signal)) === null || _a === void 0 ? void 0 : _a.stop(false);
                    }
                    else {
                        this.log.debug("stopSingleInstancePlayerIfNeedle - other call is play ".concat(signal, ", so can't stop now"));
                    }
                }
            }
            else {
                this.singleInstancePlayer.forEach(function (signalPlayer) {
                    signalPlayer.stop(false);
                });
            }
        };
        CallMediaSignalPlayerStore.prototype.convertRingAdvertisingToRingIfNeedle = function () {
            if (this.currentPhoneSignal.size) {
                var ringadv_1 = [];
                this.currentPhoneSignal.forEach(function (phoneSignal, callId) {
                    if (phoneSignal.getCurrentPlay() === "ringAdvertising") {
                        ringadv_1.push({ callId: callId });
                    }
                });
                var doConvert = ringadv_1.length === this.currentPhoneSignal.size;
                this.log.debug("convertRingAdvertisingToRingIfNeedle - ".concat(doConvert ? "".concat(ringadv_1[0], " convert to ring") : "No need to convert", " - PhoneSignal: ").concat(this.currentPhoneSignal.size, ", ringAdvertising: ").concat(ringadv_1.length));
                if (doConvert) {
                    this.stop(ringadv_1[0].callId, true);
                    this.play(ringadv_1[0].callId, MediaSignal.ring);
                }
            }
            else {
                this.log.debug("convertRingAdvertisingToRingIfNeedle - PhoneSignal: 0");
            }
        };
        return CallMediaSignalPlayerStore;
    }());

    var __spreadArray$2 = (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$2(__spreadArray$2([], 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 __assign$3 = (undefined && undefined.__assign) || function () {
        __assign$3 = Object.assign || function(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$3.apply(this, arguments);
    };
    var browser = detect();
    var isChomeMajorThan72 = browser && browser.name === "chrome" && parseInt((browser.version || "72.0").split(".")[0]) > 72;
    function phoneCallCanSwitchToVideoCall() {
        return (browser && browser.name !== "chrome") || !isChomeMajorThan72;
    }
    function buildWebrtcControlMessageFromChannelEvent(channelEvent, fromServer, override) {
        return __assign$3(__assign$3({ _isFromServer: fromServer, _channelType: channelEvent.channel, _realChannelType: channelEvent.channel }, (override !== null && override !== void 0 ? override : {})), channelEvent.callInfo);
    }
    function buildCallInfoFromWebrtcControlMessage(webrtcControlMessage) {
        var _a;
        var 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;
        var 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) {
                        var 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:
                            var call = webrtcManager.retriveCall((_a = callInfo.callId) !== null && _a !== void 0 ? _a : "");
                            if (call) {
                                if (!callInfo.remote_media_status) {
                                    callInfo.remote_media_status = {};
                                    var remoteAudioStatus = call.remoteMedia.audioLinkStatus;
                                    if (remoteAudioStatus) {
                                        callInfo.remote_media_status.audio = [remoteAudioStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE];
                                    }
                                    var 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 = [];
                                    var status_1 = (_b = call.localMedia) === null || _b === void 0 ? void 0 : _b.audioLinkStatus;
                                    if (status_1) {
                                        callInfo.media_feature.local.audio.push(status_1 === 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 = [];
                                    var status_2 = (_c = call.localMedia) === null || _c === void 0 ? void 0 : _c.videoLinkStatus;
                                    if (status_2) {
                                        callInfo.media_feature.local.video.push(status_2 === 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) {
                    var 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 = {}));

    var __extends$7 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$8 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$8 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var WebapiClientMethods =  (function (_super) {
        __extends$7(WebapiClientMethods, _super);
        function WebapiClientMethods(
        client,
        channelNotification,
        commandNotification,
        disconnectOtherSocket,
        loginRequest,
        remeberMe,
        exitAfterLogout) {
            var _this = _super.call(this, client) || this;
            _this.disconnectOtherSocket = disconnectOtherSocket;
            _this.loginRequest = loginRequest;
            _this.remeberMe = remeberMe;
            _this.exitAfterLogout = exitAfterLogout;
            _this.callInfoNotification = new NotificationManager(client, "callInfo", function () { return _this.requestObservableUpdate("startCallNotify", []).response; }, channelNotification, function (callInfo) {
                return { channel: channelIdToChannelType(callInfo.channelid), callInfo: callInfo };
            });
            _this.commandNotification = new NotificationManager(client, "clientCommand", function () { return _this.requestObservableUpdate("startClientCommandNotify", []).response; }, commandNotification, function (clientCommand) { return clientCommand; });
            return _this;
        }
        WebapiClientMethods.prototype.refreshToken = function (username, accessToken) {
            return this.requestPromise("refreshToken", [username, accessToken]).toPromise();
        };
        WebapiClientMethods.prototype.resumeChatToken = function () {
            return this.requestPromise("resumeChatToken", []).toPromise();
        };
        WebapiClientMethods.prototype.getRefreshToken = function () {
            return this.requestPromise("getRefreshToken", []).toPromise();
        };
        WebapiClientMethods.prototype.searchUsers = function (name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive) {
            return this.requestChunkedUpdate("searchUsers", [name, number, company, customFields, addressbookType, site, categories, pageNumber, pageSize, exclusive]).toLiveResult();
        };
        WebapiClientMethods.prototype.searchUsersExtended = function (addressbookType, fields, exclusive, pageNumber, pageSize, requestTimeout) {
            return this.requestChunkedUpdate("searchUsersExtended", [addressbookType, fields, exclusive, pageNumber, pageSize], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.searchUsersExtendedByBackend = function (addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize, requestTimeout) {
            return this.requestChunkedUpdate("searchUsersExtendedByBackend", [addressbookType, fields, exclusive, backendsConfigName, pageNumber, pageSize], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.getListOfCompany = function (name, backend, pageNumber, pageSize) {
            return this.requestChunked("getListOfCompany", [name, backend, pageNumber, pageSize]);
        };
        WebapiClientMethods.prototype.exportAddressBook = function (addressBookConfigName, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 3600000; }
            return this.requestPromise("exportAddressBook", [addressBookConfigName], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.importAddressBook = function (fileName, addressBookConfigName, doClean, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 300000; }
            return this.requestPromise("importAddressBook", [fileName, addressBookConfigName, doClean], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.monitorImportAddressBook = function () {
            return this.requestPromiseUpdate("monitorImportAddressBook", []).response;
        };
        WebapiClientMethods.prototype.getAllCategories = function (addressbookType) {
            return this.requestPromiseUpdate("getAllCategories", [addressbookType]).response;
        };
        WebapiClientMethods.prototype.getUserSites = function () {
            return this.requestPromise("getUserSites", []).toPromise();
        };
        WebapiClientMethods.prototype.getUnreadChat = function () {
            return this.requestChunked("getUnreadChat", []);
        };
        WebapiClientMethods.prototype.isValidSession = function () {
            return this.requestPromise("isValidSession", []).toPromise();
        };
        WebapiClientMethods.prototype.logout = function (reason, note) {
            if (reason === void 0) { reason = null; }
            if (note === void 0) { note = null; }
            return this.requestPromise("logout", [reason, note]).toPromise();
        };
        WebapiClientMethods.prototype.logoutAndExit = function (reason, note) {
            return this.exitAfterLogout(this.logout(reason, note));
        };
        WebapiClientMethods.prototype.isGrantedAccess = function () {
            return this.requestPromise("isGrantedAccess", []).toPromise();
        };
        WebapiClientMethods.prototype.getMaxPageSize = function () {
            return this.requestPromise("getMaxPageSize", []).toPromise();
        };
        WebapiClientMethods.prototype.getSessionProfile = function () {
            return this.requestPromise("getSessionProfile", []).toPromise();
        };
        WebapiClientMethods.prototype.loginForce = function () {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    this.disconnectOtherSocket();
                    return [2 , this.loadTransport()];
                });
            });
        };
        WebapiClientMethods.prototype.loginCustom = function (customData, rememberMe, timeout) {
            return __awaiter$8(this, void 0, void 0, function () {
                var _this = this;
                return __generator$8(this, function (_a) {
                    this.remeberMe(rememberMe);
                    return [2 , this.loginRequest(timeout, LoginType.Custom, customData)
                            .pipe(tap(function (loginResult) {
                            if (loginResult.sessionId) {
                                try {
                                    _this.loadTransport();
                                }
                                catch (error) {
                                    _this.transport.emitError(error, false);
                                }
                            }
                        }))
                            .toPromise()];
                });
            });
        };
        WebapiClientMethods.prototype.loginByAccessToken = function (accessToken, rememberMe, timeout) {
            return __awaiter$8(this, void 0, void 0, function () {
                var _this = this;
                return __generator$8(this, function (_a) {
                    this.remeberMe(rememberMe !== null && rememberMe !== void 0 ? rememberMe : false);
                    return [2 , this.loginRequest(timeout, LoginType.AccessToken, accessToken)
                            .pipe(tap(function (loginResult) {
                            if (loginResult.sessionId) {
                                try {
                                    _this.loadTransport();
                                }
                                catch (error) {
                                    _this.transport.emitError(error, false);
                                }
                            }
                        }))
                            .toPromise()];
                });
            });
        };
        WebapiClientMethods.prototype.login = function (username, password, rememberMe, timeout) {
            return __awaiter$8(this, void 0, void 0, function () {
                var _this = this;
                return __generator$8(this, function (_a) {
                    this.remeberMe(rememberMe);
                    return [2 , this.loginRequest(timeout, LoginType.Credential, username, password)
                            .pipe(tap(function (loginResult) {
                            if (loginResult.sessionId) {
                                try {
                                    _this.loadTransport();
                                }
                                catch (error) {
                                    _this.transport.emitError(error, false);
                                }
                            }
                        }))
                            .toPromise()];
                });
            });
        };
        WebapiClientMethods.prototype.getVersion = function () {
            return this.requestPromise("getVersion", []).toPromise();
        };
        WebapiClientMethods.prototype.uploadFile = function (file) {
            return this.requestPromise("uploadFile", [file]).toPromise();
        };
        WebapiClientMethods.prototype.getUploadFile = function (fileName, withBody) {
            return this.requestPromise("getUploadFile", [fileName, withBody]).toPromise();
        };
        WebapiClientMethods.prototype.removeUploadFile = function (fileName) {
            return this.requestPromise("removeUploadFile", [fileName]).toPromise();
        };
        WebapiClientMethods.prototype.chunkedRequest = function (chunk) {
            return this.requestPromise("chunkedRequest", [chunk]).toPromise();
        };
        WebapiClientMethods.prototype.resetChunkedRequest = function (requestId) {
            return this.requestPromise("resetChunkedRequest", [requestId]).toPromise();
        };
        WebapiClientMethods.prototype.runChunkedRequest = function (requestId, fileName) {
            return this.requestPromise("runChunkedRequestFile", [requestId, fileName]).toPromise();
        };
        WebapiClientMethods.prototype.getUserDetail = function (timeout) {
            return this.requestPromiseUpdate("getUserDetail", [], { priorityOnRestart: 1000, requestTimeout: timeout ? timeout : this.transport.getRequestTimeout() < 30000 ? 30000 : null }).response;
        };
        WebapiClientMethods.prototype.useProfile = function (id, type, device, force, reason, note, requestTimeout) {
            if (force === void 0) { force = false; }
            if (reason === void 0) { reason = null; }
            if (note === void 0) { note = null; }
            if (requestTimeout === void 0) { requestTimeout = 30000; }
            return this.requestPromiseUpdate("useProfile", [id, type, device, force, reason, note], { requestTimeout: requestTimeout }).response;
        };
        WebapiClientMethods.prototype.useDevice = function (type, exten, force) {
            return this.requestPromise("useDevice", [type, exten, force]).toPromise();
        };
        WebapiClientMethods.prototype.startConference = function () {
            return this.requestPromise("startConference", []).toPromise();
        };
        WebapiClientMethods.prototype.getCurrentCalls = function () {
            return this.requestPromise("getCurrentCalls", []).toPromise();
        };
        WebapiClientMethods.prototype.startCallNotify = function () {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    return [2 , this.callInfoNotification.start()];
                });
            });
        };
        WebapiClientMethods.prototype.isInternalNumber = function (number) {
            return this.requestPromise("isInternalNumber", [number]).toPromise();
        };
        WebapiClientMethods.prototype.getAllServiceCode = function () {
            return this.requestPromise("getAllServiceCode", []).toPromise();
        };
        WebapiClientMethods.prototype.stopCallNotify = function () {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    return [2 , this.callInfoNotification.stop()];
                });
            });
        };
        WebapiClientMethods.prototype.startVideoEchoTest = function (audio, video, videoContainer, mediaConfiguration) {
            return this.client.webrtc.methods.startVideoEchoTest(audio, video, videoContainer, mediaConfiguration).toPromise();
        };
        WebapiClientMethods.prototype.dial = function (dialParam, videoContainer, mediaConfiguration, userInteractionAction) {
            var _a;
            return __awaiter$8(this, void 0, void 0, function () {
                var dialParams, result;
                return __generator$8(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            dialParams = new DialParams(dialParam);
                            result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.dial(dialParams, videoContainer, mediaConfiguration, userInteractionAction);
                            if (!result) return [3 , 1];
                            return [2 , result.toPromise()];
                        case 1: return [4 , this.requestPromise("dial", dialParams.toRequestParams(this.client.phoneManagerActive)).toPromise()];
                        case 2:
                            if (_b.sent()) {
                                return [2 , "true"];
                            }
                            else {
                                return [2 , null];
                            }
                        case 3: return [2 ];
                    }
                });
            });
        };
        WebapiClientMethods.prototype.getUserContactStatus = function (username) {
            return this.requestPromiseUpdate("getUserContactStatus", [username]).response;
        };
        WebapiClientMethods.prototype.getAddressBookContact = function (uid, type) {
            return this.requestPromise("getAddressBookContact", [uid, type]).toPromise();
        };
        WebapiClientMethods.prototype.getAddressBookContactByUuid = function (uid) {
            return this.requestPromise("getAddressBookContactByUuid", [uid]).toPromise();
        };
        WebapiClientMethods.prototype.inboundCallExtension = function (type, device, enable, force) {
            return this.requestPromise("inboundCallExtension", [type, device, enable, force]).toPromise();
        };
        WebapiClientMethods.prototype.answerOnChannel = function (channelType, callId, media, videoContainer, mediaConfiguration) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.answer(channelType, callId, media, videoContainer, mediaConfiguration);
            return result ? result.toPromise() : this.requestPromise("answer", [callId, null]).toPromise();
        };
        WebapiClientMethods.prototype.cancel = function (callId) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.cancel(callId, true, true);
            return result ? result.toPromise() : this.requestPromise("cancel", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.hold = function (callId) {
            var _a;
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 , ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.hold(callId))];
                        case 1:
                            _b.sent();
                            return [2 , this.requestPromise("hold", [callId]).toPromise()];
                    }
                });
            });
        };
        WebapiClientMethods.prototype.unhold = function (callId) {
            var _a;
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 , ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.unhold(callId))];
                        case 1:
                            _b.sent();
                            return [2 , this.requestPromise("unhold", [callId]).toPromise()];
                    }
                });
            });
        };
        WebapiClientMethods.prototype.attendedTransfer = function (callId, heldCallId, media, fields) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.attendedTransfer(callId, heldCallId, media, fields);
            return result ? result.toPromise() : this.requestPromise("attendedTransfer", [callId, heldCallId, ["audio"], fields]).toPromise();
        };
        WebapiClientMethods.prototype.blindTransfer = function (callId, accessCode, number, data) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.blindTransfer(callId, accessCode, number, data);
            return result ? result.toPromise() : this.requestPromise("blindTransfer", [callId, accessCode, number, data]).toPromise();
        };
        WebapiClientMethods.prototype.blindTransferMultiChannelToUser = function (callId, username, channelId) {
            return this.requestPromise("blindTransferMultiChannelToUser", [callId, username, channelId]).toPromise();
        };
        WebapiClientMethods.prototype.setCallData = function (callId, data) {
            return this.requestPromise("setCallData", [callId, data]).toPromise();
        };
        WebapiClientMethods.prototype.sendDTMF = function (callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap) {
            var _a;
            dtmf = (dtmf || "").split("").reduce(function (d1, d2) { return (dtmfValidator.test(d2) ? d1 + d2 : d1); }, "");
            if (dtmf) {
                var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.sendDTMF(callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap);
                return result ? result.toPromise() : this.requestPromise("sendDTMF", [callId, dtmf]).toPromise();
            }
            else {
                return Promise.reject("Invalid DTMF");
            }
        };
        WebapiClientMethods.prototype.stopRecord = function (callId) {
            return this.requestPromise("stopRecord", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.startRecord = function (callId) {
            return this.requestPromise("startRecord", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.updateCallRecordingNote = function (tableName, id, note, additionalData) {
            return this.requestPromise("updateCallRecordingNote", [tableName, id, note, additionalData]).toPromise();
        };
        WebapiClientMethods.prototype.chanSpyUser = function (fromDeviceType, fromDevice, usernameToSpy, whisper, beep) {
            return this.requestPromise("chanSpyUser", [fromDeviceType, fromDevice, usernameToSpy, whisper, beep]).toPromise();
        };
        WebapiClientMethods.prototype.getFavouriteContacts = function (requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 30000; }
            return this.requestChunkedUpdate("getFavouriteContacts", [], { requestTimeout: requestTimeout }).response;
        };
        WebapiClientMethods.prototype.addFavouriteItemGroup = function (name, position) {
            return this.requestPromise("addFavouriteItemGroup", [name, position]).toPromise();
        };
        WebapiClientMethods.prototype.setFavouriteItemGroup = function (id, name, expanded, position) {
            return this.requestPromise("setFavouriteItemGroup", [id, name, expanded, position]).toPromise();
        };
        WebapiClientMethods.prototype.setFavouriteItemGroups = function (groups) {
            return this.requestPromise("setFavouriteItemGroups", [groups]).toPromise();
        };
        WebapiClientMethods.prototype.delFavouriteItemGroup = function (id) {
            return this.requestPromise("delFavouriteItemGroup", [id]).toPromise();
        };
        WebapiClientMethods.prototype.setFavouriteItemContact = function (uid, type, groupId, position) {
            return this.requestPromise("setFavouriteItemContact", [uid, type, groupId, position]).toPromise();
        };
        WebapiClientMethods.prototype.addFavouriteItemContact = function (uid, type, groupId, position) {
            return this.requestPromise("addFavouriteItemContact", [uid, type, groupId, position]).toPromise();
        };
        WebapiClientMethods.prototype.delFavouriteItemContactFromGroup = function (uid, type, groupId) {
            return this.requestPromise("delFavouriteItemContactFromGroup", [uid, type, groupId]).toPromise();
        };
        WebapiClientMethods.prototype.getFavouriteUserGroups = function () {
            return this.requestChunked("getFavouriteUserGroups", []);
        };
        WebapiClientMethods.prototype.delFavouriteItemContactFromGroups = function (uid, type, groupIds) {
            return this.requestPromise("delFavouriteItemContactFromGroups", [uid, type, groupIds]).toPromise();
        };
        WebapiClientMethods.prototype.addFavouriteItemContactToGroups = function (uid, type, groupIds) {
            return this.requestPromise("addFavouriteItemContactToGroups", [uid, type, groupIds]).toPromise();
        };
        WebapiClientMethods.prototype.getServicesCallQueue = function () {
            return this.requestChunkedUpdate("getServicesCallQueue", []).response;
        };
        WebapiClientMethods.prototype.getSkillsetsCallQueue = function () {
            return this.requestChunkedUpdate("getSkillsetsCallQueue", []).response;
        };
        WebapiClientMethods.prototype.getClientConfig = function () {
            return this.requestPromise("getClientConfig", []).toPromise();
        };
        WebapiClientMethods.prototype.setClientConfig = function (value) {
            return this.requestPromise("setClientConfig", [value]).toPromise();
        };
        WebapiClientMethods.prototype.setUserStatusReady = function (channelId) {
            return this.requestPromise("setUserStatusReady", [channelId]).toPromise();
        };
        WebapiClientMethods.prototype.setUserStatusNotReady = function (channelId) {
            return this.requestPromise("setUserStatusNotReady", [channelId]).toPromise();
        };
        WebapiClientMethods.prototype.setUserStatusWorkNotReady = function (channelId) {
            return this.requestPromise("setUserStatusWorkNotReady", [channelId]).toPromise();
        };
        WebapiClientMethods.prototype.setActivityCode = function (action) {
            return this.requestPromise("setActivityCode", [action]).toPromise();
        };
        WebapiClientMethods.prototype.enterOnConferenceRoom = function (fromDeviceType, fromDevice) {
            return this.requestPromise("enterOnConferenceRoom", [fromDeviceType, fromDevice]).toPromise();
        };
        WebapiClientMethods.prototype.transferToConferenceRoom = function (callId) {
            return this.requestPromise("transferToConferenceRoom", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.kickOffAllFromConferenceRoom = function () {
            return this.requestPromise("kickOffAllFromConferenceRoom", []).toPromise();
        };
        WebapiClientMethods.prototype.getAddressBooks = function () {
            return this.requestPromise("getAddressBooks", []).toPromise();
        };
        WebapiClientMethods.prototype.addAddressBookContact = function (backendConfigName, contact) {
            return this.requestPromise("addAddressBookContact", [backendConfigName, contact]).toPromise();
        };
        WebapiClientMethods.prototype.setAddressBookContact = function (contact) {
            return this.requestPromise("setAddressBookContact", [contact]).toPromise();
        };
        WebapiClientMethods.prototype.setAgentNoteOnAddressBookContact = function (uuid, agentNote) {
            return this.requestPromise("setAgentNoteOnAddressBookContact", [uuid, agentNote]).toPromise();
        };
        WebapiClientMethods.prototype.mergeAddressBookContact = function (originUid, contactDestination) {
            return this.requestPromise("mergeAddressBookContact", [originUid, contactDestination]).toPromise();
        };
        WebapiClientMethods.prototype.forgetAddressBookContact = function (originUid, force) {
            return this.requestPromise("forgetAddressBookContact", [originUid, force]).toPromise();
        };
        WebapiClientMethods.prototype.delAddressBookContact = function (contactId) {
            return this.requestPromise("delAddressBookContact", [contactId]).toPromise();
        };
        WebapiClientMethods.prototype.acquireWebRTCSession = function (force) {
            return this.requestPromise("acquireWebRTCSession", [force]).toPromise();
        };
        WebapiClientMethods.prototype.freeWebRTCSession = function () {
            return this.requestPromise("freeWebRTCSession", []).toPromise();
        };
        WebapiClientMethods.prototype.mute = function (callId, media) {
            var _a, _b, _c;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.mute(callId, media);
            return (_c = (result ? result.toPromise() : (_b = this.client.webrtc) === null || _b === void 0 ? void 0 : _b.methods.notifyMute(callId, media).toPromise())) !== null && _c !== void 0 ? _c : Promise.resolve(false);
        };
        WebapiClientMethods.prototype.unmute = function (callId, media) {
            var _a, _b, _c;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.unmute(callId, media);
            return (_c = (result ? result.toPromise() : (_b = this.client.webrtc) === null || _b === void 0 ? void 0 : _b.methods.notifyUnmute(callId, media).toPromise())) !== null && _c !== void 0 ? _c : Promise.resolve(false);
        };
        WebapiClientMethods.prototype.conferenceAttendeeMute = function (callId) {
            return this.requestPromise("conferenceAttendeeMute", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.conferenceAttendeeUnmute = function (callId) {
            return this.requestPromise("conferenceAttendeeUnmute", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.getInternalFieldConfigs = function () {
            return this.requestPromise("getInternalFieldConfigs", []).toPromise();
        };
        WebapiClientMethods.prototype.getExternalFieldConfigs = function () {
            return this.requestPromise("getExternalFieldConfigs", []).toPromise();
        };
        WebapiClientMethods.prototype.getPersonalFieldConfigs = function () {
            return this.requestPromise("getPersonalFieldConfigs", []).toPromise();
        };
        WebapiClientMethods.prototype.searchUserCallHistoryItems = function (fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize) {
            return this.requestChunked("searchUserCallHistoryItems",
            [fields, notFields, startGreaterThan, updateGreaterThan, read, services, callContact, callContactId, callContactNumber, pageNumber, pageSize]);
        };
        WebapiClientMethods.prototype.setUserCallHistoryItem = function (ids, read) {
            return this.requestPromise("setUserCallHistoryItem", [ids, read]).toPromise();
        };
        WebapiClientMethods.prototype.delUserCallHistoryItem = function (ids) {
            return this.requestPromise("delUserCallHistoryItem", [ids]).toPromise();
        };
        WebapiClientMethods.prototype.resetUserCallHistoryItemsByContact = function (contact) {
            return this.requestPromise("resetUserCallHistoryItemsByContact", [contact]).toPromise();
        };
        WebapiClientMethods.prototype.resetUserCallHistoryItems = function (transportType) {
            return this.requestPromise("resetUserCallHistoryItems", [transportType]).toPromise();
        };
        WebapiClientMethods.prototype.searchUserChatHistoryItems = function (contactUsername, insertGreaterThan, pageNumber, pageSize) {
            return this.requestChunked("searchUserChatHistoryItems",
            [contactUsername, insertGreaterThan, pageNumber, pageSize]);
        };
        WebapiClientMethods.prototype.getClassConfigurationPermission = function () {
            return this.requestPromiseUpdate("getClassConfigurationPermission", []).toLiveResult();
        };
        WebapiClientMethods.prototype.getConfiguration = function () {
            return this.requestPromiseUpdate("getConfiguration", []).toLiveResult();
        };
        WebapiClientMethods.prototype.resetPassword = function (password) {
            return this.requestPromise("resetPassword", [password]).toPromise();
        };
        WebapiClientMethods.prototype.resetPin = function (pin) {
            return this.requestPromise("resetPin", [pin]).toPromise();
        };
        WebapiClientMethods.prototype.setDirectoryFields = function (directoryFields) {
            return this.requestPromise("setDirectoryFields", [directoryFields]).toPromise();
        };
        WebapiClientMethods.prototype.setName = function (name) {
            return this.requestPromise("setName", [name]).toPromise();
        };
        WebapiClientMethods.prototype.setSurname = function (surname) {
            return this.requestPromise("setSurname", [surname]).toPromise();
        };
        WebapiClientMethods.prototype.setCallFowardSettings = function (callFowardSettings) {
            return this.requestPromise("setCallFowardSettings", [callFowardSettings]).toPromise();
        };
        WebapiClientMethods.prototype.setVoicemailSettings = function (voicemail) {
            return this.requestPromise("setVoicemailSettings", [voicemail]).toPromise();
        };
        WebapiClientMethods.prototype.setConferenceSettings = function (conference) {
            return this.requestPromise("setConferenceSettings", [conference]).toPromise();
        };
        WebapiClientMethods.prototype.getServiceForCallFoward = function () {
            return this.requestPromise("getServiceForCallFoward", []).toPromise();
        };
        WebapiClientMethods.prototype.searchFaxDocument = function (faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize) {
            return this.requestChunkedUpdate("searchFaxDocument", [faxBoxIds, usernames, clid, dnis, status, type, startTimeFrom, startTimeTo, read, pageNumber, pageSize]).toLiveResult();
        };
        WebapiClientMethods.prototype.getQueuedFaxDocument = function () {
            return this.requestChunkedUpdate("getQueuedFaxDocument", []).toLiveResult();
        };
        WebapiClientMethods.prototype.sendFaxDocument = function (faxBoxId, numbers, emailToNotify, priority, fileNames) {
            return this.requestPromise("sendFaxDocument", [faxBoxId, numbers, emailToNotify, priority, fileNames]).toPromise();
        };
        WebapiClientMethods.prototype.sendSms = function (number, message, contact, account) {
            return this.requestPromise("sendSms", [number, message, contact, account]).toPromise();
        };
        WebapiClientMethods.prototype.stopEnqueuedFaxDocument = function (id) {
            return this.requestPromise("stopEnqueuedFaxDocument", [id]).toPromise();
        };
        WebapiClientMethods.prototype.deleteFaxDocument = function (id) {
            return this.requestPromise("deleteFaxDocument", [id]).toPromise();
        };
        WebapiClientMethods.prototype.deleteFaxDocumentFromFileSystem = function (faxDoc) {
            return this.requestPromise("deleteFaxDocumentFromFileSystem", [faxDoc]).toPromise();
        };
        WebapiClientMethods.prototype.updateFaxDocument = function (id, read, note) {
            return this.requestPromise("updateFaxDocument", [id, read, note]).toPromise();
        };
        WebapiClientMethods.prototype.setCallResult = function (action) {
            return this.requestPromise("setCallResult", [action]).toPromise();
        };
        WebapiClientMethods.prototype.getUserInteractions = function () {
            return this.requestChunkedUpdate("getUserInteractions", []).toLiveResult();
        };
        WebapiClientMethods.prototype.setServiceStatusVisible = function (service, visible) {
            return this.requestPromise("setServiceStatusVisible", [service, visible]).toPromise();
        };
        WebapiClientMethods.prototype.getWebClientVersion = function () {
            return this.requestPromiseUpdate("getWebClientVersion", []).toLiveResult();
        };
        WebapiClientMethods.prototype.getClientParams = function () {
            return this.requestPromiseUpdate("getClientParams", []).toLiveResult();
        };
        WebapiClientMethods.prototype.setClientParam = function (values) {
            return this.requestPromise("setClientParam", [values]).toPromise();
        };
        WebapiClientMethods.prototype.getGeneralParams = function (params) {
            return this.requestPromise("getGeneralParams", [params]).toPromise();
        };
        WebapiClientMethods.prototype.updateUserInteraction = function (id, setReadAllRecords, status, action, lastUpdateActivityTime) {
            if (setReadAllRecords === void 0) { setReadAllRecords = false; }
            if (status === void 0) { status = UserInteractionStatus.CLOSED; }
            if (action === void 0) { action = null; }
            if (lastUpdateActivityTime === void 0) { lastUpdateActivityTime = null; }
            return this.requestPromise("updateUserInteraction", [id, setReadAllRecords, status, action, lastUpdateActivityTime]).toPromise();
        };
        WebapiClientMethods.prototype.createUserInteraction = function (createUserInteraction) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.createUserInteraction(createUserInteraction);
            return result ? result.toPromise() : this.requestPromise("createUserInteraction", [createUserInteraction]).toPromise();
        };
        WebapiClientMethods.prototype.setPinnedUserInteraction = function (action) {
            return this.requestPromise("setPinnedUserInteraction", [action]).toPromise();
        };
        WebapiClientMethods.prototype.cleanUserInteractions = function (interactionsToExclude) {
            return this.requestPromise("cleanUserInteractions", interactionsToExclude == undefined ? [] : [interactionsToExclude]).toPromise();
        };
        WebapiClientMethods.prototype.getCurrentUserInteractions = function () {
            return this.requestPromise("getCurrentUserInteractions", []).toPromise();
        };
        WebapiClientMethods.prototype.removeCallFromUserInteraction = function (callId) {
            var _a;
            var result = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.methods.removeCallFromUserInteraction(callId);
            return result ? result.toPromise() : this.requestPromise("removeCallFromUserInteraction", [callId]).toPromise();
        };
        WebapiClientMethods.prototype.getAllActivityCode = function () {
            return this.requestPromise("getAllActivityCode", []).toPromise();
        };
        WebapiClientMethods.prototype.getRoomDeskConfig = function (roomId) {
            return this.requestChunkedUpdate("getRoomDeskConfig", [roomId]).toLiveResult();
        };
        WebapiClientMethods.prototype.getActiveServiceCalls = function (profileId) {
            return this.requestChunkedUpdate("getActiveServiceCalls", [profileId]).toLiveResult();
        };
        WebapiClientMethods.prototype.servicePickup = function (fromDeviceType, fromDevice, callId, skillset, mcId) {
            if (mcId === void 0) { mcId = "0"; }
            return this.requestPromise("servicePickup", [fromDeviceType, fromDevice, callId, skillset, mcId]).toPromise();
        };
        WebapiClientMethods.prototype.servicePickupPrivateParkedCall = function (fromDeviceType, fromDevice, callId) {
            return this.requestPromise("servicePickupPrivateParkedCall", [fromDeviceType, fromDevice, callId]).toPromise();
        };
        WebapiClientMethods.prototype.updateWorkingSessionsNote = function (id, note) {
            return this.requestPromise("updateWorkingSessionsNote", [id, note]).toPromise();
        };
        WebapiClientMethods.prototype.setDND = function (active) {
            return this.requestPromise("setDND", [active]).toPromise();
        };
        WebapiClientMethods.prototype.tqmParkPrivate = function (callId, fromDeviceType, fromDevice, service, cli, data) {
            return this.requestPromise("tqmParkPrivate", [callId, fromDeviceType, fromDevice, service, cli, data]).toPromise();
        };
        WebapiClientMethods.prototype.tqmParkPublic = function (fromDeviceType, fromDevice, number) {
            return this.requestPromise("tqmParkPublic", [fromDeviceType, fromDevice, number]).toPromise();
        };
        WebapiClientMethods.prototype.freeDevice = function (type, device) {
            return this.requestPromise("freeDevice", [type, device]).toPromise();
        };
        WebapiClientMethods.prototype.isCallTaggable = function (number) {
            return this.requestPromise("isCallTaggable", [number]).toPromise();
        };
        WebapiClientMethods.prototype.getIntranetSections = function () {
            return this.requestChunked("getIntranetSections", []);
        };
        WebapiClientMethods.prototype.getIntranetPages = function () {
            return this.requestChunked("getIntranetPages", []);
        };
        WebapiClientMethods.prototype.getIntranetPage = function (id) {
            return this.requestPromise("getIntranetPage", [id]).toPromise();
        };
        WebapiClientMethods.prototype.getIntranetSection = function (id) {
            return this.requestPromise("getIntranetSection", [id]).toPromise();
        };
        WebapiClientMethods.prototype.monitorContact = function (contactId) {
            return this.requestPromiseUpdate("monitorContact", []).toLiveResult();
        };
        WebapiClientMethods.prototype.addIntranetSection = function (name, position) {
            return this.requestPromise("addIntranetSection", [name, position]).toPromise();
        };
        WebapiClientMethods.prototype.setIntranetSection = function (id, name, position) {
            return this.requestPromise("setIntranetSection", [id, name, position]).toPromise();
        };
        WebapiClientMethods.prototype.resetIntranetSectionPosition = function (sectionIdList) {
            return this.requestPromise("resetIntranetSectionPosition", [sectionIdList]).toPromise();
        };
        WebapiClientMethods.prototype.delIntranetSection = function (id) {
            return this.requestPromise("delIntranetSection", [id]).toPromise();
        };
        WebapiClientMethods.prototype.getIntranetItemsOnSection = function (sectionId) {
            return this.requestChunked("getIntranetItemsOnSection", [sectionId]);
        };
        WebapiClientMethods.prototype.addIntranetItemToSection = function (sectionId, description, url, image, position) {
            return this.requestPromise("addIntranetItemToSection", [sectionId, description, url, image, position]).toPromise();
        };
        WebapiClientMethods.prototype.setIntranetItemPosition = function (uid, sectionId, position) {
            return this.requestPromise("setIntranetItemPosition", [uid, sectionId, position]).toPromise();
        };
        WebapiClientMethods.prototype.setIntranetItem = function (uid, sectionId, description, url, image, position) {
            return this.requestPromise("setIntranetItem", [uid, sectionId, description, url, image, position]).toPromise();
        };
        WebapiClientMethods.prototype.delIntranetItem = function (uid) {
            return this.requestPromise("delIntranetItem", [uid]).toPromise();
        };
        WebapiClientMethods.prototype.resetIntranetItemPosition = function (itemIdList) {
            return this.requestPromise("resetIntranetItemPosition", [itemIdList]).toPromise();
        };
        WebapiClientMethods.prototype.noteSearch = function (searchCriteria) {
            return this.requestChunked("noteSearch", [searchCriteria]);
        };
        WebapiClientMethods.prototype.noteGet = function (noteUid) {
            return this.requestPromise("noteGet", [noteUid]).toPromise();
        };
        WebapiClientMethods.prototype.noteAdd = function (note) {
            return this.requestPromise("noteAdd", [note]).toPromise();
        };
        WebapiClientMethods.prototype.noteSet = function (note) {
            return this.requestPromise("noteSet", [note]).toPromise();
        };
        WebapiClientMethods.prototype.noteContactSet = function (noteUid, noteContacts) {
            return this.requestPromise("noteContactSet", [noteUid, noteContacts]).toPromise();
        };
        WebapiClientMethods.prototype.noteTagAdd = function (noteUid, tag) {
            return this.requestPromise("noteTagAdd", [noteUid, tag]).toPromise();
        };
        WebapiClientMethods.prototype.noteTagDel = function (noteUid, tag) {
            return this.requestPromise("noteTagDel", [noteUid, tag]).toPromise();
        };
        WebapiClientMethods.prototype.noteTagGet = function () {
            return this.requestChunked("noteTagGet", []);
        };
        WebapiClientMethods.prototype.noteSetArchived = function (noteUid, archived) {
            return this.requestPromise("noteSetArchived", [noteUid, archived]).toPromise();
        };
        WebapiClientMethods.prototype.noteSetDeleted = function (noteUid, deleted) {
            return this.requestPromise("noteSetDeleted", [noteUid, deleted]).toPromise();
        };
        WebapiClientMethods.prototype.startNoteCounterTotalNotify = function () {
            return this.requestPromiseUpdate("startNoteCounterTotalNotify", []).response;
        };
        WebapiClientMethods.prototype.startOmnideskCounterTotalNotify = function () {
            return this.requestPromiseUpdate("startOmnideskCounterTotalNotify", []).response;
        };
        WebapiClientMethods.prototype.startNoteUpdateNotify = function () {
            return this.requestPromiseUpdate("startNoteUpdateNotify", []).response;
        };
        WebapiClientMethods.prototype.startClientStatusNotify = function (requestTimeout) {
            return this.requestPromiseUpdate("startClientStatusNotify", [], { requestTimeout: requestTimeout }).response;
        };
        WebapiClientMethods.prototype.contactNoteExpiredNotify = function () {
            return this.requestPromiseUpdate("contactNoteExpiredNotify", []).response;
        };
        WebapiClientMethods.prototype.contactNoteReminderNotify = function () {
            return this.requestPromiseUpdate("contactNoteReminderNotify", []).response;
        };
        WebapiClientMethods.prototype.omnideskScheduledMeetingNotify = function () {
            return this.requestPromiseUpdate("omnideskScheduledMeetingNotify", []).response;
        };
        WebapiClientMethods.prototype.isSecurePasswordEnabled = function () {
            return this.requestPromise("isSecurePasswordEnabled", []).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallsSearchClosed = function (searchCriteria) {
            return this.requestChunked("abandonedCallsSearchClosed", [searchCriteria]);
        };
        WebapiClientMethods.prototype.abandonedCallsSearchOpened = function (searchCriteria) {
            return this.requestChunkedUpdate("abandonedCallsSearchOpened", [searchCriteria]).toLiveResult();
        };
        WebapiClientMethods.prototype.abandonedCallsSearchOpenedPaged = function (searchCriteria, page, size, order) {
            return this.requestChunked("abandonedCallsSearchOpenedPaged", [searchCriteria, page, size, order]);
        };
        WebapiClientMethods.prototype.abandonedCallClose = function (id) {
            return this.requestPromise("abandonedCallClose", [id]).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallDelete = function (id) {
            return this.requestPromise("abandonedCallDelete", [id]).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallRetryExceeded = function (id) {
            return this.requestPromise("abandonedCallRetryExceeded", [id]).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallUnlock = function (id, force) {
            return this.requestPromise("abandonedCallUnlock", [id, force]).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallLock = function (id) {
            return this.requestPromise("abandonedCallLock", [id]).toPromise();
        };
        WebapiClientMethods.prototype.abandonedCallUpdateNote = function (id, startTime, note) {
            return this.requestPromise("abandonedCallUpdateNote", [id, startTime, note]).toPromise();
        };
        WebapiClientMethods.prototype.getAgentsOnServices = function (serviceCodes) {
            return this.requestChunked("getAgentsOnServices", [serviceCodes]);
        };
        WebapiClientMethods.prototype.getAgentsOnServicesCheckMc1002 = function (serviceCodes, checkMc1002Sync, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 60000; }
            return this.requestChunked("getAgentsOnServicesCheckMc1002", [serviceCodes, checkMc1002Sync], { requestTimeout: requestTimeout });
        };
        WebapiClientMethods.prototype.getServicesByCode = function (serviceCodes) {
            return this.requestChunked("getServicesByCode", [serviceCodes]);
        };
        WebapiClientMethods.prototype.getServices = function () {
            return this.requestChunked("getServices", []);
        };
        WebapiClientMethods.prototype.setWinWebVersion = function (version) {
            return this.requestPromise("setWinWebVersion", [version]).toPromise();
        };
        WebapiClientMethods.prototype.setClientDetail = function (id, platform, so, release, clientVersion) {
            return this.requestPromise("setClientDetail", [id, platform, so, release, clientVersion]).toPromise();
        };
        WebapiClientMethods.prototype.setAppDetail = function (action) {
            return this.requestPromise("setAppDetail", [action]).toPromise();
        };
        WebapiClientMethods.prototype.ackCallMessage = function (callId, counter) {
            return this.requestPromise("ackCallMessage", [callId, counter]).toPromise();
        };
        WebapiClientMethods.prototype.ticketSearch = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketSearch", [action], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketEscalatedSearch = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketEscalatedSearch", [action], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketSearchForMerge = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketSearchForMerge", [action], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketSearchForLink = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketSearchForLink", [action], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketGet = function (ticketId, withUpdatePolicy, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromiseUpdate("ticketGet", [ticketId, withUpdatePolicy], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketGetPreview = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketGetPreview", [ticketId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetArticles = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestChunkedUpdate("ticketGetArticles", [ticketId], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketGetArticlesLight = function (ticketId, articleIds, serviceCode, callLink, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestChunkedUpdate("ticketGetArticlesLight", [ticketId, articleIds, serviceCode, callLink], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketGetArticlesPreview = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunked("ticketGetArticlesPreview", [ticketId], { requestTimeout: requestTimeout });
        };
        WebapiClientMethods.prototype.ticketGetArticlesPreviewByArticleId = function (firstArticleId, lastArticleId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunked("ticketGetArticlesPreviewByArticleId", [firstArticleId, lastArticleId], { requestTimeout: requestTimeout });
        };
        WebapiClientMethods.prototype.ticketGetHistory = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketGetHistory", [ticketId], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketGetLinks = function (ticketId, serviceCodes, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestChunkedUpdate("ticketGetLinks", [ticketId, serviceCodes], { requestTimeout: requestTimeout }).toLiveResult();
        };
        WebapiClientMethods.prototype.ticketAddLinks = function (ticketTargetId, ticketSourceNumber, linkType, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketAddLinks", [ticketTargetId, ticketSourceNumber, linkType], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketDeleteLinks = function (ticketTargetId, ticketSourceId, linkType, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketDeleteLinks", [ticketTargetId, ticketSourceId, linkType], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketAdd = function (ticket, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketAdd", [ticket], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketAddWithAttachments = function (ticket, attachments, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketAddWithAttachments", [ticket, attachments], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketMerge = function (ticketMaster, ticketSlaveId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketMerge", [ticketMaster, ticketSlaveId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketUpdate = function (ticket, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketUpdate", [ticket], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketMultipleUpdate = function (ticketIdList, field, value, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketMultipleUpdate", [ticketIdList, field, value], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketSetViewByOwner = function (ticket, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketSetViewByOwner", [ticket], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketAddArticle = function (ticket, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketAddArticle", [ticket], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketAddArticleWithAttachments = function (article, attachments, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketAddArticleWithAttachments", [article, attachments], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketSignatureGet = function (serviceCode, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketSignatureGet", [serviceCode], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetEmailAddresses = function (requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketGetEmailAddresses", [], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketSetRead = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketSetRead", [ticketId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetFieldConfigs = function (requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketGetFieldConfigs", [], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetInboundEmailAddressOnService = function (serviceCode, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketGetInboundEmailAddressOnService", [serviceCode], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetSettings = function (requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketGetSettings", [], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketStartSession = function (ticketId, interactionId, action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketStartSession", [ticketId, interactionId, action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketStopSession = function (ticketId, interactionId, action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketStopSession", [ticketId, interactionId, action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketIsAcdOnAgentBar = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("ticketIsAcdOnAgentBar", [ticketId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.customerPortalIsCustomerRegistered = function (customerEmail, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("customerPortalIsCustomerRegistered", [customerEmail], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.customerPortalGetCustomerSettings = function (t4youUid, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("customerPortalGetCustomerSettings", [t4youUid], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.customerPortalSetCustomerSettings = function (cps, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("customerPortalSetCustomerSettings", [cps], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.customerPortalRestoreCustomerPassword = function (cps, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 15000; }
            return this.requestPromise("customerPortalRestoreCustomerPassword", [cps], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.getWebrtcConfiguration = function () {
            return this.requestPromise("getWebrtcConfiguration", []).toPromise();
        };
        WebapiClientMethods.prototype.lookupSearch = function (value) {
            return this.requestChunked("lookupSearch", [value]);
        };
        WebapiClientMethods.prototype.callLookupSearch = function (value) {
            return this.requestChunked("callLookupSearch", [value]);
        };
        WebapiClientMethods.prototype.startChatSessionNotify = function () {
            return this.requestPromiseUpdate("startChatSessionNotify", []).toLiveResult();
        };
        WebapiClientMethods.prototype.sendChatEventMessage = function (chatId, message) {
            return this.requestPromise("sendChatEventMessage", [chatId, message]).toPromise();
        };
        WebapiClientMethods.prototype.searchChatMessageChannel = function (action) {
            return this.requestChunkedUpdate("searchChatMessageChannel", [action]).toLiveResult();
        };
        WebapiClientMethods.prototype.chatAgentReceivedMessage = function (action) {
            return this.requestPromise("chatAgentReceivedMessage", [action]).toPromise();
        };
        WebapiClientMethods.prototype.chatAgentReadMessage = function (action) {
            return this.requestPromise("chatAgentReadMessage", [action]).toPromise();
        };
        WebapiClientMethods.prototype.channelInfoHistoryItemSearch = function (action) {
            return this.requestChunked("channelInfoHistoryItemSearch",
            [action]);
        };
        WebapiClientMethods.prototype.chatUpdateFile = function (file) {
            return this.requestPromise("chatUpdateFile", [file]).toPromise();
        };
        WebapiClientMethods.prototype.channelInfoHistoryFileSearch = function (action) {
            return this.requestChunked("channelInfoHistoryFileSearch",
            [action]);
        };
        WebapiClientMethods.prototype.widgetJourneySearch = function (action) {
            return this.requestChunkedUpdate("widgetJourneySearch", [action]).toLiveResult();
        };
        WebapiClientMethods.prototype.moveInteractionToContact = function (moveInteraction) {
            return this.requestPromise("moveInteractionToContact", [moveInteraction]).toPromise();
        };
        WebapiClientMethods.prototype._internalTest_updateContactOnInteraction = function (moveInteraction) {
            return this.requestPromise("_internalTest_updateContactOnInteraction", [moveInteraction]).toPromise();
        };
        WebapiClientMethods.prototype.getServicesByChannel = function (action) {
            return this.requestChunked("getServicesByChannel", [action]);
        };
        WebapiClientMethods.prototype.transferChannelToService = function (callId, serviceCode) {
            return this.requestPromise("transferChannelToService", [callId, serviceCode]).toPromise();
        };
        WebapiClientMethods.prototype.setOutboundCallBlocked = function (active) {
            return this.requestPromise("setOutboundCallBlocked", [active]).toPromise();
        };
        WebapiClientMethods.prototype.chatSendRecapOfSession = function (action) {
            return this.requestPromise("chatSendRecapOfSession", [action]).toPromise();
        };
        WebapiClientMethods.prototype.callbackRequestSearchClosed = function (searchAction) {
            return this.requestChunked("callbackRequestSearchClosed", [searchAction]);
        };
        WebapiClientMethods.prototype.callbackRequestSearchOpen = function (searchAction) {
            return this.requestChunkedUpdate("callbackRequestSearchOpen", [searchAction]).toLiveResult();
        };
        WebapiClientMethods.prototype.callbackRequestsSearchOpenPaginated = function (searchAction, page, size, order) {
            return this.requestChunked("callbackRequestsSearchOpenPaginated", [searchAction, page, size, order]);
        };
        WebapiClientMethods.prototype.callbackRequestClose = function (id) {
            return this.requestPromise("callbackRequestClose", [id]).toPromise();
        };
        WebapiClientMethods.prototype.callbackRequestDelete = function (id) {
            return this.requestPromise("callbackRequestDelete", [id]).toPromise();
        };
        WebapiClientMethods.prototype.callbackRequestUnlock = function (id, force) {
            return this.requestPromise("callbackRequestUnlock", [id, force]).toPromise();
        };
        WebapiClientMethods.prototype.callbackRequestLock = function (id) {
            return this.requestPromise("callbackRequestLock", [id]).toPromise();
        };
        WebapiClientMethods.prototype.callbackRequestUpdateNote = function (id, startTime, note) {
            return this.requestPromise("callbackRequestUpdateNote", [id, startTime, note]).toPromise();
        };
        WebapiClientMethods.prototype.getInsightUrl = function () {
            return this.requestPromise("getInsightUrl", []).toPromise();
        };
        WebapiClientMethods.prototype.searchADSAlarmHistory = function () {
            return this.requestChunked("searchADSAlarmHistory", []);
        };
        WebapiClientMethods.prototype.startDelayedTaskNotify = function () {
            return this.requestPromiseUpdate("startDelayedTaskNotify", []).response;
        };
        WebapiClientMethods.prototype.startADSAlarmNotify = function () {
            return this.requestPromiseUpdate("startADSAlarmNotify", []).response;
        };
        WebapiClientMethods.prototype.validateAddressBookContactField = function (uid, field, position) {
            return this.requestPromise("validateAddressBookContactField", [uid, field, position]).toPromise();
        };
        WebapiClientMethods.prototype.setCensusResult = function (userInteractionId, result, backend, number) {
            if (backend === void 0) { backend = null; }
            if (number === void 0) { number = null; }
            return this.requestPromise("setCensusResult", backend == null ? [userInteractionId, result] : [userInteractionId, result, backend, number]).toPromise();
        };
        WebapiClientMethods.prototype.getCustomerJourney = function (uidContact, page, size, agentFilter) {
            return this.requestChunked("getCustomerJourney", [uidContact, page, size, agentFilter]);
        };
        WebapiClientMethods.prototype.getCustomerJourneyInteractionAmounts = function (uidContact, agentFilter) {
            return this.requestPromise("getCustomerJourneyInteractionAmounts", [uidContact, agentFilter]).toPromise();
        };
        WebapiClientMethods.prototype.searchLoggedProfileByChannel = function (action) {
            return this.requestChunked("searchLoggedProfileByChannel", [action]);
        };
        WebapiClientMethods.prototype.usersThatWaitToSetNR = function () {
            return this.requestChunkedUpdate("usersThatWaitToSetNR", []).toLiveResult();
        };
        WebapiClientMethods.prototype.acceptRequestToSetNR = function (username) {
            return this.requestPromise("acceptRequestToSetNR", [username]).toPromise();
        };
        WebapiClientMethods.prototype.denyRequestToSetNR = function (username) {
            return this.requestPromise("denyRequestToSetNR", [username]).toPromise();
        };
        WebapiClientMethods.prototype.setUserStatusNotReadyAskingToSupervisor = function () {
            return this.requestPromise("setUserStatusNotReadyAskingToSupervisor", []).toPromise();
        };
        WebapiClientMethods.prototype.resetRequestNRToSupervisor = function () {
            return this.requestPromise("resetRequestNRToSupervisor", []).toPromise();
        };
        WebapiClientMethods.prototype.getActiveLicense = function () {
            return this.requestPromise("getActiveLicense", []).toPromise();
        };
        WebapiClientMethods.prototype.getListOfNumbersWithInternationalPrefix = function (number) {
            return this.requestPromise("getListOfNumbersWithInternationalPrefix", [number]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterGetFieldByScope = function (scope) {
            return this.requestPromise("searchFilterGetFieldByScope", [scope]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterSearch = function (scopeApplication, stringToSearch) {
            return this.requestPromise("searchFilterSearch", [scopeApplication, stringToSearch]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterGetById = function (searchFilterId) {
            return this.requestPromise("searchFilterGetById", [searchFilterId]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterGetByIdList = function (searchFilterIdList) {
            return this.requestPromise("searchFilterGetByIdList", [searchFilterIdList]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterAdd = function (searchFilter) {
            return this.requestPromise("searchFilterAdd", [searchFilter]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterUpdate = function (searchFilter) {
            return this.requestPromise("searchFilterUpdate", [searchFilter]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterDelete = function (searchFilterId) {
            return this.requestPromise("searchFilterDelete", [searchFilterId]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterOnUserByApplication = function (scopeApplication) {
            return this.requestPromise("searchFilterOnUserByApplication", [scopeApplication]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterAddOnUserByApplication = function (searchFilterId, scopeApplication) {
            return this.requestPromise("searchFilterAddOnUserByApplication", [searchFilterId, scopeApplication]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterDeleteOnUserByApplication = function (searchFilterId, scopeApplication) {
            return this.requestPromise("searchFilterDeleteOnUserByApplication", [searchFilterId, scopeApplication]).toPromise();
        };
        WebapiClientMethods.prototype.sendCommandResponse = function (commandResult) {
            return this.requestPromise("sendCommandResponse", [commandResult]).toPromise();
        };
        WebapiClientMethods.prototype.publishNewIncomingCall = function (callEvent) {
            return this.requestPromise("publishNewIncomingCall", [callEvent]).toPromise();
        };
        WebapiClientMethods.prototype.publishNewOutgoingCall = function (callEvent) {
            return this.requestPromise("publishNewOutgoingCall", [callEvent]).toPromise();
        };
        WebapiClientMethods.prototype.publishEvent = function (event) {
            return this.requestPromise("publishEvent", [event]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterEnable = function (searchFilterId) {
            return this.requestPromise("searchFilterEnable", [searchFilterId]).toPromise();
        };
        WebapiClientMethods.prototype.searchFilterDisable = function (searchFilterId) {
            return this.requestPromise("searchFilterDisable", [searchFilterId]).toPromise();
        };
        WebapiClientMethods.prototype.searchCampaign = function (action) {
            return this.requestChunked("searchCampaign", [action]);
        };
        WebapiClientMethods.prototype.startCampaign = function (action) {
            return this.requestPromise("startCampaign", [action]).toPromise();
        };
        WebapiClientMethods.prototype.stopCampaign = function (action) {
            return this.requestPromise("stopCampaign", [action]).toPromise();
        };
        WebapiClientMethods.prototype.getCampaignStatus = function () {
            return this.requestChunkedUpdate("getCampaignStatus", []).toLiveResult();
        };
        WebapiClientMethods.prototype.searchCampaignProcessedByRunId = function (action) {
            return this.requestChunked("searchCampaignProcessedByRunId", [action]);
        };
        WebapiClientMethods.prototype.exportCampaignRunIdDetail = function (runEndtime, runId, type) {
            return this.requestPromise("exportCampaignRunIdDetail", [runEndtime, runId, type]).toPromise();
        };
        WebapiClientMethods.prototype.createCampaign = function (action) {
            return this.requestPromise("createCampaign", [action]).toPromise();
        };
        WebapiClientMethods.prototype.setCampaign = function (campaign) {
            return this.requestPromise("setCampaign", [campaign]).toPromise();
        };
        WebapiClientMethods.prototype.getCampaign = function (id) {
            return this.requestPromise("getCampaign", [id]).toPromise();
        };
        WebapiClientMethods.prototype.updateImgProfile = function (img, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 30000; }
            return this.requestPromise("updateImgProfile", [img], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetArticlesTimeAccounting = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("ticketGetArticlesTimeAccounting", [ticketId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetMergedArticlesTimeAccounting = function (ticketArticleIdList, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("ticketGetMergedArticlesTimeAccounting", [ticketArticleIdList], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.ticketGetArticleTimeAccounting = function (ticketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("ticketGetArticleTimeAccounting", [ticketId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSearch = function (knowledgeBaseId, categoryId, query) {
            return this.requestPromise("knowledgeBaseSearch", [knowledgeBaseId, categoryId, query]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetAnswerOnCall = function (interactionId, callId, answerId, answerUrl) {
            return this.requestPromise("knowledgeBaseSetAnswerOnCall", [interactionId, callId, answerId, answerUrl]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetNotFoundAnswerOnCall = function (interactionId, callId) {
            return this.requestPromise("knowledgeBaseSetNotFoundAnswerOnCall", [interactionId, callId]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetNoAnswerOnCall = function (interactionId, callId) {
            return this.requestPromise("knowledgeBaseSetNoAnswerOnCall", [interactionId, callId]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetAnswerOnTicket = function (ticketId, answerId, answerUrl) {
            return this.requestPromise("knowledgeBaseSetAnswerOnTicket", [ticketId, answerId, answerUrl]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetNoAnswerOnTicket = function (ticketId) {
            return this.requestPromise("knowledgeBaseSetNoAnswerOnTicket", [ticketId]).toPromise();
        };
        WebapiClientMethods.prototype.knowledgeBaseSetCategoryOnTicket = function (ticketId, categoryId, categoryUrl) {
            return this.requestPromise("knowledgeBaseSetCategoryOnTicket", [ticketId, categoryId, categoryUrl]);
        };
        WebapiClientMethods.prototype.knowledgeBaseGetAnswerHits = function (answerId) {
            return this.requestPromise("knowledgeBaseGetAnswerHits", [answerId]);
        };
        WebapiClientMethods.prototype.ticketAddArticleByCopy = function (originalArticle, destinationTicketId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("ticketAddArticleByCopy", [originalArticle, destinationTicketId], { requestTimeout: requestTimeout });
        };
        WebapiClientMethods.prototype.omnideskCreateMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskCreateMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskCreateScheduledMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskCreateScheduledMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskSetScheduledMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskSetScheduledMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskUpdateScheduleMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskUpdateScheduleMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskCreateChatGroupForMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskCreateChatGroupForMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskDeleteScheduledMeetingEvent = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskDeleteScheduledMeetingEvent", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskGetMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskGetMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskSearchMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 30000; }
            return this.requestChunked("omnideskSearchMeeting", [action], { requestTimeout: requestTimeout });
        };
        WebapiClientMethods.prototype.omnideskGetParticipantToken = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskGetParticipantToken", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskGetJwt = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskGetJwt", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskAddParticipantToMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskAddParticipantToMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskResetParticipantToken = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskResetParticipantToken", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskLeaveMeeting = function (meetingParticipantId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskLeaveMeeting", [meetingParticipantId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskCloseMeeting = function (meetingId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskCloseMeeting", [meetingId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskGenerateLinkToMeeting = function (meetingId, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskGenerateLinkToMeeting", [meetingId], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskRemoveParticipantFromMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskRemoveParticipantFromMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskResumeMeeting = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskResumeMeeting", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.omnideskResetLostMeetingOnContact = function (contact, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("omnideskResetLostMeetingOnContact", [contact], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.startClientCommandNotify = function () {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    return [2 , this.commandNotification.start()];
                });
            });
        };
        WebapiClientMethods.prototype.stopClientCommandNotify = function () {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    return [2 , this.commandNotification.stop()];
                });
            });
        };
        WebapiClientMethods.prototype.sendClientCommandResponse = function (commandResult) {
            return __awaiter$8(this, void 0, void 0, function () {
                return __generator$8(this, function (_a) {
                    return [2 , this.requestPromise("sendClientCommandResponse", [commandResult]).toPromise()];
                });
            });
        };
        WebapiClientMethods.prototype.getUserDetailLight = function () {
            return this.requestPromise("getUserDetailLight", []);
        };
        WebapiClientMethods.prototype.sendFeedback = function (action, requestTimeout) {
            if (requestTimeout === void 0) { requestTimeout = 120000; }
            return this.requestPromise("sendFeedback", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.dialATXferOnGenericDevice = function (action, requestTimeout) {
            return this.requestPromise("dialATXferOnGenericDevice", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.cancelTransferOnGenericDevice = function (action, requestTimeout) {
            return this.requestPromise("cancelTransferOnGenericDevice", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.setWebRTCActiveMedia = function (action, requestTimeout) {
            return this.requestPromise("setWebRTCActiveMedia", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.setPhoneManagerActive = function (action, requestTimeout) {
            return this.requestPromise("setPhoneManagerActive", [action], { requestTimeout: requestTimeout }).toPromise();
        };
        WebapiClientMethods.prototype.getFireFlyMeasurement = function (requestTimeout) {
            return this.requestPromiseUpdate("getFireFlyMeasurement", []).response;
        };
        WebapiClientMethods.prototype.getCurrentSkillsetsWithProfiles = function (requestTimeout) {
            return this.requestPromise("getCurrentSkillsetsWithProfiles", [], { requestTimeout: requestTimeout }).toPromise();
        };
        return WebapiClientMethods;
    }(Methods));

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

    function exceptionInitializer(exception) {
        try {
            return exceptionInitializer$1(exception, Errors);
        }
        catch (e) {
            return e;
        }
    }
    var ErrorResolver =  (function () {
        function ErrorResolver() {
        }
        ErrorResolver.login = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.logout = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getUserDetail = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.useProfile = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.useDevice = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.inboundCallExtension = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchUsers = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getListOfCompany = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchUsersExtended = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchUsersExtendedByBackend = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getUserSites = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getUnreadChat = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getUserContactStatus = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAddressBookContactByUuid = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getFavouriteContacts = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.addFavouriteItemGroup = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setFavouriteItemGroup = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setFavouriteItemGroups = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delFavouriteItemGroup = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setFavouriteItemContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.addFavouriteItemContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delFavouriteItemContactFromGroup = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startCallNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.isInternalNumber = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAllServiceCode = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopCallNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startVideoSessionNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopVideoSessionNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.dial = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.dialCallTagging = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.answer = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.cancel = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.hold = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.unhold = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.attendedTransfer = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.blindTransfer = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.blindTransferMultiChannelToUser = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setCallData = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendDTMF = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopRecord = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startRecord = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateCallRecordingNoted = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.chanSpyUser = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getFavouriteUserGroups = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delFavouriteItemContactFromGroups = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.addFavouriteItemContactToGroups = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getServicesCallQueue = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getSkillsetsCallQueue = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getClientConfig = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setClientConfig = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setUserStatusReady = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setUserStatusNotReady = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setUserStatusWorkNotReady = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setActivityCode = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.enterOnConferenceRoom = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.transferToConferenceRoom = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.kickOffAllFromConferenceRoom = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateWebRTCFields = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAddressBooks = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.addAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.mergeAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setAgentNoteOnAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.acquireWebRTCSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.freeWebRTCSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.mute = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.unmute = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startVideoOnCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopVideoOnCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getExternalCustomFieldConfigs = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getInternalCustomFieldConfigs = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchUserCallHistoryItems = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchUserChatHistoryItems = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setUserCallHistoryItem = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delUserCallHistoryItem = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resetUserCallHistoryItems = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resetUserCallHistoryItemsByContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getClassConfigurationPermission = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getConfiguration = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resetPassword = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resetPin = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setDirectoryFields = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setName = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setSurname = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setCallFowardSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setVoicemailSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setConferenceSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getServiceForCallFoward = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getQueuedFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendSms = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopEnqueuedFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.deleteFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.deleteFaxDocumentFromFileSystem = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateFaxDocument = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.restartSessionId = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setCallResult = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getUserInteractions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.closeUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.removeCallFromUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setPinnedUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.delUserInteractions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCurrentCalls = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setServiceStatusVisible = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getClientParams = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setClientParam = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getGeneralParams = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.exportAddressBook = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.importAddressBook = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAllCategories = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getWorkingSessions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.closeWorkingSessions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startWorkingSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCurrentWorkingSessions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startAnonymousWorkingSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAllActivityCode = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getRoomDeskConfig = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getActiveServiceCalls = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.servicePickup = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.servicePickupPrivateParkedCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateWorkingSessions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.createUserInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setDND = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.tqmParkPrivate = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.tqmParkPublic = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.freeDevice = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallsSearchClosed = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallsSearchOpened = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallClose = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallDelete = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallRetryExceeded = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallUnlock = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallLock = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.abandonedCallUpdateNote = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAgentsOnServices = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getAgentsOnServicesCheckMc1002 = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getServicesByCode = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getServices = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getWebrtcConfiguration = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setWinWebVersion = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setClientDetail = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketEscalatedSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSearchForMerge = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSearchForLink = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGet = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetPreview = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetArticles = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetArticlesLight = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetArticlesPreviewByArticleId = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetArticlesPreview = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetHistory = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetLinks = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAddLinks = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.prototype.ticketDeleteLinks = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAdd = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAddWithAttachments = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketMerge = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketUpdate = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketMultipleUpdate = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSetViewByOwner = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAddArticle = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAddArticleWithAttachments = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSignatureGet = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetEmailAddresses = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketSetRead = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetFieldConfigs = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetInboundEmailAddressOnServiceerror = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketStartSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketStopSession = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketIsAcdOnAgentBar = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.customerPortalIsCustomerRegistered = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.customerPortalSetCustomerSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.customerPortalGetCustomerSettings = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.customerPortalRestoreCustomerPassword = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.lookupSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callLookupSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startChatSessionNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendChatEventMessage = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.moveInteractionToContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.widgetJourneySearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver._internalTest_updateContactOnInteraction = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getServicesByChannel = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.transferChannelToService = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchChatMessageChannel = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.chatAgentReceivedMessage = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.chatAgentReadMessage = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setOutboundCallBlocked = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setOutboundCchatSendRecapOfSessionallBlocked = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestSearchClosed = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestSearchOpen = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestsSearchOpenPaginated = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestClose = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestDelete = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestUnlock = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestLock = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.callbackRequestUpdateNote = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getInsightUrl = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchADSAlarmHistory = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.validateAddressBookContactField = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setCensusResult = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCustomerJourney = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCustomerJourneyInteractionsInfo = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchLoggedProfileByChannel = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.usersThatWaitToSetNR = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.acceptRequestToSetNR = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.denyRequestToSetNR = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setUserStatusNotReadyAskingToSupervisor = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resetRequestNRToSupervisor = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getActiveLicense = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getListOfNumbersWithInternationalPrefix = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterGetFieldByScope = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterGetById = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterAdd = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterUpdate = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterDelete = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterOnUserByApplication = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterAddOnUserByApplication = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterDeleteOnUserByApplication = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendCommandResponse = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.publishNewIncomingCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.publishNewOutgoingCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.publishEvent = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterEnable = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterDisable = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchFilterGetByIdList = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.stopCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCampaignStatus = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.searchCampaignProcessedByRunId = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.exportCampaignRunIdDetail = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.createCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.setCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCampaign = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateImgProfile = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateImgPticketGetArticlesTimeAccountingrofile = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.updateImgPticketGetArticleTimeAccountingrofile = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetAnswerOnCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetNoAnswerOnCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetNotFoundAnswerOnCall = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetAnswerOnTicket = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetNoAnswerOnTicket = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseSetCategoryOnTicket = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.knowledgeBaseGetAnswerHits = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.channelInfoHistoryItemSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketAddArticleByCopy = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.ticketGetMergedArticlesTimeAccounting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.cleanUserInteractions = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.channelInfoHistoryFileSearch = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.chatUpdateFile = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.monitorContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getIntranetPages = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getIntranetPage = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startNoteCounterTotalNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startOmnideskCounterTotalNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startNoteUpdateNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getOmnideskUriAccess = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.resumeChatToken = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskCreateMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskAddParticipantToMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskGetParticipantToken = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskResetParticipantToken = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskCloseMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskLeaveMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskGenerateLinkToMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskGetJwt = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskRemoveParticipantFromMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskResumeMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskUpdateScheduleMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskCreateChatGroupForMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startClientCommandNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.contactNoteExpiredNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.contactNoteReminderNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskScheduledMeetingNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendClientCommandResponse = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.forgetAddressBookContact = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskCreateScheduledMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskSetScheduledMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskDeleteScheduledMeetingEvent = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskGetMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.omnideskSearchMeeting = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.sendFeedback = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startADSAlarmNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.startDelayedTaskNotify = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.dialATXferOnGenericDevice = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.cancelTransferOnGenericDevice = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getFireFlyMeasurement = function (error) {
            return exceptionInitializer(error);
        };
        ErrorResolver.getCurrentSkillsetsWithProfiles = function (error) {
            return exceptionInitializer(error);
        };
        return ErrorResolver;
    }());

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

    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;
      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;
    };
    RetryOperation.prototype.stop = function() {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      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.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(this._errors.length - 1, this._errors.length);
          this._timeouts = this._cachedTimeouts.slice(0);
          timeout = this._timeouts.shift();
        } else {
          return false;
        }
      }
      var self = this;
      var 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) {
          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;
    };

    var retry$1 = createCommonjsModule(function (module, exports) {
    exports.operation = function(options) {
      var timeouts = exports.timeouts(options);
      return new retry_operation(timeouts, {
          forever: options && options.forever,
          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 * opts.minTimeout * 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$1.operation;
    retry$1.timeouts;
    retry$1.createTimeout;
    retry$1.wrap;

    var retry = retry$1;

    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$m(WebSocketSubject, _super);
        function WebSocketSubject(urlConfigOrSource, destination) {
            var _this = _super.call(this) || this;
            if (urlConfigOrSource instanceof Observable) {
                _this.destination = destination;
                _this.source = urlConfigOrSource;
            }
            else {
                var config = _this._config = __assign$5({}, 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(function (x) {
                    try {
                        if (messageFilter(x)) {
                            observer.next(x);
                        }
                    }
                    catch (err) {
                        observer.error(err);
                    }
                }, function (err) { return observer.error(err); }, 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 (e) {
                var _socket = _this._socket;
                if (!_socket) {
                    socket.close();
                    _this._resetState();
                    return;
                }
                var openObserver = _this._config.openObserver;
                if (openObserver) {
                    openObserver.next(e);
                }
                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 (e) {
                    var closingObserver = _this._config.closingObserver;
                    if (closingObserver) {
                        closingObserver.next(undefined);
                    }
                    if (e && e.code) {
                        socket.close(e.code, e.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) {
                _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.close();
                    }
                    _this._resetState();
                }
            });
            return subscriber;
        };
        WebSocketSubject.prototype.unsubscribe = function () {
            var _socket = this._socket;
            if (_socket && _socket.readyState === 1) {
                _socket.close();
            }
            this._resetState();
            _super.prototype.unsubscribe.call(this);
        };
        return WebSocketSubject;
    }(AnonymousSubject));

    var __extends$6 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$7 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$7 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var RxWebsocketSubject =  (function (_super) {
        __extends$6(RxWebsocketSubject, _super);
        function RxWebsocketSubject(
        client,
        retryOptions,
        retryWait,
        urlGenerator,
        webSocketSubjectConfig,
        deserializer,
        serializer) {
            var _this = _super.call(this) || this;
            _this.retryOptions = retryOptions;
            _this.retryWait = retryWait;
            _this.urlGenerator = urlGenerator;
            _this.webSocketSubjectConfig = webSocketSubjectConfig;
            _this.deserializer = deserializer;
            _this.serializer = serializer;
            _this.log = Log$1.of("transport:socket", client);
            _this.connectionStatus = new Observable(function (observer) {
                _this.connectionObserver = observer;
            }).pipe(share(), distinctUntilChanged());
            if (!deserializer) {
                _this.deserializer = function (e) {
                    return JSON.parse(e.data);
                };
            }
            if (!_this.serializer) {
                _this.serializer = function (data) {
                    return JSON.stringify(data, MapOrSet_toJSON);
                };
            }
            _this.wsSubjectConfig = {
                url: null,
                closingObserver: webSocketSubjectConfig.closingObserver,
                closeObserver: {
                    next: function (e) {
                        _this.closeEvent = e;
                        _this.internalDisconnect();
                        _this.socket = null;
                        _this.webSocketSubjectConfig.closeObserver.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;
                        }
                        _this.connectionObserver.next(false);
                    },
                },
                openObserver: {
                    next: function (e) {
                        _this.closeEvent = null;
                        _this.connectionObserver.next(true);
                        _this.webSocketSubjectConfig.openObserver.next(e);
                    },
                },
                deserializer: _this.deserializer,
                serializer: _this.serializer,
            };
            _this.connect();
            return _this;
        }
        RxWebsocketSubject.prototype.protocolReady = function () {
            if (this.operation) {
                this.operation.reset();
                var operationErrors = this.operation.errors();
                if (operationErrors && operationErrors.length) {
                    operationErrors.splice(0, operationErrors.length);
                }
                this.reconnecting = false;
            }
        };
        RxWebsocketSubject.prototype.disconnect = function () {
            this.log.info("Disconnet from ws");
            this.operation.stop();
            var operationErrors = this.operation.errors();
            if (operationErrors && operationErrors.length) {
                operationErrors.splice(0, operationErrors.length);
            }
            this.operation = null;
            this.reconnecting = false;
            this.internalDisconnect();
        };
        RxWebsocketSubject.prototype.connect = function () {
            if (!this.operation) {
                this.log.info("Connect to ws");
                this.operation = retry.operation(this.retryOptions);
                this.operation.attempt(this.internalConnect.bind(this));
            }
        };
        RxWebsocketSubject.prototype.internalDisconnect = function () {
            if (this.socket) {
                this.socket.unsubscribe();
            }
        };
        RxWebsocketSubject.prototype.internalConnect = function (currentAttempt) {
            var _a;
            return __awaiter$7(this, void 0, void 0, function () {
                var e_1;
                var _this = this;
                return __generator$7(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            this.log.info("Attempt ".concat(currentAttempt, " to connect to ws"));
                            this.wsSubjectConfig.url = this.webSocketSubjectConfig.url || this.urlGenerator();
                            this.internalDisconnect();
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 3, , 4]);
                            return [4 , this.retryWait(this.closeEvent, currentAttempt)];
                        case 2:
                            if (!(_b.sent())) {
                                this.log.info("retryWait return false, stop reconnecting");
                                this.operation.stop();
                                this.operation = null;
                                this.reconnecting = false;
                                return [2 ];
                            }
                            return [3 , 4];
                        case 3:
                            e_1 = _b.sent();
                            (_a = this.operation) === null || _a === void 0 ? void 0 : _a.retry({ name: String(e_1.code), message: e_1.reason });
                            return [2 ];
                        case 4:
                            this.socket = new WebSocketSubject(this.wsSubjectConfig);
                            this.socket.subscribe(function (message) {
                                try {
                                    _this.next(message);
                                }
                                catch (err) {
                                    _this.log.error("Unhandled error", err);
                                }
                            }, function (err) {
                                _this.log.error("Socket error", err);
                            });
                            return [2 ];
                    }
                });
            });
        };
        RxWebsocketSubject.prototype.send = function (message) {
            if (this.socket) {
                this.socket.next(message);
            }
            else {
                this.log.error("Unable to send, socket is not connected");
            }
            return this;
        };
        return RxWebsocketSubject;
    }(Subject));

    var client = createCommonjsModule(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.CrossStorageClient;

    var hub = createCommonjsModule(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.CrossStorageHub;

    var lib = {
      CrossStorageClient: client,
      CrossStorageHub:    hub
    };
    var lib_1 = lib.CrossStorageClient;

    var __extends$5 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$6 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$6 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var __spreadArray$1 = (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 Heartbeat =  (function () {
        function Heartbeat(
        heartbeatInterval) {
            this.heartbeatInterval = heartbeatInterval;
            this.heartbeatCheckId = null;
            this.connected = false;
        }
        Heartbeat.prototype.setConnected = function (connected) {
            this.connected = connected;
        };
        Heartbeat.prototype.setTransportSocket = function (transportSocket) {
            this.transportSocket = transportSocket;
        };
        Heartbeat.prototype.heartbeat = function () {
            var _this = this;
            if (this.heartbeatCheckId)
                clearTimeout(this.heartbeatCheckId);
            this.heartbeatCheckId = setTimeout(function () {
                if (_this.connected && _this.transportSocket) {
                    _this.transportSocket.send("ping");
                    _this.heartbeat();
                }
            }, this.heartbeatInterval);
        };
        return Heartbeat;
    }());
    var AbstractJsonRpcWebsocket =  (function () {
        function AbstractJsonRpcWebsocket(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();
            }
        }
        AbstractJsonRpcWebsocket.prototype.retryWait = function (event, retries) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    return [2 , true];
                });
            });
        };
        AbstractJsonRpcWebsocket.prototype.getCrossStorage = function () {
            return this.crossStorage;
        };
        AbstractJsonRpcWebsocket.prototype.initCrossStorage = function () {
            return __awaiter$6(this, void 0, void 0, function () {
                var result;
                var _this = this;
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.crossStorage = new CrossStorageManager(this.client, this, this.crossStorageUrl, function () { return _this.crossStorageEnabled; }, function (idRequest) { return _this.getResponseOf(idRequest); }, function () { return _this.getNewIdRequest(); }, function () { return _this.webSocketConnect(); }, function () { return _this.webSocketDisconnect(); }, function (response) { return _this.socketMessage.next(response); }, function (message) { var _a; return (_a = _this.transportSocket) === null || _a === void 0 ? void 0 : _a.send(message); }, this.connectionEventSubject);
                            return [4 , this.crossStorage.connect()];
                        case 1:
                            _a.sent();
                            if (!(this.crossStorage.getLevel() === Storagelevel.slave)) return [3 , 3];
                            return [4 , this.crossStorage.getStorage().get(ConnectionKey.commonMethodsMessage)];
                        case 2:
                            result = _a.sent();
                            if (result) {
                                this.crossStorage.commonMethodsRequestMap.fromJSON(JSON.parse(result));
                            }
                            this.connectionEventSubject.next({ connected: true });
                            _a.label = 3;
                        case 3: return [2 ];
                    }
                });
            });
        };
        AbstractJsonRpcWebsocket.prototype.disconnect = function () {
            if (this.crossStorage) {
                this.crossStorageEnabled = false;
                this.crossStorage.disconnect();
            }
            else {
                this.webSocketDisconnect();
            }
        };
        AbstractJsonRpcWebsocket.prototype.connect = function () {
            if (this.crossStorageUrl) {
                this.crossStorageEnabled = true;
            }
            else {
                this.webSocketConnect();
            }
        };
        AbstractJsonRpcWebsocket.prototype.getResponseOf = function (idRequest) {
            var requestData = this.requestExecuted.get(idRequest);
            if (!requestData) {
                requestData = new RequestData(null, null, null, null, null);
                requestData.identifier = new RequestIdentifier(idRequest);
                this.requestExecuted.set(idRequest, requestData);
            }
            return requestData.response;
        };
        AbstractJsonRpcWebsocket.prototype.handleResponseMessage = function (response) {
            if (response.hasOwnProperty("id")) {
                var 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);
                    }
                }
            }
        };
        AbstractJsonRpcWebsocket.prototype.webSocketConnect = function () {
            var _this = this;
            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;
            }
            var url = this.client.generateWsUrl();
            this.log.debug("connection ws to '".concat(url, "'"));
            this.webSocketDisconnect();
            this.transportSocket = new RxWebsocketSubject(this.client, this.retryOptions, this.retryWait.bind(this), function () { return _this.client.generateWsUrl(); }, {
                url: "",
                closeObserver: {
                    next: function (e) {
                        _this.log.debug("ws closed, code ".concat(e.code));
                        _this.onClose(e);
                    },
                },
                openObserver: {
                    next: function () {
                        _this.log.debug("ws open");
                        _this.onOpen();
                    },
                },
            }, function (message) {
                try {
                    var 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 };
                }
            }, function (request) {
                var webSocketMessage;
                if (request instanceof RequestData) {
                    var jsonRpcMessage = { id: request.identifier.idRequest, method: request.method, params: request.params };
                    _this.logRequest.debug(" --> ", jsonRpcMessage, { requestTimeout: request.options.requestTimeout });
                    webSocketMessage = JSON.stringify(jsonRpcMessage, MapOrSet_toJSON);
                }
                else {
                    webSocketMessage = request;
                }
                return webSocketMessage;
            });
            this.transportSocket.subscribe(function (data) { return _this.socketMessage.next(data); });
            this.transportSocket.connectionStatus.subscribe(function (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();
        };
        AbstractJsonRpcWebsocket.prototype.webSocketDisconnect = function () {
            if (this.transportSocket && this.connected) {
                this.log.debug("force disconnect previous socket");
                this.transportSocket.disconnect();
                this.transportSocket.unsubscribe();
                this.transportSocket = undefined;
            }
        };
        AbstractJsonRpcWebsocket.prototype.errorTimeoutToWebapiException = function (request) {
            var _this = this;
            return function (e) {
                if (e instanceof TimeoutError) {
                    _this.log.error("Timeout occurred, startTime ".concat(request.requestTime ? Log$1.getPrefixTimestamp(request.requestTime) : null, " - timeout ").concat(request.options.requestTimeout, " ms - id ").concat(request.identifier.idRequest, " - method ").concat(request.method));
                    throw new TimeoutResponse();
                }
                else {
                    throw e;
                }
            };
        };
        AbstractJsonRpcWebsocket.prototype.waitSendRequest = function (requestData) {
            return __awaiter$6(this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                return [2 ];
            }); });
        };
        AbstractJsonRpcWebsocket.prototype.getNewIdRequest = function () {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    if (this.currentIdRequest === Number.MAX_SAFE_INTEGER) {
                        this.log.info("Reached Number.MAX_SAFE_INTEGER for idRequest, reset to 1000");
                        this.currentIdRequest = 999;
                    }
                    return [2 , new RequestIdentifier(++this.currentIdRequest)];
                });
            });
        };
        AbstractJsonRpcWebsocket.prototype.stopCurrentRequestWithException = function (exception) {
            this.stopActiveRequest.next(exception);
        };
        AbstractJsonRpcWebsocket.prototype.generateSyncFromRequest = function (request) {
            var _this = this;
            var response = merge(request.response.result,
            this.stopActiveRequest.asObservable().pipe(switchMap(function (exception) { return throwError(exception); }))).pipe(timeout(request.options.requestTimeout),
            catchError(this.errorTimeoutToWebapiException(request)));
            var result;
            if (request.responseIsChunked) {
                result = new Observable(function (chunckedResponse) {
                    var subscription = response.subscribe({
                        next: function (_data) {
                            var data = _data;
                            if (data.cRes) {
                                var pos_1 = data.i - data.cRes.length;
                                data.cRes.forEach(function (d) { return chunckedResponse.next({ tot: data.tot, i: ++pos_1, data: d }); });
                            }
                            if (data.part === "END") {
                                chunckedResponse.complete();
                                subscription.unsubscribe();
                            }
                        },
                        error: function (err) {
                            setTimeout(function () {
                                try {
                                    chunckedResponse.error(err);
                                }
                                catch (e) {
                                    if (e === err) {
                                        _this.log.error("Error received but not handled ", request.identifier.idRequest, ", method ", request.method);
                                    }
                                    else {
                                        throw e;
                                    }
                                }
                            });
                        },
                    });
                    return function () { return subscription.unsubscribe(); };
                });
            }
            else {
                result = response.pipe(take(1));
            }
            return result.pipe(finalize(function () { return _this.emitEventComplete(request, false); }));
        };
        AbstractJsonRpcWebsocket.prototype.requestInternal = function (method, params, options, responseIsChunked, activateNotification) {
            var _this = this;
            var _a;
            var timeoutparsed = parseInt("".concat(options === null || options === void 0 ? void 0 : options.requestTimeout));
            var requestOptions = { requestTimeout: isNaN(timeoutparsed) || timeoutparsed <= 0 ? this.getRequestTimeout() : timeoutparsed, priorityOnRestart: (_a = options === null || options === void 0 ? void 0 : options.priorityOnRestart) !== null && _a !== void 0 ? _a : 0 };
            var stopResult;
            var stopNotification;
            var resultSyncSubscription = Subscription.EMPTY;
            var request = new RequestData(method, params, requestOptions, activateNotification, responseIsChunked);
            var resultSync = request.response.resultSync.asObservable().pipe(tap(function () {
                _this.log.debug("resultSync - emit", request.compact());
            }), finalize(function () {
                _this.log.debug("resultSync - complete", request.compact());
            }), share());
            var responseData = {
                result: new Observable(function (observer) {
                    var firstResponseComplete;
                    resultSyncSubscription = resultSync
                        .pipe(finalize(function () {
                        firstResponseComplete = undefined;
                    }), concatMap(function (response) {
                        if (observer.closed) {
                            _this.log.warn("resultSync - result is lost due to previous result complete at '".concat(firstResponseComplete, "', subscribe to resultSync to handle all result"), request.compact());
                            return response;
                        }
                        else {
                            var sharedResponse = response.pipe(finalize(function () {
                                firstResponseComplete = new Date();
                            }), share());
                            sharedResponse.subscribe(observer);
                            return sharedResponse;
                        }
                    }))
                        .subscribe();
                }),
                notification: EMPTY,
                resultSync: resultSync,
            };
            var createRequestData = new Observable(function (observer) {
                from(_this.waitSendRequest(request)).subscribe(observer);
            }).pipe(concatMap(function () { return __awaiter$6(_this, void 0, void 0, function () {
                var _a;
                return __generator$6(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _a = request;
                            return [4 , this.getNewIdRequest()];
                        case 1:
                            _a.identifier = _b.sent();
                            return [2 ];
                    }
                });
            }); }));
            if (activateNotification) {
                createRequestData = createRequestData.pipe(shareReplay(1));
                var resultNotificationSubscription_1 = Subscription.EMPTY;
                var stopNotificationIsRequest_1 = false;
                var stopNotificationAction_1 = null;
                stopNotification = function () { return __awaiter$6(_this, void 0, void 0, function () {
                    var result;
                    return __generator$6(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                stopNotificationIsRequest_1 = true;
                                result = true;
                                if (!stopNotificationAction_1) return [3 , 2];
                                return [4 , stopNotificationAction_1()];
                            case 1:
                                result = _a.sent();
                                if (result) {
                                    stopNotificationAction_1 = null;
                                    resultNotificationSubscription_1.unsubscribe();
                                    this.completeRequestExecution(request);
                                }
                                return [3 , 3];
                            case 2:
                                this.completeRequestExecution(request);
                                _a.label = 3;
                            case 3: return [2 , result];
                        }
                    });
                }); };
                responseData.notification = createRequestData.pipe(switchMap(function () {
                    if (stopNotificationIsRequest_1) {
                        _this.log.debug("Stop notification of method '".concat(method, "' was called before subscribe, return EMPTY observable"));
                        return EMPTY;
                    }
                    else {
                        return new Observable(function (observer) {
                            stopNotificationAction_1 = function () { return __awaiter$6(_this, void 0, void 0, function () {
                                var response, err_1;
                                return __generator$6(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            this.log.debug("Stop notification ".concat(request.identifier.idRequest, ", method ").concat(method));
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 3, , 4]);
                                            return [4 , this.requestInternal("stopNotification", [request.identifier.idRequest], null, false, false).response.result.toPromise()];
                                        case 2:
                                            response = _a.sent();
                                            this.log.debug("Notification ".concat(request.identifier.idRequest, " ").concat(response ? "correctly" : "not", " stopped"));
                                            this.emitEventComplete(request, true);
                                            return [2 , response];
                                        case 3:
                                            err_1 = _a.sent();
                                            this.log.error("Notification ".concat(request.identifier.idRequest, " failed stopped"), err_1);
                                            return [2 , false];
                                        case 4: return [2 ];
                                    }
                                });
                            }); };
                            (function () { return __awaiter$6(_this, void 0, void 0, function () {
                                var err_2;
                                return __generator$6(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            resultNotificationSubscription_1.unsubscribe();
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 3, , 4]);
                                            resultNotificationSubscription_1 = request.response.notification.subscribe(observer);
                                            return [4 , this.execRequest(request)];
                                        case 2:
                                            _a.sent();
                                            return [3 , 4];
                                        case 3:
                                            err_2 = _a.sent();
                                            this.log.error("Error on activate result notification", err_2);
                                            observer.error(err_2);
                                            stopNotification();
                                            return [3 , 4];
                                        case 4: return [2 ];
                                    }
                                });
                            }); })();
                            return function () { return stopNotification(); };
                        });
                    }
                }));
            }
            var resultSubscription = Subscription.EMPTY;
            stopResult = function () { return __awaiter$6(_this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    resultSubscription.unsubscribe();
                    if (!activateNotification) {
                        resultSyncSubscription.unsubscribe();
                    }
                    return [2 , true];
                });
            }); };
            request.buildResponse = function (forceSend) {
                var result = {
                    response: undefined,
                    sent: undefined,
                };
                result.sent = new Promise(function (sentDone, sentError) {
                    result.response = createRequestData.pipe(switchMap(function () {
                        return new Observable(function (observer) {
                            (function () { return __awaiter$6(_this, void 0, void 0, function () {
                                var err_3;
                                var _this = this;
                                return __generator$6(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            resultSubscription.unsubscribe();
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 3, , 4]);
                                            resultSubscription = this.generateSyncFromRequest(request)
                                                .pipe(finalize(function () { return (!request.withNotification ? _this.completeRequestExecution(request) : null); }))
                                                .subscribe(observer);
                                            return [4 , this.execRequest(request, forceSend)];
                                        case 2:
                                            _a.sent();
                                            sentDone();
                                            return [3 , 4];
                                        case 3:
                                            err_3 = _a.sent();
                                            sentError(err_3);
                                            this.log.error("Error on activate result", err_3);
                                            observer.error(err_3);
                                            stopResult();
                                            return [3 , 4];
                                        case 4: return [2 ];
                                    }
                                });
                            }); })();
                            return function () { return stopResult(); };
                        }).pipe(catchError(function (error) {
                            stopNotification === null || stopNotification === void 0 ? void 0 : stopNotification();
                            throw error;
                        }), finalize(function () { return stopResult(); }));
                    }));
                });
                return result;
            };
            request.newResponse();
            return {
                response: responseData,
                toLiveResult: function () {
                    return {
                        result: responseData.result,
                        notification: responseData.notification,
                        resultSync: responseData.resultSync,
                        stopResult: function () { return __awaiter$6(_this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                            return [2 , stopResult === null || stopResult === void 0 ? void 0 : stopResult()];
                        }); }); },
                        stopNotification: function () { return __awaiter$6(_this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                            return [2 , stopNotification === null || stopNotification === void 0 ? void 0 : stopNotification()];
                        }); }); },
                    };
                },
            };
        };
        AbstractJsonRpcWebsocket.prototype.execRequest = function (request, force) {
            var _a;
            return __awaiter$6(this, void 0, void 0, function () {
                var requestIdentifier;
                return __generator$6(this, function (_b) {
                    if (!request.identifier)
                        throw new Error("Error on send ".concat(request.method, ", identifier is unset"));
                    requestIdentifier = this.requestExecuted.get(request.identifier.idRequest);
                    if (requestIdentifier) {
                        if (!force) {
                            this.log.warn("Unable to execRequest of method ".concat(request.method, ", id ").concat(request.identifier.idRequest, " was used by previous method ").concat(requestIdentifier.method, " at ").concat(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);
                    }
                    return [2 ];
                });
            });
        };
        AbstractJsonRpcWebsocket.prototype.completeRequestExecution = function (request) {
            if (request.executed && request.identifier) {
                var requestData = this.requestExecuted.get(request.identifier.idRequest);
                if (requestData) {
                    this.requestExecuted.delete(request.identifier.idRequest);
                    requestData.complete();
                }
            }
        };
        AbstractJsonRpcWebsocket.prototype.emitEventComplete = function (request, isNotification) {
            if (this.crossStorage && request.identifier) {
                this.crossStorage.emitEventComplete(request.identifier, isNotification);
            }
        };
        AbstractJsonRpcWebsocket.prototype.emitErrorInternal = function (error, activateNotification) {
            var _this = this;
            var response = {
                result: throwError(error),
                notification: throwError(error),
                resultSync: throwError(error),
            };
            return {
                response: response,
                toLiveResult: function () {
                    return {
                        result: response.result,
                        notification: response.notification,
                        resultSync: response.resultSync,
                        stopResult: function () { return __awaiter$6(_this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                            return [2 , false];
                        }); }); },
                        stopNotification: function () { return __awaiter$6(_this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                            return [2 , false];
                        }); }); },
                    };
                },
            };
        };
        AbstractJsonRpcWebsocket.prototype.resendActiveNotification = function () {
            return __awaiter$6(this, void 0, void 0, function () {
                var _this = this;
                return __generator$6(this, function (_a) {
                    return [2 , from(Array.from(this.requestExecuted.values())
                            .filter(function (request) { return request && request.method && request.executed && request.withNotification; })
                            .sort(function (r1, r2) { return (r1.options.priorityOnRestart === r2.options.priorityOnRestart ? 0 : r1.options.priorityOnRestart < r2.options.priorityOnRestart ? 1 : -1); }))
                            .pipe(concatMap(function (request) { return __awaiter$6(_this, void 0, void 0, function () {
                            var _a, _b, err_4;
                            return __generator$6(this, function (_c) {
                                switch (_c.label) {
                                    case 0:
                                        _c.trys.push([0, 3, , 4]);
                                        _a = this.elaborateResponseFromRevival;
                                        _b = [request];
                                        return [4 , request.newResponse(true)];
                                    case 1: return [4 , _a.apply(this, _b.concat([_c.sent()]))];
                                    case 2:
                                        _c.sent();
                                        return [3 , 4];
                                    case 3:
                                        err_4 = _c.sent();
                                        this.log.error("Error on resend active notification - ".concat(JSON.stringify(request.compact(), MapOrSet_toJSON)), err_4);
                                        return [3 , 4];
                                    case 4: return [2 ];
                                }
                            });
                        }); }), last())
                            .toPromise()];
                });
            });
        };
        AbstractJsonRpcWebsocket.prototype.elaborateResponseFromRevival = function (request, response) {
            return __awaiter$6(this, void 0, void 0, function () { return __generator$6(this, function (_a) {
                return [2 ];
            }); });
        };
        AbstractJsonRpcWebsocket.prototype.request = function (method, params, options, responseIsChunked, activateNotification) {
            return this.requestInternal(method, params, options, responseIsChunked, activateNotification);
        };
        AbstractJsonRpcWebsocket.prototype.emitError = function (error, activateNotification) {
            return this.emitErrorInternal(error, activateNotification);
        };
        return AbstractJsonRpcWebsocket;
    }());
    var CrossStorageMessage =  (function () {
        function CrossStorageMessage(manager, eventHandler) {
            this.manager = manager;
            this.eventHandler = eventHandler;
        }
        CrossStorageMessage.prototype.notify = function (key, message) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , this.manager.getStorage().set(key, JSON.stringify(message, MapOrSet_toJSON))];
                        case 1:
                            _a.sent();
                            return [2 , message];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.retrive = function (connectionKey) {
            return this.manager.getStorage().get(connectionKey);
        };
        CrossStorageMessage.prototype.ping = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , this.notify(ConnectionKey.pingToMaster, new StorageMessage(this.manager.getStorage()._id, message))];
                        case 1: return [2 , (_a.sent()).message];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.pong = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , this.notify(ConnectionKey.pongToSlave, new StorageMessage(this.manager.getStorage()._id, message))];
                        case 1: return [2 , (_a.sent()).message];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.notifyHierarchy = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b, _c, _d;
                return __generator$6(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.hierarchy];
                            _c = StorageMessage.bind;
                            _d = [void 0, this.manager.getStorage()._id];
                            return [4 , this.eventHandler.hierarchy(message)];
                        case 1: return [4 , _a.apply(this, _b.concat([new (_c.apply(StorageMessage, _d.concat([_e.sent()])))()]))];
                        case 2: return [2 , (_e.sent()).message];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.notifyCommonMethodsMap = function (message) {
            return this.notify(ConnectionKey.commonMethodsMessage, message);
        };
        CrossStorageMessage.prototype.decodePing = function (message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        };
        CrossStorageMessage.prototype.decodePong = function (message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        };
        CrossStorageMessage.prototype.decodeHierarchy = function (message) {
            return message ? StorageMessage.fromStringMessage(message).message : null;
        };
        CrossStorageMessage.prototype.notifyWsResponse = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.fromWsResponse];
                            return [4 , this.eventHandler.fromWsResponse(this.decodeWsResponse(JSON.stringify(message, MapOrSet_toJSON)))];
                        case 1: return [2 , _a.apply(this, _b.concat([_c.sent()]))];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.decodeWsResponse = function (message) {
            var _a, _b, _c, _d, _e, _f;
            var 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;
        };
        CrossStorageMessage.prototype.notifyWsRequestId = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.fromWsRequestId];
                            return [4 , this.eventHandler.fromWsRequestId(this.decodeWsRequestId(JSON.stringify(message, MapOrSet_toJSON)))];
                        case 1: return [2 , _a.apply(this, _b.concat([_c.sent()]))];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.notifyWsRequestIdUpdate = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.fromWsRequestIdUpdate];
                            return [4 , this.eventHandler.fromWsRequestIdUpdate(JSON.parse(JSON.stringify(message, MapOrSet_toJSON)))];
                        case 1: return [2 , _a.apply(this, _b.concat([_c.sent()]))];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.decodeWsRequestId = function (message) {
            var _a, _b, _c, _d;
            var 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;
        };
        CrossStorageMessage.prototype.notifyWsRequestComplete = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.toWsRequestComplete];
                            return [4 , this.eventHandler.toWsRequestComplete(this.decodeWsRequestComplete(JSON.stringify(message, MapOrSet_toJSON)))];
                        case 1: return [2 , _a.apply(this, _b.concat([_c.sent()]))];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.decodeWsRequestComplete = function (message) {
            var _a, _b, _c, _d;
            var 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;
        };
        CrossStorageMessage.prototype.notifyWsRequest = function (message) {
            return __awaiter$6(this, void 0, void 0, function () {
                var _a, _b;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _a = this.notify;
                            _b = [ConnectionKey.toWsRequest];
                            return [4 , this.eventHandler.toWsRequest(this.decodeWsRequest(JSON.stringify(message, MapOrSet_toJSON)))];
                        case 1: return [2 , _a.apply(this, _b.concat([_c.sent()]))];
                    }
                });
            });
        };
        CrossStorageMessage.prototype.decodeWsRequest = function (message) {
            var _a;
            var 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;
        };
        CrossStorageMessage.prototype.decodeCommonMethodsMap = function (message) {
            return message ? JSON.parse(message) : null;
        };
        return CrossStorageMessage;
    }());
    var CrossStorageHeartBeat =  (function () {
        function CrossStorageHeartBeat(client, manger, onHeartBeatEnd, onHeartBeatOk, pongTimeout, pingInterval) {
            if (pongTimeout === void 0) { pongTimeout = 500; }
            if (pingInterval === void 0) { 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);
        }
        CrossStorageHeartBeat.prototype.stop = function () {
            this.pongSubscription.unsubscribe();
            this.started = false;
        };
        CrossStorageHeartBeat.prototype.stopCheck = function () {
            this.checkSubscription.unsubscribe();
        };
        CrossStorageHeartBeat.prototype.start = function () {
            var _this = this;
            if (this.manger.getLevel() != Storagelevel.master) {
                this.started = true;
                this.log.info("PING");
                var idPing_1 = new Date().toISOString();
                this.pongSubscription.unsubscribe();
                this.pongSubscription = this.manger
                    .getPongObserver()
                    .pipe(filter(function (pong) { return pong.id_pong === idPing_1; }), timeout(this.pongTimeout), take(1))
                    .subscribe(function () {
                    _this.log.info("PONG");
                    _this.errorCounter = 0;
                    setTimeout(function () { return _this.start(); }, _this.pingInterval);
                }, function (err) {
                    _this.errorCounter++;
                    _this.log.warn("PONG lost");
                    if (_this.errorCounter < 3) {
                        setTimeout(function () { return _this.start(); }, 200);
                    }
                    else {
                        _this.onHeartBeatEnd(err);
                        _this.log.error("no PONG response");
                    }
                });
                this.manger.ping({ id_ping: idPing_1 });
            }
            else {
                this.stop();
            }
        };
        CrossStorageHeartBeat.prototype.check = function () {
            var _this = this;
            this.log.info("PING check master");
            var idPing = new Date().toISOString();
            this.checkSubscription.unsubscribe();
            this.checkSubscription = this.manger
                .getPongObserver()
                .pipe(filter(function (pong) { return pong.id_pong === idPing; }), timeout(this.pongTimeout), take(1))
                .subscribe(function () {
                _this.onHeartBeatOk(true);
                _this.log.info("PONG check master");
            }, function () {
                _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 });
        };
        CrossStorageHeartBeat.prototype.getStarted = function () {
            return this.started;
        };
        return CrossStorageHeartBeat;
    }());
    var CrossStorageManager =  (function () {
        function CrossStorageManager(client,
        transport,
        crossStorageUrl,
        isCrossStorageEnabled,
        getResponseOf,
        getNewIdRequest,
        webSocketConnect,
        webSocketDisconnect,
        onResponse,
        sendToSocket,
        connectionEventSubject) {
            var _this = this;
            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: function (event) { return _this.message.decodePing(event.newValue); },
                pongToSlave: function (event) { return _this.message.decodePong(event.newValue); },
                hierarchy: function (event) { return _this.message.decodeHierarchy(event.newValue); },
                fromWsResponse: function (event) { return _this.message.decodeWsResponse(event === null || event === void 0 ? void 0 : event.newValue); },
                fromWsRequestId: function (event) { return _this.message.decodeWsRequestId(event === null || event === void 0 ? void 0 : event.newValue); },
                fromWsRequestIdUpdate: function (event) { return _this.message.decodeWsRequestId(event === null || event === void 0 ? void 0 : event.newValue); },
                toWsRequestComplete: function (event) { return _this.message.decodeWsRequestComplete(event === null || event === void 0 ? void 0 : event.newValue); },
                toWsRequest: function (event) { return _this.message.decodeWsRequest(event === null || event === void 0 ? void 0 : event.newValue); },
                CommonMethodsMessage: function (event) { return _this.message.decodeCommonMethodsMap(event.newValue); },
            };
            this.eventHandler = {
                pingToMaster: function (ping) {
                    if (_this.storageLevel === Storagelevel.master) {
                        _this.message.pong({
                            id_pong: ping.id_ping,
                            to_id: ping.from_id,
                        });
                    }
                    return Promise.resolve(ping);
                },
                pongToSlave: function (pong) {
                    if (pong.to_id === _this.crossStorage._id) {
                        _this.pongSubject.next(pong);
                    }
                    return Promise.resolve(pong);
                },
                hierarchy: function (hierarchy) {
                    return _this.updateHierarchy(hierarchy);
                },
                fromWsResponse: function (fromWsMessage) { return __awaiter$6(_this, void 0, void 0, function () {
                    var requestIdentifier, jsonRpcResponse;
                    return __generator$6(this, function (_a) {
                        if (fromWsMessage && fromWsMessage.to_ids.indexOf(this.crossStorage._id) > -1) {
                            requestIdentifier = this.slaveRequestMap.get(fromWsMessage.data.message.identifier.request.idRequest);
                            if (requestIdentifier) {
                                jsonRpcResponse = fromWsMessage.data.message.data;
                                if (jsonRpcResponse) {
                                    jsonRpcResponse.id = fromWsMessage.data.message.isNotification ? requestIdentifier.idNotification : requestIdentifier.idRequest;
                                    this.onResponse(jsonRpcResponse);
                                }
                            }
                        }
                        return [2 , fromWsMessage];
                    });
                }); },
                fromWsRequestId: function (toWsIdMessage) { return __awaiter$6(_this, void 0, void 0, function () {
                    var storagemsg;
                    return __generator$6(this, function (_a) {
                        if (toWsIdMessage && toWsIdMessage.to_ids.indexOf(this.crossStorage._id) > -1) {
                            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 [2 , toWsIdMessage];
                    });
                }); },
                fromWsRequestIdUpdate: function (toWsIdMessageUpdate) { return __awaiter$6(_this, void 0, void 0, function () {
                    var _this = this;
                    return __generator$6(this, function (_a) {
                        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(function (masterIdentification) {
                                var slaveRequestIdentification = _this.slaveRequestMap.get(masterIdentification.oldId);
                                if (slaveRequestIdentification) {
                                    _this.slaveRequestMap.set(masterIdentification.newId, slaveRequestIdentification);
                                    _this.slaveRequestMap.delete(masterIdentification.oldId);
                                    var 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 [2 , toWsIdMessageUpdate];
                    });
                }); },
                toWsRequestComplete: function (toWsCompleteMessage) { return __awaiter$6(_this, void 0, void 0, function () {
                    var idToRemove;
                    var _a;
                    return __generator$6(this, function (_b) {
                        if (this.storageLevel === Storagelevel.master) {
                            if (toWsCompleteMessage) {
                                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 [2 , toWsCompleteMessage];
                    });
                }); },
                toWsRequest: function (toWsMessage) { return __awaiter$6(_this, void 0, void 0, function () {
                    var storage_request, registerResult, realRequestIdentifier, data, registerRequest, requestIdentifierNotication, response, responseHandler_1, notificationResponseHandler_1, error_1;
                    var _a, _b;
                    return __generator$6(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                if (!(toWsMessage && this.storageLevel === Storagelevel.master)) return [3 , 9];
                                storage_request = toWsMessage.data.message;
                                _c.label = 1;
                            case 1:
                                _c.trys.push([1, 8, , 9]);
                                return [4 , this.registerRequest(toWsMessage.from_id, storage_request)];
                            case 2:
                                registerResult = _c.sent();
                                realRequestIdentifier = registerResult.identifier;
                                data = void 0;
                                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;
                                }
                                registerRequest = data.registerRequest;
                                requestIdentifierNotication = data.requestIdentifierNotication;
                                if (!registerRequest) return [3 , 4];
                                return [4 , this.message.notifyWsRequestIdUpdate(new FromWsMessage((_b = (_a = this.commonMethodsRequestMap.get(storage_request.method)) === null || _a === void 0 ? void 0 : _a.id_slaves) !== null && _b !== void 0 ? _b : [], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)))];
                            case 3:
                                _c.sent();
                                registerRequest.id_slaves.push(toWsMessage.from_id);
                                this.commonMethodsRequestMap.set(storage_request.method, new RegisterRequestObj(registerRequest.id_slaves, storage_request, requestIdentifierNotication));
                                this.notifyCommonMethodsMap();
                                return [3 , 5];
                            case 4:
                                if (this.notCommonMethods.indexOf(storage_request.method) < 0) {
                                    this.commonMethodsRequestMap.set(storage_request.method, new RegisterRequestObj([toWsMessage.from_id], storage_request, requestIdentifierNotication));
                                    this.notifyCommonMethodsMap();
                                }
                                _c.label = 5;
                            case 5: return [4 , this.message.notifyWsRequestId(new FromWsMessage([toWsMessage.from_id], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)))];
                            case 6:
                                _c.sent();
                                response = this.getResponseOf(requestIdentifierNotication.realRequest.idRequest).asObservable();
                                responseHandler_1 = this.notifyCrossStorageResponse(toWsMessage.from_id, false, storage_request.method, requestIdentifierNotication);
                                this.storageRequestMap.set(requestIdentifierNotication.realRequest.idRequest, response
                                    .pipe(filter(function (response) { return !responseIsNotification(response); }), concatMap(function (response) { return responseHandler_1(response); }))
                                    .subscribe());
                                if (storage_request.withNotification) {
                                    notificationResponseHandler_1 = this.notifyCrossStorageResponse(toWsMessage.from_id, true, storage_request.method, requestIdentifierNotication);
                                    this.storageRequestMap.set(requestIdentifierNotication.realRequest.idNotification, response
                                        .pipe(filter(function (response) { return responseIsNotification(response); }), concatMap(function (response) { return notificationResponseHandler_1(response); }))
                                        .subscribe());
                                }
                                storage_request.identifier.idRequest = requestIdentifierNotication.realRequest.idRequest;
                                return [4 , this.sendToSocket(storage_request)];
                            case 7:
                                _c.sent();
                                return [3 , 9];
                            case 8:
                                error_1 = _c.sent();
                                if (error_1 && error_1.stop) ;
                                else {
                                    console.log(error_1);
                                }
                                return [3 , 9];
                            case 9: return [2 , toWsMessage];
                        }
                    });
                }); },
                CommonMethodsMessage: function (commonMethodsMessage) { return __awaiter$6(_this, void 0, void 0, function () {
                    return __generator$6(this, function (_a) {
                        this.commonMethodsRequestMap.fromJSON(commonMethodsMessage);
                        return [2 , 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, function () {
                _this.masterReconnect();
            }, function (res) {
                _this.masterChecked.next(res);
            });
        }
        CrossStorageManager.prototype.getPongObserver = function () {
            return this.pongSubject.asObservable();
        };
        CrossStorageManager.prototype.getMessage = function () {
            return this.message;
        };
        CrossStorageManager.prototype.getStorage = function () {
            return this.crossStorage;
        };
        CrossStorageManager.prototype.getLevel = function () {
            return this.storageLevel;
        };
        CrossStorageManager.prototype.setString = function (key, value) {
            return this.crossStorage.set(key, value);
        };
        CrossStorageManager.prototype.setValue = function (key, value) {
            return this.crossStorage.set(key, JSON.stringify(value, MapOrSet_toJSON));
        };
        CrossStorageManager.prototype.getValue = function (key) {
            return this.crossStorage.get(key);
        };
        CrossStorageManager.prototype.disconnect = function () {
            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 });
            }
        };
        CrossStorageManager.prototype.connect = function () {
            return __awaiter$6(this, void 0, void 0, function () {
                var hierarchy, _a, _b;
                var _this = this;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            this.log.debug("connect with cross-Storage");
                            this.crossStorage = new lib_1(this.crossStorageUrl, { timeout: 30000 });
                            this.hierarchy = new HierarchyMessage(null, []);
                            return [4 , this.crossStorage.onConnect()];
                        case 1:
                            _c.sent();
                            this.crossStorage.listen(function (event) { return _this.storageEventHandler(event); });
                            _b = (_a = this.message).decodeHierarchy;
                            return [4 , this.message.retrive(ConnectionKey.hierarchy)];
                        case 2: return [4 , _b.apply(_a, [_c.sent()])];
                        case 3:
                            hierarchy = _c.sent();
                            this.hierarchy = hierarchy ? hierarchy : this.hierarchy;
                            return [4 , new Promise(function (resolve) {
                                    if (_this.hierarchy.connectionMaster) {
                                        _this.log.debug("There is a master");
                                        _this.masterChecked.subscribe(function (res) { return __awaiter$6(_this, void 0, void 0, function () {
                                            return __generator$6(this, function (_a) {
                                                switch (_a.label) {
                                                    case 0:
                                                        if (!res) return [3 , 1];
                                                        this.log.debug("connecting as slave");
                                                        this.storageLevel = Storagelevel.slave;
                                                        this.hierarchy.connectionSlave.push(this.crossStorage._id);
                                                        this.heartBeat.start();
                                                        resolve(true);
                                                        return [3 , 3];
                                                    case 1: return [4 , this.masterReconnect()];
                                                    case 2:
                                                        _a.sent();
                                                        resolve(false);
                                                        _a.label = 3;
                                                    case 3: return [2 ];
                                                }
                                            });
                                        }); }, function () { return __awaiter$6(_this, void 0, void 0, function () {
                                            return __generator$6(this, function (_a) {
                                                switch (_a.label) {
                                                    case 0: return [4 , this.masterReconnect()];
                                                    case 1:
                                                        _a.sent();
                                                        resolve(false);
                                                        return [2 ];
                                                }
                                            });
                                        }); });
                                        _this.heartBeat.check();
                                    }
                                    else {
                                        _this.log.debug("There isn't a master");
                                        _this.masterConnect();
                                        resolve(true);
                                    }
                                })];
                        case 4:
                            _c.sent();
                            return [2 , this.notifyHierarchy()];
                    }
                });
            });
        };
        CrossStorageManager.prototype.masterConnect = function () {
            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 = [];
        };
        CrossStorageManager.prototype.slaveConnect = function () {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    this.log.debug("connecting as slave");
                    this.storageLevel = Storagelevel.slave;
                    this.hierarchy.connectionSlave.push(this.crossStorage._id);
                    this.heartBeat.start();
                    return [2 , this.notifyHierarchy()];
                });
            });
        };
        CrossStorageManager.prototype.masterReconnect = function () {
            var _this = this;
            this.log.debug("Check if there are slaves alive");
            return new Promise(function (resolve) {
                _this.slaveChecked.pipe(timeout(1000)).subscribe(function () { return __awaiter$6(_this, void 0, void 0, function () {
                    var _this = this;
                    return __generator$6(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (this.slavesCheck.length) {
                                    this.slavesCheck.forEach(function (slave) {
                                        _this.hierarchy.connectionSlave.splice(_this.slavesCheck.indexOf(slave), 1);
                                    });
                                }
                                return [4 , this.reconnect()];
                            case 1:
                                _a.sent();
                                resolve(this.hierarchy);
                                return [2 ];
                        }
                    });
                }); }, function () { return __awaiter$6(_this, void 0, void 0, function () {
                    return __generator$6(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                this.hierarchy.connectionSlave = [];
                                return [4 , this.reconnect()];
                            case 1:
                                _a.sent();
                                resolve(this.hierarchy);
                                return [2 ];
                        }
                    });
                }); });
            });
        };
        CrossStorageManager.prototype.reconnect = function () {
            var _this = this;
            return new Promise(function (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(function (value, key) {
                        var requestData = value.request;
                        var 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);
            });
        };
        CrossStorageManager.prototype.clear = function () {
            for (var key in ConnectionKey) {
                this.crossStorage.del(ConnectionKey[key]);
            }
        };
        CrossStorageManager.prototype.storageEventHandler = function (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));
                }
            }
        };
        CrossStorageManager.prototype.notifyCrossStorageResponse = function (from_id, isNotification, method, identifier) {
            var _this = this;
            var _a, _b;
            var storagetMessageData = {
                identifier: identifier,
                isNotification: isNotification,
                data: null,
            };
            var 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];
            var result = new FromWsMessage(to_ids, new StorageMessage(this.crossStorage._id, storagetMessageData));
            return function (response) {
                var _a, _b, _c;
                storagetMessageData.data = response;
                if (_this.commonMethodsRequestMap.get(method)) {
                    var 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) {
                        var serviceMonitorResponse_1 = response.result;
                        if (last_responses) {
                            last_responses.forEach(function (last_response) {
                                last_response.result.cRes.forEach(function (serviceStatus) {
                                    if (serviceStatus.service === serviceMonitorResponse_1.service) {
                                        serviceStatus.status = serviceMonitorResponse_1.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 {
                            var request = _this.commonMethodsRequestMap.get(method);
                            if (request)
                                request.lastResponse = [response];
                        }
                    }
                }
                return _this.message.notifyWsResponse(result);
            };
        };
        CrossStorageManager.prototype.updateHierarchy = function (newHierarchy) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            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) return [3 , 3];
                            this.connectionEventSubject.next({ connected: false });
                            if (!this.hierarchy.connectionFutureMaster) return [3 , 3];
                            this.heartBeat.stop();
                            if (!(this.hierarchy.connectionFutureMaster == this.crossStorage._id)) return [3 , 3];
                            this.log.debug("I'm new master");
                            this.storageLevel = Storagelevel.futureMaster;
                            this.hierarchy.connectionFutureMaster = null;
                            return [4 , this.reconnect()];
                        case 1:
                            _a.sent();
                            return [4 , this.notifyHierarchy()];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [2 , newHierarchy];
                    }
                });
            });
        };
        CrossStorageManager.prototype.notifyHierarchy = function () {
            return this.message.notifyHierarchy(this.hierarchy);
        };
        CrossStorageManager.prototype.notifyCommonMethodsMap = function () {
            return this.message.notifyCommonMethodsMap(this.commonMethodsRequestMap);
        };
        CrossStorageManager.prototype.ping = function (message) {
            return this.message.ping({
                id_ping: message.id_ping,
                from_id: this.crossStorage._id,
            });
        };
        CrossStorageManager.prototype.emitEventComplete = function (request, isNotification) {
            return __awaiter$6(this, void 0, void 0, function () {
                var result, idToRemove, masterIdentifier;
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            result = null;
                            if (!(this.isCrossStorageEnabled() && this.storageLevel === Storagelevel.slave)) return [3 , 2];
                            idToRemove = isNotification ? request.idNotification : request.idRequest;
                            masterIdentifier = this.masterRequestMap.get(idToRemove);
                            if (!masterIdentifier) return [3 , 2];
                            return [4 , this.message.notifyWsRequestComplete(new ToWsMessage(this.crossStorage._id, new StorageMessage(this.crossStorage._id, { isNotification: isNotification, identifier: masterIdentifier })))];
                        case 1:
                            result = _a.sent();
                            this.masterRequestMap.delete(idToRemove);
                            this.slaveRequestMap.delete(isNotification ? masterIdentifier.idRequest : masterIdentifier.idNotification);
                            _a.label = 2;
                        case 2: return [2 , result];
                    }
                });
            });
        };
        CrossStorageManager.prototype.execRequest = function (request) {
            return __awaiter$6(this, void 0, void 0, function () {
                return __generator$6(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.isCrossStorageEnabled()  ) return [3 , 2];
                            return [4 , this.message.notifyWsRequest(new ToWsMessage(this.crossStorage._id, new StorageMessage(this.crossStorage._id, request)))];
                        case 1:
                            _a.sent();
                            return [2 , true];
                        case 2: return [2 , false];
                    }
                });
            });
        };
        CrossStorageManager.prototype.registerRequest = function (from_id, request) {
            var _a;
            return __awaiter$6(this, void 0, void 0, function () {
                var needSocketRequest, requestRegistered, currentParam, newParams, notifyWsRequestId, requestIdentifierNotication, notifyWsResponseArray_1, err_5;
                var _b;
                var _this = this;
                return __generator$6(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            needSocketRequest = true;
                            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)) return [3 , 8];
                            currentParam = __spreadArray$1([], request.params, true);
                            return [4 , (this.methodAnalizer[request.method] && requestRegistered.request ? this.methodAnalizer[request.method](currentParam, requestRegistered.request.params) : currentParam)];
                        case 1:
                            newParams = _c.sent();
                            notifyWsRequestId = false;
                            if (!newParams) return [3 , 2];
                            request.params.length = 0;
                            request.params.push.apply(request.params, newParams);
                            notifyWsRequestId = true;
                            return [3 , 4];
                        case 2:
                            (_a = this.commonMethodsRequestMap.get(request.method)) === null || _a === void 0 ? void 0 : _a.id_slaves.push(from_id);
                            requestIdentifierNotication = {
                                request: request.identifier,
                                realRequest: requestRegistered.requestIdentifierNotification.request,
                                activateNotification: requestRegistered.requestIdentifierNotification.activateNotification,
                            };
                            return [4 , this.message.notifyWsRequestId(new FromWsMessage([from_id], new StorageMessage(this.crossStorage._id, requestIdentifierNotication)))];
                        case 3:
                            _c.sent();
                            _c.label = 4;
                        case 4:
                            notifyWsResponseArray_1 = new Array();
                            if (!!notifyWsRequestId) return [3 , 8];
                            requestRegistered.lastResponse.forEach(function (response) {
                                var result = new FromWsMessage([from_id], new StorageMessage(_this.crossStorage._id, {
                                    identifier: requestRegistered.requestIdentifierNotification,
                                    isNotification: responseIsNotification(response),
                                    data: response,
                                }));
                                notifyWsResponseArray_1.push(_this.message.notifyWsResponse(result));
                            });
                            _c.label = 5;
                        case 5:
                            _c.trys.push([5, 7, , 8]);
                            return [4 , Promise.all(notifyWsResponseArray_1)];
                        case 6:
                            _c.sent();
                            needSocketRequest = false;
                            return [3 , 8];
                        case 7:
                            _c.sent();
                            return [3 , 8];
                        case 8:
                            _c.trys.push([8, 12, , 13]);
                            if (!needSocketRequest) return [3 , 10];
                            _b = {
                                isNew: needSocketRequest
                            };
                            return [4 , this.getNewIdRequest()];
                        case 9: return [2 , (_b.identifier = _c.sent(),
                                _b)];
                        case 10: return [2 , {
                                isNew: false,
                                identifier: null,
                            }];
                        case 11: return [3 , 13];
                        case 12:
                            err_5 = _c.sent();
                            this.log.error("Error on handle request joiner", err_5);
                            throw err_5;
                        case 13: return [2 ];
                    }
                });
            });
        };
        CrossStorageManager.prototype.resendRequest = function () {
            return Promise.resolve(true);
        };
        return CrossStorageManager;
    }());
    var CrossStorageMethodAnalizer =  (function () {
        function CrossStorageMethodAnalizer() {
        }
        CrossStorageMethodAnalizer.prototype.isChannelEnabled = function (newParams, oldParams) {
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.multiChannelServiceMonitor = function (newParams, oldParams) {
            if (oldParams) {
                if (newParams && newParams[0].type === oldParams[0].type) {
                    var 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);
        };
        CrossStorageMethodAnalizer.prototype.videoChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.callChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.chatChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.omnideskChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.callbackChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.mailChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.whatsappChannelServiceMonitor = function (newParams, oldParams) {
            var _a, _b;
            if (oldParams) {
                var 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);
        };
        CrossStorageMethodAnalizer.prototype.compareRequestParams = function (request_1, request_2) {
            if (request_1.length === request_2.length) {
                for (var 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 (var 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 (var index = 0; index < request_2.length; index++) {
                    if (request_1.indexOf(request_2[index]) < 0) {
                        return -1;
                    }
                }
                return 1;
            }
            else {
                return -1;
            }
        };
        return CrossStorageMethodAnalizer;
    }());
    var MyMap =  (function () {
        function MyMap() {
            this.data = new Map();
        }
        MyMap.prototype.get = function (key) {
            return this.data.get(key);
        };
        MyMap.prototype.set = function (key, value) {
            this.data.set(key, value);
        };
        MyMap.prototype.getSize = function () {
            return this.data.size;
        };
        MyMap.prototype.getMap = function () {
            return this.data;
        };
        MyMap.prototype.toJSON = function () {
            var obj = Object.create(null);
            this.data.forEach(function (value, key) {
                obj[key] = value;
            });
            return obj;
        };
        MyMap.prototype.delete = function (key) {
            this.data.delete(key);
        };
        MyMap.prototype.fromJSON = function (obj) {
            if (obj) {
                for (var key in obj) {
                    this.data.set(this.keyTransform(key), this.valueTransform(obj[key]));
                }
            }
        };
        return MyMap;
    }());
    var StringKeyMap =  (function (_super) {
        __extends$5(StringKeyMap, _super);
        function StringKeyMap() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        StringKeyMap.prototype.valueTransform = function (value) {
            return value;
        };
        StringKeyMap.prototype.keyTransform = function (key) {
            return key;
        };
        return StringKeyMap;
    }(MyMap));
    var RequestData =  (function () {
        function RequestData(method, params, options, withNotification, responseIsChunked) {
            this.method = method;
            this.params = params;
            this.options = options;
            this.withNotification = withNotification;
            this.responseIsChunked = responseIsChunked;
            this.response = new ResponseData();
        }
        RequestData.prototype.newResponse = function (forceSend) {
            var _a;
            return __awaiter$6(this, void 0, void 0, function () {
                var responseData, response;
                return __generator$6(this, function (_b) {
                    responseData = (_a = this.buildResponse) === null || _a === void 0 ? void 0 : _a.call(this, forceSend);
                    if (responseData) {
                        response = responseData.response.pipe(share());
                        this.response.resultSync.next(response);
                        return [2 , Promise.all([responseData.sent, response.pipe(take(1)).toPromise()]).then(function (_a) {
                                _a[0]; var result = _a[1];
                                return result;
                            })];
                    }
                    else {
                        throw new Error("Error on buildResponse - ".concat(JSON.stringify(this.compact(), MapOrSet_toJSON)));
                    }
                });
            });
        };
        RequestData.prototype.complete = function () {
            this.buildResponse = undefined;
            this.response.complete();
        };
        Object.defineProperty(RequestData.prototype, "executed", {
            get: function () {
                return !!this.requestTime;
            },
            enumerable: false,
            configurable: true
        });
        RequestData.prototype.compact = function () {
            var _a;
            return {
                id: (_a = this.identifier) === null || _a === void 0 ? void 0 : _a.idRequest,
                method: this.method,
                options: {
                    timeout: this.options.requestTimeout,
                    notification: this.withNotification,
                    chunked: this.responseIsChunked,
                },
            };
        };
        RequestData.prototype.toJSON = function () {
            return {
                method: this.method,
                params: this.params,
                requestTimeout: this.options.requestTimeout,
                withNotification: this.withNotification,
                responseIsChunked: this.responseIsChunked,
                identifier: this.identifier,
            };
        };
        RequestData.fromRequestData = function (requestData) {
            if (requestData) {
                if (requestData instanceof RequestData) {
                    return requestData;
                }
                else {
                    var requestDataInstance = new RequestData(requestData.method, requestData.params, requestData.options, requestData.withNotification, requestData.responseIsChunked);
                    requestDataInstance.identifier = new RequestIdentifier(requestData.identifier.idRequest);
                    return requestDataInstance;
                }
            }
            else {
                return requestData;
            }
        };
        return RequestData;
    }());
    var ResponseData =  (function (_super) {
        __extends$5(ResponseData, _super);
        function ResponseData() {
            var _a;
            var _this = _super.call(this) || this;
            _this.resultSync = new BehaviorSubject(null);
            _a = partition(_this.asObservable(), function (response) { return responseIsNotification(response); }).map(function (jsonRpcResponse) { return jsonRpcResponse.pipe(map(function (response) { return extractDataFromResponse(response); })); }), _this.notification = _a[0], _this.result = _a[1];
            return _this;
        }
        ResponseData.prototype.complete = function () {
            _super.prototype.complete.call(this);
            this.resultSync.complete();
        };
        return ResponseData;
    }(Subject));
    var RequestIdentifier =  (function () {
        function RequestIdentifier(idRequest) {
            this.idRequest = idRequest;
        }
        Object.defineProperty(RequestIdentifier.prototype, "idRequest", {
            get: function () {
                return this._idRequest;
            },
            set: function (idRequest) {
                this._idRequest = idRequest;
                if (idRequest && idRequest > 0) {
                    this._idNotification = -1 * idRequest;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RequestIdentifier.prototype, "idNotification", {
            get: function () {
                return this._idNotification;
            },
            set: function (idNotification) {
                this._idNotification = idNotification;
            },
            enumerable: false,
            configurable: true
        });
        RequestIdentifier.prototype.toJSON = function () {
            return {
                idRequest: this.idRequest,
                idNotification: this.idNotification,
            };
        };
        return RequestIdentifier;
    }());
    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 = {}));
    var RestoreSessionEvent =  (function () {
        function RestoreSessionEvent(state, error) {
            this.state = state;
            this.error = error;
            this.time = new Date();
        }
        Object.defineProperty(RestoreSessionEvent.prototype, "phase", {
            get: function () {
                return this._phase;
            },
            set: function (phase) {
                this._phase = phase;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RestoreSessionEvent.prototype, "phaseState", {
            get: function () {
                return this._phaseState;
            },
            set: function (phaseState) {
                this._phaseState = phaseState;
            },
            enumerable: false,
            configurable: true
        });
        return RestoreSessionEvent;
    }());

    var __extends$4 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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$2 = (undefined && undefined.__assign) || function () {
        __assign$2 = Object.assign || function(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$2.apply(this, arguments);
    };
    var __awaiter$5 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$5 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var JsonRpcWebsocket =  (function (_super) {
        __extends$4(JsonRpcWebsocket, _super);
        function JsonRpcWebsocket(
        client,
        loginRequest, connectionEventSubject, retryOptions, heartbeatInterval, storageUrl) {
            var _this = _super.call(this, client, connectionEventSubject, retryOptions, heartbeatInterval, storageUrl) || this;
            _this.client = client;
            _this.loginRequest = loginRequest;
            _this.stopOpenSocket = false;
            _this.onOpenSubscription = Subscription.EMPTY;
            _this.restoreSession = new JsonRpcWebsocketRestoreSession(function () {
                var revivalSessionTimeout = 90000;
                try {
                    var requestWithNotificationExecuted = Array.from(_this.requestExecuted.values()).filter(function (request) { return request.method && request.executed && request.withNotification; });
                    var requestWithNotificationAverageTimeout = requestWithNotificationExecuted.length ? requestWithNotificationExecuted.reduce(function (totalTimeout, request) { return totalTimeout + request.options.requestTimeout; }, 0) / requestWithNotificationExecuted.length : 0;
                    revivalSessionTimeout = Math.ceil(Math.max(revivalSessionTimeout, requestWithNotificationAverageTimeout * 4));
                }
                catch (e) { }
                _this.log.info("set revival session timeout to ".concat(revivalSessionTimeout, " ms"));
                return revivalSessionTimeout;
            });
            _this.restoreSession.event.subscribe(function (data) {
                if (data) {
                    var message = "restoreSession ".concat(data.state);
                    if (RestoreSessionState.progress === data.state) {
                        message += " - ".concat(data.phase, " - ").concat(data.phaseState);
                    }
                    if (data.error) {
                        _this.log.error(message, data.error);
                    }
                    else {
                        _this.log.debug(message);
                    }
                }
            });
            return _this;
        }
        Object.defineProperty(JsonRpcWebsocket.prototype, "restoreSessionEvent", {
            get: function () {
                return this.restoreSession.event;
            },
            enumerable: false,
            configurable: true
        });
        JsonRpcWebsocket.prototype.waitSendRequest = function (requestData) {
            return __awaiter$5(this, void 0, void 0, function () {
                return __generator$5(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this.restoreSession.inProgress && requestData.method !== "restartSessionId")) return [3 , 2];
                            this.log.debug("Method '".concat(requestData.method, "' will be called after restore connection complete"));
                            return [4 , this.restoreSession.waitEnd()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 ];
                    }
                });
            });
        };
        JsonRpcWebsocket.prototype.load = function () {
            return __awaiter$5(this, void 0, void 0, function () {
                return __generator$5(this, function (_a) {
                    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();
                    }
                    return [2 ];
                });
            });
        };
        JsonRpcWebsocket.prototype.getRequestTimeout = function () {
            return this.client.options.requestTimeout;
        };
        JsonRpcWebsocket.prototype.webSocketConnect = function () {
            var _a;
            if (!this.firstConnect && ((_a = this.transportSocket) === null || _a === void 0 ? void 0 : _a.reconnecting)) {
                this.restoreSession.start();
            }
            _super.prototype.webSocketConnect.call(this);
        };
        JsonRpcWebsocket.prototype.retryWait = function (event, retries) {
            return __awaiter$5(this, void 0, void 0, function () {
                var err_1;
                return __generator$5(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!((event === null || event === void 0 ? void 0 : event.code) === 1006)) return [3 , 4];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this.loginRequest(30000).toPromise()];
                        case 2:
                            if (_a.sent()) {
                                this.log.info("revival accessToken complete, try to connect socket");
                            }
                            else {
                                throw new AuthorizationRequired({ clazz: "com.telenia.webapi.exception.AuthorizationRequiredException" });
                            }
                            return [3 , 4];
                        case 3:
                            err_1 = _a.sent();
                            if (!(err_1 instanceof NoRouteToHost)) {
                                this.log.warn("error on login [code: ".concat(err_1.code, ", message: ").concat(err_1.message, "]"), err_1);
                            }
                            if (err_1 instanceof AuthorizationRequired || err_1 instanceof PasswordExpired || err_1 instanceof UserNotEnabledOnMcs || err_1 instanceof UserNotEnabled) {
                                switch (err_1 === null || err_1 === void 0 ? void 0 : err_1.code) {
                                    case AuthorizationRequired.CODE:
                                    case PasswordExpired.CODE:
                                    case UserNotEnabledOnMcs.CODE:
                                    case UserNotEnabled.CODE:
                                        this.onClose(__assign$2(__assign$2({}, event), { code: 4000 + (err_1 === null || err_1 === void 0 ? void 0 : err_1.code) }));
                                        return [2 , false];
                                }
                            }
                            throw err_1;
                        case 4: return [2 , true];
                    }
                });
            });
        };
        JsonRpcWebsocket.prototype.onClose = function (event) {
            var _a;
            return __awaiter$5(this, void 0, void 0, function () {
                var resetSocket, stopOpenSocket, loginProfileStatus;
                return __generator$5(this, function (_b) {
                    this.log.debug("ws onClose");
                    resetSocket = true;
                    stopOpenSocket = true;
                    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, username: this.client.username },
                        });
                    }
                    return [2 ];
                });
            });
        };
        JsonRpcWebsocket.prototype.onOpen = function () {
            return __awaiter$5(this, void 0, void 0, function () {
                var _this = this;
                return __generator$5(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.log.debug("ws onOpen");
                            if (!!this.firstConnect) return [3 , 2];
                            this.restoreSession.start();
                            this.onOpenSubscription.unsubscribe();
                            return [4 , asyncTimeout(200)];
                        case 1:
                            _a.sent();
                            this.log.debug("Is not first connection, so run restartSessionId");
                            if (this.connected) {
                                this.onOpenSubscription.unsubscribe();
                                this.onOpenSubscription = new Observable(function (observer) {
                                    var onOpenSubscribed = true;
                                    (function () { return __awaiter$5(_this, void 0, void 0, function () {
                                        var lastRequestId, err_2, lastRequestIdResponse, lastRequestIdExpected, request, err_3, err_4;
                                        return __generator$5(this, function (_a) {
                                            switch (_a.label) {
                                                case 0:
                                                    _a.trys.push([0, 10, , 11]);
                                                    lastRequestId = void 0;
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.start);
                                                    _a.label = 1;
                                                case 1:
                                                    _a.trys.push([1, 3, , 4]);
                                                    return [4 , this.client.methods.restartSessionId().toPromise()];
                                                case 2:
                                                    lastRequestId = _a.sent();
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.end);
                                                    return [3 , 4];
                                                case 3:
                                                    err_2 = _a.sent();
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.restartSessionId, RestoreSessionPhaseState.error, err_2);
                                                    throw err_2;
                                                case 4:
                                                    if (!onOpenSubscribed) return [3 , 9];
                                                    lastRequestIdResponse = parseInt(lastRequestId);
                                                    if (!(!isNaN(lastRequestIdResponse) && lastRequestIdResponse)) return [3 , 5];
                                                    lastRequestIdExpected = Array.from(this.requestExecuted.values())
                                                        .filter(function (request) { return request && request.method && request.executed && request.withNotification; })
                                                        .reduce(function (lastRequestExpected, request) { return (request.identifier.idRequest > lastRequestExpected ? request.identifier.idRequest : lastRequestExpected); }, lastRequestIdResponse);
                                                    if (lastRequestIdResponse !== lastRequestIdExpected) {
                                                        request = this.requestExecuted.get(lastRequestIdExpected);
                                                        this.log.warn("restartSessionId MISMATCH DETECTED - response: ".concat(lastRequestIdResponse, " expected: ").concat(lastRequestIdExpected, " used by ").concat(request === null || request === void 0 ? void 0 : request.method, " at ").concat(request === null || request === void 0 ? void 0 : request.requestTime));
                                                    }
                                                    this.currentIdRequest = lastRequestIdExpected;
                                                    return [3 , 9];
                                                case 5:
                                                    if (!onOpenSubscribed) return [3 , 9];
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.start);
                                                    _a.label = 6;
                                                case 6:
                                                    _a.trys.push([6, 8, , 9]);
                                                    return [4 , this.resendActiveNotification()];
                                                case 7:
                                                    _a.sent();
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.end);
                                                    return [3 , 9];
                                                case 8:
                                                    err_3 = _a.sent();
                                                    this.restoreSession.notifyProgress(RestoreSessionPhase.resendActiveNotification, RestoreSessionPhaseState.error, err_3);
                                                    throw err_3;
                                                case 9: return [3 , 11];
                                                case 10:
                                                    err_4 = _a.sent();
                                                    this.log.error("Error on restartSessionId and resendActiveNotification", err_4);
                                                    throw err_4;
                                                case 11: return [2 ];
                                            }
                                        });
                                    }); })()
                                        .then(function () {
                                        if (onOpenSubscribed)
                                            observer.complete();
                                    })
                                        .catch(function (err) {
                                        if (onOpenSubscribed)
                                            observer.error(err);
                                    });
                                    return function () {
                                        _this.log.info("restore connection ended");
                                        onOpenSubscribed = false;
                                        _this.onOpenSubscription = Subscription.EMPTY;
                                    };
                                }).subscribe({
                                    error: function (err) {
                                        _this.log.error("restore connection error", err);
                                        _this.restoreSession.error(err);
                                    },
                                    complete: function () {
                                        var _a;
                                        _this.log.info("restore connection complete");
                                        _this.restoreSession.complete();
                                        (_a = _this.transportSocket) === null || _a === void 0 ? void 0 : _a.protocolReady();
                                    },
                                });
                            }
                            _a.label = 2;
                        case 2: return [2 ];
                    }
                });
            });
        };
        JsonRpcWebsocket.prototype.resetSocket = function () {
            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;
        };
        JsonRpcWebsocket.prototype.elaborateResponseFromRevival = function (request, response) {
            return __awaiter$5(this, void 0, void 0, function () {
                var user, useProfileRequest, useProfileRequestParams;
                return __generator$5(this, function (_a) {
                    if (request.method === "getUserDetail") {
                        user = response;
                        if (user) {
                            useProfileRequest = Array.from(this.requestExecuted.values()).find(function (r) { return r.method === "useProfile"; });
                            if (useProfileRequest) {
                                useProfileRequestParams = useProfileRequest.params;
                                try {
                                    useProfileRequestParams.splice(0, 1, user.loggedProfileId);
                                    useProfileRequestParams.splice(1, 1, user.chosenDeviceTypeByClient);
                                    useProfileRequestParams.splice(2, 1, user.chosenDeviceByClient);
                                }
                                catch (e) { }
                            }
                        }
                    }
                    else {
                        _super.prototype.elaborateResponseFromRevival.call(this, request, response);
                    }
                    return [2 ];
                });
            });
        };
        return JsonRpcWebsocket;
    }(AbstractJsonRpcWebsocket));
    var JsonRpcWebsocketRestoreSession =  (function () {
        function JsonRpcWebsocketRestoreSession( revivalTimeout) {
            this.revivalTimeout = revivalTimeout;
            this._event = new BehaviorSubject(null);
        }
        Object.defineProperty(JsonRpcWebsocketRestoreSession.prototype, "event", {
            get: function () {
                return this._event.asObservable();
            },
            enumerable: false,
            configurable: true
        });
        JsonRpcWebsocketRestoreSession.prototype.start = function () {
            var _this = this;
            if (!this.onOpenRevival) {
                this.onOpenRevival = from(new Promise(function (onComplete, onError) {
                    _this.onComplete = onComplete;
                    _this.onError = onError;
                    _this.notifyState(RestoreSessionState.start);
                }))
                    .pipe(timeout(this.revivalTimeout()), finalize(function () {
                    _this.onOpenRevival = undefined;
                    _this.onComplete = undefined;
                    _this.onError = undefined;
                    if (_this._event.value && _this._event.value.state !== RestoreSessionState.error) {
                        _this.notifyState(RestoreSessionState.end);
                    }
                    _this.notifyState(null);
                }), catchError(function (e) {
                    _this.notifyState(RestoreSessionState.error, e);
                    if (e instanceof TimeoutError) {
                        throw TimeoutResponse.newInstance("Timeout has occurred on wait restore connection complete");
                    }
                    else {
                        throw e;
                    }
                }))
                    .toPromise();
            }
        };
        Object.defineProperty(JsonRpcWebsocketRestoreSession.prototype, "inProgress", {
            get: function () {
                return !!this.onOpenRevival;
            },
            enumerable: false,
            configurable: true
        });
        JsonRpcWebsocketRestoreSession.prototype.notifyState = function (state, error) {
            try {
                this._event.next(state ? new RestoreSessionEvent(state, error) : null);
            }
            catch (e) { }
        };
        JsonRpcWebsocketRestoreSession.prototype.notifyProgress = function (phase, phaseState, error) {
            if (this.inProgress) {
                var event_1 = new RestoreSessionEvent(RestoreSessionState.progress, error);
                event_1.phase = phase;
                event_1.phaseState = phaseState;
                try {
                    this._event.next(event_1);
                }
                catch (e) { }
            }
        };
        JsonRpcWebsocketRestoreSession.prototype.waitEnd = function () {
            return __awaiter$5(this, void 0, void 0, function () {
                return __generator$5(this, function (_a) {
                    if (this.inProgress) {
                        return [2 , this.onOpenRevival];
                    }
                    return [2 ];
                });
            });
        };
        JsonRpcWebsocketRestoreSession.prototype.complete = function () {
            var _a;
            if (this.inProgress) {
                (_a = this.onComplete) === null || _a === void 0 ? void 0 : _a.call(this);
            }
        };
        JsonRpcWebsocketRestoreSession.prototype.error = function (err) {
            var _a;
            if (this.inProgress) {
                (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, err);
            }
        };
        return JsonRpcWebsocketRestoreSession;
    }());

    var 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));
        }
    }
    var 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("");
    }
    var _btoa = btoa
        ? 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 external_api_min = createCommonjsModule(function (module, exports) {
    !function(e,t){module.exports=t();}(self,(function(){return (()=>{var e={820:(e,t,n)=>{n.d(t,{default:()=>S});var i=n(620),r=n.n(i);class s extends i{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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(0===e.length)return JSON.stringify(this._storage);const t={...this._storage};return e.forEach((e=>{delete t[e];})),JSON.stringify(t)}}const o=new class extends i{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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(this.isLocalStorageDisabled())return this._storage.serialize(e);const t=this._storage.length,n={};for(let i=0;i<t;i++){const t=this._storage.key(i);e.includes(t)||(n[t]=this._storage.getItem(t));}return JSON.stringify(n)}};var a=n(571);const c=["__proto__","constructor","prototype"];function l(e){const t=new RegExp("^([a-z][a-z0-9\\.\\+-]*:)+","gi"),n=t.exec(e);if(n){let i=n[n.length-1].toLowerCase();"http:"!==i&&"https:"!==i&&(i="https:"),(e=e.substring(t.lastIndex)).startsWith("//")&&(e=i+e);}return e}function d(e={}){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 u(e){const t={toString:h};let n,i,r;if(e=e.replace(/\s/g,""),n=new RegExp("^([a-z][a-z0-9\\.\\+-]*:)","gi"),i=n.exec(e),i&&(t.protocol=i[1].toLowerCase(),e=e.substring(n.lastIndex)),n=new RegExp("^(//[^/?#]+)","gi"),i=n.exec(e),i){let r=i[1].substring(2);e=e.substring(n.lastIndex);const s=r.indexOf("@");-1!==s&&(r=r.substring(s+1)),t.host=r;const o=r.lastIndexOf(":");-1!==o&&(t.port=r.substring(o+1),r=r.substring(0,o)),t.hostname=r;}if(n=new RegExp("^([^?#]*)","gi"),i=n.exec(e),i&&(r=i[1],e=e.substring(n.lastIndex)),r?r.startsWith("/")||(r=`/${r}`):r="/",t.pathname=r,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 h(e){const{hash:t,host:n,pathname:i,protocol:r,search:s}=e||this;let o="";return r&&(o+=r),n&&(o+=`//${n}`),o+=i||"/",s&&(o+=s),t&&(o+=t),o}function p(e){let t;t=e.serverURL&&e.room?new URL(e.room,e.serverURL).toString():e.room?e.room:e.url||"";const n=u(l(t));if(!n.protocol){let t=e.protocol||e.scheme;t&&(t.endsWith(":")||(t+=":"),n.protocol=t);}let{pathname:i}=n;if(!n.host){const t=e.domain||e.host||e.hostname;if(t){const{host:e,hostname:r,pathname:s,port:o}=u(l(`org.jitsi.meet://${t}`));e&&(n.host=e,n.hostname=r,n.port=o),"/"===i&&"/"!==s&&(i=s);}}const r=e.roomName||e.room;!r||!n.pathname.endsWith("/")&&n.pathname.endsWith(`/${r}`)||(i.endsWith("/")||(i+="/"),i+=r),n.pathname=i;const{jwt:s,lang:o,release:a}=e,c=new URLSearchParams(n.search);s&&c.set("jwt",s);const{defaultLanguage:h}=e.configOverwrite||{};(o||h)&&c.set("lang",o||h),a&&c.set("release",a);const p=c.toString();p&&(n.search=`?${p}`);let{hash:g}=n;for(const t of ["config","interfaceConfig","devices","userInfo","appData"]){const n=d(e[`${t}Overwrite`]||e[t]||e[`${t}Override`]);if(n.length){let e=`${t}.${n.join(`&${t}.`)}`;g.length?e=`&${e}`:g="#",g+=e;}}return n.hash=g,n.toString()||void 0}const g={window:window.opener||window.parent},m="message";class f{constructor(){let{postisOptions:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.postis=function(e){var t,n=e.scope,i=e.window,r=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 i=o[t.method];if(i)for(var r=0;r<i.length;r++)i[r].call(null,t.params);else c[t.method]=c[t.method]||[],c[t.method].push(t.params);}};r.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 i=o[e],r=0;r<i.length;r++)for(var s=0;s<n.length;s++)i[r].call(null,n[s]);delete c[e];},send:function(e){var t=e.method;(l||e.method===d)&&i&&"function"==typeof i.postMessage?i.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,r&&"function"==typeof r.removeEventListener&&r.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}({...g,...e}),this._receiveCallback=()=>{},this.postis.listen(m,(e=>this._receiveCallback(e)));}dispose(){this.postis.destroy();}send(e){this.postis.send({method:m,params:e});}setReceiveCallback(e){this._receiveCallback=e;}}const v="request",y="response";class _{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===y){const t=this._responseHandlers.get(e.id);t&&(t(e),this._responseHandlers.delete(e.id));}else e.type===v?this.emit("request",e.data,((t,n)=>{this._backend.send({type:y,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),i=1;i<t;i++)n[i-1]=arguments[i];const r=this._listeners.get(e);let s=!1;return r&&r.size&&r.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,i)=>{this._responseHandlers.set(t,(e=>{let{error:t,result:r}=e;void 0!==r?n(r):i(void 0!==t?t:new Error("Unexpected response format!"));})),this._backend.send({type:v,data:e,id:t});}))}setBackend(e){this._disposeBackend(),this._backend=e,this._backend.setReceiveCallback(this._onMessageReceived.bind(this));}}(function(e,t=!1,n="hash"){"string"==typeof e&&(e=new URL(e));const i="search"===n?e.search:e.hash,r={},s=(null==i?void 0:i.substr(1).split("&"))||[];if("hash"===n&&1===s.length){const e=s[0];if(e.startsWith("/")&&1===e.split("&").length)return r}return s.forEach((e=>{const n=e.split("="),i=n[0];if(!i||i.split(".").some((e=>c.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 function(e,t=""){var n;console.error(t,e),null===(n=window.onerror)||void 0===n||n.call(window,t,void 0,void 0,void 0,e);}(e,`Failed to parse URL parameter value: ${String(s)}`)}r[i]=s;})),r})(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 b=n(860);const w=n.n(b)().getLogger("modules/API/external/functions.js");function L(e,t){return e.sendRequest({type:"devices",name:"setDevice",device:t})}const k=["css/all.css","libs/alwaysontop.min.js"],E={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",hideNotification:"hide-notification",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",resizeFilmStrip:"resize-film-strip",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",setNoiseSuppressionEnabled:"set-noise-suppression-enabled",setParticipantVolume:"set-participant-volume",setSubtitles:"set-subtitles",setTileView:"set-tile-view",setVideoQuality:"set-video-quality",showNotification:"show-notification",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",toggleNoiseSuppression:"toggle-noise-suppression",toggleParticipantsPane:"toggle-participants-pane",toggleRaiseHand:"toggle-raise-hand",toggleShareScreen:"toggle-share-screen",toggleSubtitles:"toggle-subtitles",toggleTileView:"toggle-tile-view",toggleVirtualBackgroundDialog:"toggle-virtual-background",toggleVideo:"toggle-video"},C={"avatar-changed":"avatarChanged","audio-availability-changed":"audioAvailabilityChanged","audio-mute-status-changed":"audioMuteStatusChanged","audio-or-video-sharing-toggled":"audioOrVideoSharingToggled","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","participants-pane-toggled":"participantsPaneToggled","password-required":"passwordRequired","prejoin-screen-loaded":"prejoinScreenLoaded","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 x=0;function O(e,t){e._numberOfParticipants+=t;}function R(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 S extends(r()){constructor(e){super();for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];const{roomName:r="",width:s="100%",height:a="100%",parentNode:c=document.body,configOverwrite:l={},interfaceConfigOverwrite:d={},jwt:u,lang:h,onload:g,invitees:m,devices:v,userInfo:y,e2eeKey:b,release:w}=function(e){if(!e.length)return {};switch(typeof e[0]){case"string":case"undefined":{const[t,n,i,r,s,o,a,c,l]=e;return {roomName:t,width:n,height:i,parentNode:r,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),L=o.getItem("jitsiLocalStorage");this._parentNode=c,this._url=function(e){return p({...arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},url:`https://${e}/#jitsi_meet_external_api_id=${x}`})}(e,{configOverwrite:l,interfaceConfigOverwrite:d,jwt:u,lang:h,roomName:r,devices:v,userInfo:y,appData:{localStorageContent:L},release:w}),this._createIFrame(a,s,g),this._transport=new _({backend:new f({postisOptions:{allowedOrigin:new URL(this._url).origin,scope:`jitsi_meet_external_api_${x}`,window:this._frame.contentWindow}})}),Array.isArray(m)&&m.length>0&&this.invite(m),this._tmpE2EEKey=b,this._isLargeVideoVisible=!1,this._isPrejoinVideoVisible=!1,this._numberOfParticipants=0,this._participants={},this._myUserID=void 0,this._onStageParticipant=void 0,this._setupListeners(),x++;}_createIFrame(e,t,n){const i=`jitsiConferenceFrame${x}`;this._frame=document.createElement("iframe"),this._frame.allow="camera; microphone; display-capture; autoplay; clipboard-write",this._frame.src=this._url,this._frame.name=i,this._frame.id=i,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 i=t.querySelector("base");if(i&&i.href)n=i.href;else {const{protocol:t,host:i}=e.location;n=`${t}//${i}`;}return k.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")}_getPrejoinVideo(){const e=this.getIFrame();if(this._isPrejoinVideoVisible&&e&&e.contentWindow&&e.contentWindow.document)return e.contentWindow.document.getElementById("prejoinVideo")}_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=R(e),i=R(t);void 0!==n&&(this._height=e,this._frame.style.height=n),void 0!==i&&(this._width=t,this._frame.style.width=i);}_setupListeners(){this._transport.on("event",(e=>{let{name:t,...n}=e;const i=n.id;switch(t){case"video-conference-joined":void 0!==this._tmpE2EEKey&&(this.executeCommand(E.e2eeKey,this._tmpE2EEKey),this._tmpE2EEKey=void 0),this._myUserID=i,this._participants[i]={email:n.email,avatarURL:n.avatarURL};case"participant-joined":this._participants[i]=this._participants[i]||{},this._participants[i].displayName=n.displayName,this._participants[i].formattedDisplayName=n.formattedDisplayName,O(this,1);break;case"participant-left":O(this,-1),delete this._participants[i];break;case"display-name-change":{const e=this._participants[i];e&&(e.displayName=n.displayname,e.formattedDisplayName=n.formattedDisplayName);break}case"email-change":{const e=this._participants[i];e&&(e.email=n.email);break}case"avatar-changed":{const e=this._participants[i];e&&(e.avatarURL=n.avatarURL);break}case"on-stage-participant-changed":this._onStageParticipant=i,this.emit("largeVideoChanged");break;case"large-video-visibility-changed":this._isLargeVideoVisible=n.isVisible,this.emit("largeVideoChanged");break;case"prejoin-screen-loaded":this._participants[i]={displayName:n.displayName,formattedDisplayName:n.formattedDisplayName};break;case"on-prejoin-video-changed":this._isPrejoinVideoVisible=n.isVisible,this.emit("prejoinVideoChanged");break;case"video-conference-left":O(this,-1),delete this._participants[this._myUserID];break;case"video-quality-changed":this._videoQuality=n.videoQuality;break;case"breakout-rooms-updated":this.updateNumberOfParticipants(n.rooms);break;case"local-storage-changed":return o.setItem("jitsiLocalStorage",n.localStorageContent),!0}const r=C[t];return !!r&&(this.emit(r,n),!0)}));}updateNumberOfParticipants(e){if(!e||!Object.keys(e).length)return;const t=Object.keys(e).reduce(((t,n)=>{var i;return null!==(i=e[n])&&void 0!==i&&i.participants?Object.keys(e[n].participants).length+t:t}),0);this._numberOfParticipants=t;}async getRoomsInfo(){return this._transport.sendRequest({name:"rooms-info"})}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 E){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this._transport.sendEvent({data:n,name:E[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=>(w.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=>(w.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 L(e,{id:n,kind:"audioinput",label:t})}(this._transport,e,t)}setAudioOutputDevice(e,t){return function(e,t,n){return L(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 L(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(820).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 i="object"==typeof(arguments.length<=1?void 0:arguments[1])&&(arguments.length<=1?void 0:arguments[1]),r=(arguments.length<=1?0:arguments.length-1)>1||!i?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])||i||{},o=JSON.parse(e,r);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 i of e){if(Object.prototype.hasOwnProperty.call(i,"__proto__")){if("remove"!==t.protoAction)throw new SyntaxError("Object contains forbidden prototype property");delete i.__proto__;}for(const e in i){const t=i[e];t&&"object"==typeof t&&n.push(i[e]);}}}},t.safeParse=function(e,n){try{return t.parse(e,n)}catch(e){return null}};},369:(e,t,n)=>{var i=n(7);function r(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(i.levels).forEach(function(e){this[i.levels[e]]=function(){this._log.apply(this,arguments);}.bind(this,e);}.bind(this)),this.storeLogsIntervalID=null,this.queue=[],this.totalLen=0,this.outputCache=[];}r.prototype.stringify=function(e){try{return JSON.stringify(e)}catch(e){return "[object with circular refs?]"}},r.prototype.formatLogMessage=function(e){for(var t="",n=1,r=arguments.length;n<r;n++){var s=arguments[n];!this.stringifyObjects&&e!==i.levels.ERROR||"object"!=typeof s||(s=this.stringify(s)),t+=s,n!==r-1&&(t+=" ");}return t.length?t:null},r.prototype._log=function(){var e=arguments[1],t=this.formatLogMessage.apply(this,arguments);if(t){var n=this.queue[this.queue.length-1],i=n&&n.text;i===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);},r.prototype.start=function(){this._reschedulePublishInterval();},r.prototype._reschedulePublishInterval=function(){this.storeLogsIntervalID&&(window.clearTimeout(this.storeLogsIntervalID),this.storeLogsIntervalID=null),this.storeLogsIntervalID=window.setTimeout(this._flush.bind(this,!1,!0),this.storeInterval);},r.prototype.flush=function(){this._flush(!1,!0);},r.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();},r.prototype.stop=function(){this._flush(!1,!1);},e.exports=r;},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 i={};function r(){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 i=null;return n[3]&&(i=n[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/)),!i||i.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=i[1],e.fileLocation=i[2],e.line=i[3],e.column=i[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||i.disableCallerInfo)&&r(),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,i,r){this.id=n,this.options=r||{},this.transports=i,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){i=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 i=n(7),r=n(369),s={},o=[],a=i.levels.TRACE;e.exports={addGlobalTransport:function(e){i.addGlobalTransport(e);},removeGlobalTransport:function(e){i.removeGlobalTransport(e);},setGlobalOptions:function(e){i.setGlobalOptions(e);},getLogger:function(e,t,n){var r=new i(a,e,t,n);return e?(s[e]=s[e]||[],s[e].push(r)):o.push(r),r},setLogLevelById:function(e,t){for(var n=t?s[t]||[]:o,i=0;i<n.length;i++)n[i].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 i=s[n]||[];for(t=0;t<i.length;t++)i[t].setLevel(e);}},levels:i.levels,LogCollector:r};},620:e=>{var t,n="object"==typeof Reflect?Reflect:null,i=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 r=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,i){function r(n){e.removeListener(t,s),i(n);}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),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,r);}))},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,i){var r,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]=i?[n,o]:[o,n]:i?o.unshift(n):o.push(n),(r=c(e))>0&&o.length>r&&!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 i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=d.bind(i);return r.listener=n,i.wrapFn=r,r}function h(e,t,n){var i=e._events;if(void 0===i)return [];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]: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}(r):g(r,r.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),i=0;i<t;++i)n[i]=e[i];return n}function m(e,t,n,i){if("function"==typeof e.on)i.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 r(s){i.once&&e.removeEventListener(t,r),n(s);}));}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(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||r(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 r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return !1;if(r){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)i(c,this,t);else {var l=c.length,d=g(c,l);for(n=0;n<l;++n)i(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,i,r,s,o;if(a(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,r=s;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop();}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t);}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,i;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 r,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(r=s[i])&&this.removeAllListeners(r);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(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);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(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i](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 i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]});},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n(872)})()}));
    });
    unwrapExports(external_api_min);
    external_api_min.JitsiMeetExternalAPI;

    var JitsiMeetAPI_1 = createCommonjsModule(function (module, exports) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JitsiMeetExternalAPI = void 0;
    exports.JitsiMeetExternalAPI = external_api_min;
    });
    unwrapExports(JitsiMeetAPI_1);
    var JitsiMeetAPI_2 = JitsiMeetAPI_1.JitsiMeetExternalAPI;

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

    var __extends$3 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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$1 = (undefined && undefined.__assign) || function () {
        __assign$1 = Object.assign || function(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$1.apply(this, arguments);
    };
    var __awaiter$4 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$4 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var WebapiClient =  (function () {
        function WebapiClient(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 }, function () { return Math.random().toString(36)[3]; }).join("");
            this._log = Log$1.create("", this.instanceId, new DefaultLogConfigurator(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._logConfigImpl = new WebapiClientLogConfigurator(this);
            this._log.client = this;
            this._initializeClient();
        }
        Object.defineProperty(WebapiClient.prototype, "omnidesk", {
            get: function () {
                return this._omnidesk;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "webrtc", {
            get: function () {
                return this._webrtc;
            },
            set: function (webrtc) {
                if (webrtc) {
                    if (!webrtc.client) {
                        this._log.debug("Attach WebRTCManager to client");
                    }
                    this._webrtc = webrtc;
                    this._webrtc.attachToClient(this);
                    this._webrtc.initFromClient(this._webrtcControlMessageNotifier);
                }
                else {
                    if (this._webrtc) {
                        this._log.debug("Disable and unlink WebRTCManager to client");
                        this._webrtc.stop();
                        this._webrtc = webrtc;
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "instanceId", {
            get: function () {
                return this._instanceId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "phoneManagerActive", {
            get: function () {
                return this._options.phoneManagerActive;
            },
            set: function (phoneManagerActive) {
                var _this = this;
                if (this._options.phoneManagerActive !== phoneManagerActive) {
                    var previousValue_1 = this._options.phoneManagerActive;
                    this._options.phoneManagerActive = !!phoneManagerActive;
                    this.notifyPhoneManagerActive().then(function (result) {
                        if (!result) {
                            _this._log.warn("reset phoneManagerActive to '".concat(previousValue_1, "'"));
                            _this._options.phoneManagerActive = previousValue_1;
                        }
                    });
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "logConfigurator", {
            get: function () {
                return this._logConfigImpl;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "options", {
            get: function () {
                return this._options;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "transport", {
            get: function () {
                return this._transport;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "methods", {
            get: function () {
                return this._methods;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "loginProfile", {
            get: function () {
                return this._loginProfileSubject.asObservable();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "loginProfileLoggedOnNewSession", {
            get: function () {
                return this._loginProfileLoggedOnNewSession;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "connectionEvent", {
            get: function () {
                return this._connectionEventSubject.asObservable();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "restoreSessionEvent", {
            get: function () {
                return this._transport.restoreSessionEvent;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "callNotification", {
            get: function () {
                return this._channelNotification.pipe(map(function (data) { return data.callInfo; }));
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "sessionId", {
            get: function () {
                return this._sessionId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "deviceId", {
            get: function () {
                return this._deviceId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "username", {
            get: function () {
                return this._username;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClient.prototype, "accessToken", {
            get: function () {
                return this._getAccessToken(false);
            },
            enumerable: false,
            configurable: true
        });
        WebapiClient.prototype._initializeClient = function () {
            var _this = this;
            var 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(function (statusEvent) {
                _this._log.debug("Login profile status changed", statusEvent);
            });
            this._connectionEventSubject.subscribe(function (event) {
                if (event.connected) {
                    _this._forceOpenSocket = false;
                }
            });
            this._transport = new JsonRpcWebsocket(this, function (timeout) {
                var _a;
                var 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._methods = new WebapiClientMethods(this, this.handleChannelNotification(new Subject()), this.handleClientCommandNotification(new Subject()), function () {
                _this._forceOpenSocket = true;
                _this._transport.stopOpenSocket = false;
            }, function (timeout, loginType, usernameOrAccessToken, password) { return _this._loginRequest(timeout, loginType, usernameOrAccessToken, password); }, function (rememberMe) {
                _this.options.rememberMe = rememberMe ? true : false;
                if (!_this.options.rememberMe) {
                    _this._cleanAccessToken(false);
                }
            }, function (logoutResponse) { return __awaiter$4(_this, void 0, void 0, function () {
                var response;
                return __generator$4(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 , logoutResponse];
                        case 1:
                            response = _a.sent();
                            if (response) {
                                this.cleanAllCredential(true);
                                this.disconnect();
                            }
                            return [2 , response];
                    }
                });
            }); });
            var loginProfileResult = this.transport.getResponseOf(1 );
            var loginProfileEvent = merge(loginProfileResult.result, loginProfileResult.notification).pipe(share());
            var loggedLoginProfile = loginProfileEvent.pipe(filter(function (event) { var _a; return (_a = event.logged) !== null && _a !== void 0 ? _a : false; }));
            this._loginProfileLoggedOnNewSession = loggedLoginProfile.pipe(distinctUntilChanged(function (prev, curr) {
                if (prev.sessionId === curr.sessionId) {
                    _this._log.verbose("SessionId not changed, ".concat(curr.sessionId));
                    return true;
                }
                else {
                    _this._log.info("SessionId changed - previous ".concat(prev.sessionId, ", current ").concat(curr.sessionId));
                    return false;
                }
            }), share());
            this._loginProfileLoggedOnNewSession.pipe(concatMap(function () { return _this.notifyPhoneManagerActive(); })).subscribe();
            loginProfileEvent.subscribe(function (loginProfile) { return _this._handleLoginProfileEvent(loginProfile); });
            this._updateLoginProfileSubject(loggedLoginProfile.pipe(take(1)))
                .pipe(concatMap(function () { return _this.notifyPhoneManagerActive(); }))
                .subscribe({
                error: function (err) {
                    _this._log.error("Error on update loginProfile", err);
                },
            });
            var currentAccessToken = sessionAccessToken || this._getAccessToken();
            if (currentAccessToken) {
                if (this.options.selfManagedLogin) {
                    this._log.info("Find stored accessToken ".concat(currentAccessToken, " and options.selfManagedLogin is true, try login"));
                    setTimeout(function () {
                        _this.oneTimeLoginByAccessToken(currentAccessToken);
                    });
                }
                else {
                    this.cleanAllCredential(true);
                    this._log.info("Find stored accessToken ".concat(currentAccessToken, " but options.selfManagedLogin is false, nothing to do"));
                }
            }
            else {
                this._updateLoginProfileSubject(throwError(null)).subscribe({
                    error: function () {
                        _this._log.info("Credential requested, wait login");
                    },
                });
            }
        };
        WebapiClient.prototype.notifyPhoneManagerActive = function () {
            return __awaiter$4(this, void 0, void 0, function () {
                var result, e_1, err_1, err_2;
                return __generator$4(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            result = false;
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this._methods.setPhoneManagerActive({ active: this.phoneManagerActive })];
                        case 2:
                            result = _a.sent();
                            return [3 , 4];
                        case 3:
                            e_1 = _a.sent();
                            this._log.error("error on setPhoneManagerActive", e_1);
                            return [3 , 4];
                        case 4:
                            if (!("tvoxclient" === this._options.userAgent.type.trim().toLowerCase())) return [3 , 12];
                            if (!this.phoneManagerActive) return [3 , 9];
                            _a.label = 5;
                        case 5:
                            _a.trys.push([5, 7, , 8]);
                            return [4 , this._methods.startClientCommandNotify()];
                        case 6:
                            if (!(_a.sent())) {
                                this._log.error("unable to startClientCommandNotify, server response false");
                            }
                            return [3 , 8];
                        case 7:
                            err_1 = _a.sent();
                            this._log.error("error on startClientCommandNotify", err_1);
                            return [3 , 8];
                        case 8: return [3 , 12];
                        case 9:
                            _a.trys.push([9, 11, , 12]);
                            return [4 , this._methods.stopClientCommandNotify()];
                        case 10:
                            _a.sent();
                            return [3 , 12];
                        case 11:
                            err_2 = _a.sent();
                            this._log.error("error on stopClientCommandNotify", err_2);
                            return [3 , 12];
                        case 12: return [2 , result];
                    }
                });
            });
        };
        WebapiClient.prototype.handleChannelNotification = function (channelNotification) {
            var _this = this;
            this._channelNotification = merge(channelNotification, this._webrtcControlMessageNotifier.pipe(filter(function (webrtcControlMessage) { return !webrtcControlMessage._isFromServer; }), map(function (webrtcControlMessage) {
                return {
                    channel: webrtcControlMessage._realChannelType,
                    callInfo: buildCallInfoFromWebrtcControlMessage(webrtcControlMessage),
                    webrtcControlMessage: webrtcControlMessage,
                };
            }))).pipe(map(function (callInfo) { return adjustCallInfoWithMediaInfo(callInfo, _this.webrtc); }), share());
            this._channelNotification
                .pipe(filter(function (channelEvent) {
                if (!!(channelEvent && channelEvent.callInfo) && (channelEvent && channelEvent.webrtcControlMessage ? channelEvent.webrtcControlMessage._isFromServer : true)) {
                    switch (channelEvent.channel) {
                        case ChannelType.PhoneCall:
                            var 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(function (channelEvent) {
                return buildWebrtcControlMessageFromChannelEvent(channelEvent,
                channelEvent.webrtcControlMessage ? channelEvent.webrtcControlMessage._isFromServer : true,
                channelEvent.channel === ChannelType.Video ? { direction: CallDirection.inbound } : null);
            }))
                .subscribe(this._webrtcControlMessageNotifier);
            return channelNotification;
        };
        WebapiClient.prototype.handleClientCommandNotification = function (commandNotification) {
            var _this = this;
            var executeCommand = function (command) { return __awaiter$4(_this, void 0, void 0, function () {
                var result, commandIsForDevice, methodResult, e_2;
                return __generator$4(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this._log.debug("HandleClientCommand - Manage message ".concat(command.id, " - ").concat(command.command));
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 26, , 27]);
                            if (!this.options.remoteCommandHandler) return [3 , 3];
                            return [4 , this.options.remoteCommandHandler(command)];
                        case 2:
                            result = _a.sent();
                            return [3 , 25];
                        case 3:
                            commandIsForDevice = true, methodResult = true;
                            if (!isDialCommand(command)) return [3 , 5];
                            return [4 , this.methods.dial(__assign$1(__assign$1({}, command), { channelId: channelIdToChannelType(command.channelId), media: buildMediaParam(command.media) }))];
                        case 4:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 5:
                            if (!isAnswerCommand(command)) return [3 , 7];
                            return [4 , this.methods.answerOnChannel(ChannelType.PhoneCall, command.callId, buildMediaParam(command.media))];
                        case 6:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 7:
                            if (!isCancelCommand(command)) return [3 , 9];
                            return [4 , this.methods.cancel(command.callId)];
                        case 8:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 9:
                            if (!isHoldCommand(command)) return [3 , 11];
                            return [4 , this.methods.hold(command.callId)];
                        case 10:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 11:
                            if (!isUnholdCommand(command)) return [3 , 13];
                            return [4 , this.methods.unhold(command.callId)];
                        case 12:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 13:
                            if (!isAttendedTransferCommand(command)) return [3 , 15];
                            return [4 , this.methods.attendedTransfer(command.callId, command.heldCallId, buildMediaParam(command.media))];
                        case 14:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 15:
                            if (!isBlindTransferCommand(command)) return [3 , 17];
                            return [4 , this.methods.blindTransfer(command.callId, command.accessCode, command.number, command.data || [])];
                        case 16:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 17:
                            if (!isSendDTMFCommand(command)) return [3 , 19];
                            return [4 , this.methods.sendDTMF(command.callId, command.dtmf, true)];
                        case 18:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 19:
                            if (!isDialATXferOnGenericDeviceCommand(command)) return [3 , 21];
                            return [4 , this.methods.dialATXferOnGenericDevice(command)];
                        case 20:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 21:
                            if (!isCancelTransferOnGenericDeviceCommand(command)) return [3 , 23];
                            return [4 , this.methods.cancelTransferOnGenericDevice(command)];
                        case 22:
                            methodResult = !!(_a.sent());
                            return [3 , 24];
                        case 23:
                            if (isSendFeedbackCommand(command)) {
                                commandIsForDevice = false;
                            }
                            else {
                                commandIsForDevice = false;
                            }
                            _a.label = 24;
                        case 24:
                            if (commandIsForDevice) {
                                result = methodResult ? { result: ClientCommandResult.OK } : { result: ClientCommandResult.FAILED, resultMessage: "false" };
                            }
                            else {
                                result = { result: ClientCommandResult.FAILED, resultMessage: "Not implemented" };
                            }
                            _a.label = 25;
                        case 25: return [3 , 27];
                        case 26:
                            e_2 = _a.sent();
                            this._log.error("HandleClientCommand - Error on manage message ".concat(command.id, " - ").concat(command.command), e_2);
                            result = { result: ClientCommandResult.FAILED, resultMessage: "error on execute ".concat(command.command, " command - ").concat(e_2) };
                            return [3 , 27];
                        case 27: return [2 , { command: command, result: result }];
                    }
                });
            }); };
            var notifyCommandReceived = function (commandNotification) {
                return commandNotification.pipe(tap(function (command) {
                    _this._log.debug("HandleClientCommand - Receiving message ".concat(command.id), command);
                }), mergeMap(function (command) { return __awaiter$4(_this, void 0, void 0, function () {
                    return __generator$4(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                return [4 , this.methods.sendClientCommandResponse({ command: command.command, commandId: command.id, result: ClientCommandResult.RECEIVED })];
                            case 1:
                                if (_a.sent()) {
                                    this._log.debug("HandleClientCommand - server confirm RECEIVED ".concat(command.id, " - ").concat(command.command));
                                }
                                else {
                                    this._log.debug("HandleClientCommand - server not confirm RECEIVED ".concat(command.id, " - ").concat(command.command));
                                }
                                return [3 , 3];
                            case 2:
                                _a.sent();
                                this._log.warn("HandleClientCommand - error on send command RECEIVED ".concat(command.id, " - ").concat(command.command));
                                return [3 , 3];
                            case 3: return [2 , command];
                        }
                    });
                }); }));
            };
            var commandNotified = commandNotification.asObservable();
            var commandWithResult;
            if (this.options.remoteCommandHandler) {
                commandWithResult = notifyCommandReceived(commandNotified).pipe(mergeMap(executeCommand));
            }
            else {
                var _a = partition(commandNotified, function (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;
                    }
                }), phoneDeviceCommandNotified = _a[0], otherCommandNotified = _a[1];
                commandWithResult = merge(notifyCommandReceived(phoneDeviceCommandNotified).pipe(concatMap(executeCommand)),
                notifyCommandReceived(otherCommandNotified).pipe(mergeMap(executeCommand)));
            }
            commandWithResult.subscribe(function (_a) {
                var command = _a.command, result = _a.result;
                return __awaiter$4(_this, void 0, void 0, function () {
                    return __generator$4(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                if (!result || !result.result) {
                                    result = { result: ClientCommandResult.FAILED, resultMessage: "Unknow result" };
                                }
                                _b.label = 1;
                            case 1:
                                _b.trys.push([1, 3, , 4]);
                                return [4 , this.methods.sendClientCommandResponse({ command: command.command, commandId: command.id, result: result.result, resultMessage: result.resultMessage })];
                            case 2:
                                _b.sent();
                                return [3 , 4];
                            case 3:
                                _b.sent();
                                return [3 , 4];
                            case 4:
                                this._log.debug("HandleClientCommand - End manage message ".concat(command.id, " - ").concat(command.command));
                                return [2 ];
                        }
                    });
                });
            });
            return commandNotification;
        };
        WebapiClient.prototype._handleLoginProfileEvent = function (loginProfile) {
            if (loginProfile && (this.username == null || this.username === loginProfile.username)) {
                if (this.username === null && loginProfile.username) {
                    this._username = loginProfile.username;
                }
                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);
                            var 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);
                        }
                        var accessToken = this._getAccessToken();
                        if (loginProfile.status !== LoginProfileStatus.LOGGED && accessToken) {
                            this._methods.loginByAccessToken(accessToken, this.options.rememberMe);
                        }
                        else {
                            this._loginProfileSubject.next(loginProfile);
                        }
                        break;
                }
            }
        };
        WebapiClient.prototype._loginRequest = function (requestTimeout, loginType, usernameOrAccessToken, password) {
            var _this = this;
            var result = from(fetch(this.generateWsUrl(loginType === LoginType.Custom ? "/login_custom" : "/login", true, loginType === LoginType.Credential).replace(new RegExp("^ws"), "http"), {
                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(function (err) {
                if (err instanceof TimeoutError) {
                    throw err;
                }
                else {
                    throw new NoRouteToHost({
                        clazz: "",
                        code: -3,
                        message: err.message,
                    });
                }
            }), switchMap(function (fetchResponse) {
                return defer(function () { return __awaiter$4(_this, void 0, void 0, function () {
                    var loginResponse, response;
                    var _a, _b, _c;
                    return __generator$4(this, function (_d) {
                        switch (_d.label) {
                            case 0:
                                if (!fetchResponse.ok) return [3 , 2];
                                return [4 , fetchResponse.text()];
                            case 1:
                                loginResponse = _d.sent();
                                if (loginResponse) {
                                    try {
                                        response = JSON.parse(loginResponse);
                                        this._saveAccessToken(response.accessToken);
                                        this._localStoreManager.deleteData("teleniaWebApiDeviceId");
                                        this._deviceId = response.deviceId;
                                        this._sessionId = response.sessionId;
                                        this._username = response.username;
                                        return [2 , 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",
                                    });
                                }
                                return [3 , 3];
                            case 2:
                                switch (fetchResponse.status) {
                                    case 403:
                                        throw PasswordExpired.newInstance((_a = fetchResponse.headers.get("TeleniaUser")) !== null && _a !== void 0 ? _a : "", "true" === fetchResponse.headers.get("TeleniaCheckSecurityEnabled"));
                                    case 497:
                                        throw UserNotEnabledOnMcs.newInstance((_b = fetchResponse.headers.get("TeleniaUser")) !== null && _b !== void 0 ? _b : "");
                                    case 498:
                                        throw UserNotEnabled.newInstance((_c = fetchResponse.headers.get("TeleniaUser")) !== null && _c !== void 0 ? _c : "");
                                    default:
                                        throw new AuthorizationRequired({
                                            clazz: "com.telenia.webapi.exception.AuthorizationRequiredException",
                                            sessionId: this.sessionId,
                                            code: fetchResponse.status,
                                            message: fetchResponse.statusText,
                                        });
                                }
                                _d.label = 3;
                            case 3: return [2 ];
                        }
                    });
                }); });
            }));
        };
        WebapiClient.prototype._updateLoginProfileSubject = function (loginPromise) {
            var _this = this;
            return loginPromise.pipe(tap(function (response) {
                setTimeout(function () {
                    if (response) {
                        if (response.accessToken && response.accessToken !== _this._getAccessToken()) {
                            _this._saveAccessToken(response.accessToken);
                        }
                        _this._loginProfileSubject.next(response);
                    }
                });
            }), catchError(function (err) {
                if (!(err instanceof SocketClosed)) {
                    var newStatus_1 = LoginProfileStatus.RETRY;
                    if (err instanceof StopOpenSocket) {
                        newStatus_1 = LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE;
                    }
                    setTimeout(function () { return _this._loginProfileSubject.next({ status: newStatus_1, logged: false }); });
                }
                throw err;
            }));
        };
        WebapiClient.prototype._cleanAccessToken = function (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) { }
        };
        WebapiClient.prototype._getAccessToken = function (sessionOnly) {
            var cookieAccessToken = null;
            if (!this._accessToken) {
                var sessionAccessToken = this._localStoreManager.getData(this._getSessionStorageAccessTokenKey("teleniaWebApiAccessToken"));
                if (sessionAccessToken) {
                    cookieAccessToken = sessionAccessToken;
                }
                else if (!sessionOnly) {
                    if (navigator.cookieEnabled) {
                        var currentCookie = parse_1(document.cookie);
                        if (currentCookie && currentCookie.teleniaWebApiAccessToken) {
                            cookieAccessToken = currentCookie.teleniaWebApiAccessToken;
                        }
                    }
                }
            }
            return this._accessToken ? this._accessToken : cookieAccessToken;
        };
        WebapiClient.prototype._getSessionStorageAccessTokenKey = function (prefix) {
            return prefix + (this.options.cookie_path ? ("/" + this.options.cookie_path.trim()).replace("//", ".").replace("/", ".") : "") || "";
        };
        WebapiClient.prototype._saveAccessToken = function (accessToken) {
            var _this = this;
            this._accessToken = accessToken;
            this._localStoreManager.saveSessionData(accessToken !== null && accessToken !== void 0 ? accessToken : "", this._getSessionStorageAccessTokenKey("teleniaWebApiAccessToken"));
            if (navigator.cookieEnabled) {
                var 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(function () {
                                    var 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);
            }
        };
        WebapiClient.prototype.isRequestEnableUntilReconnect = function () {
            return !!this.options.requestEnableUntilReconnect;
        };
        WebapiClient.prototype.generateWsUrl = function (path, ignoreAccessToken, ignoreSessionId) {
            var _a, _b;
            var sessionId = this.sessionId;
            var accessToken = this._getAccessToken();
            var deviceId = this.deviceId;
            var multisession = this.options.multisession;
            var wsurl = this.options.url.replace(new RegExp("^http"), "ws") + (path !== null && path !== void 0 ? path : "/ws/endpoint");
            var sessionParam = [];
            var sessionParams = (_a = this.options.sessionParams) !== null && _a !== void 0 ? _a : {};
            for (var key in sessionParams) {
                if ((key !== null && key !== void 0 ? key : false) && ((_b = sessionParams[key]) !== null && _b !== void 0 ? _b : false)) {
                    sessionParam.push("".concat(key.trim(), "=").concat(sessionParams[key].trim()));
                }
            }
            sessionParam.push("agent=".concat(this.options.userAgent.type.trim().toLowerCase(), "__").concat(LIB_VERSION$1, "__").concat("".concat(this.options.userAgent.version).trim()));
            if (this._forceOpenSocket) {
                sessionParam.push("force=true");
            }
            if (multisession) {
                sessionParam.push("multisession=true");
            }
            if (accessToken && !ignoreAccessToken) {
                sessionParam.push("access_token=".concat(accessToken));
            }
            if (deviceId) {
                sessionParam.push("deviceid=".concat(deviceId));
            }
            if (sessionId && !ignoreSessionId) {
                sessionParam.push("jsessionid=".concat(sessionId));
            }
            if (sessionParam.length > 0) {
                wsurl += ";" + sessionParam.map(function (p) { return p.replace(";", ""); }).join(";");
            }
            return wsurl;
        };
        WebapiClient.prototype.disconnect = function () {
            var notLoggedEvent = __assign$1({}, this._loginProfileSubject.value);
            notLoggedEvent.status = LoginProfileStatus.NOTLOGGED;
            notLoggedEvent.logged = false;
            this._handleLoginProfileEvent(notLoggedEvent);
        };
        WebapiClient.prototype.cleanAllCredential = function (clearPermanentData) {
            this._sessionId = undefined;
            this._cleanAccessToken(clearPermanentData);
        };
        WebapiClient.prototype.oneTimeLoginByAccessToken = function (accessToken) {
            return __awaiter$4(this, void 0, void 0, function () {
                var err_3, errorLoginProfile, error;
                return __generator$4(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (this.oneTimeLoginByAccessTokenDone) {
                                this._log.warn("oneTimeLoginByAccessToken was just called at ".concat(this.oneTimeLoginByAccessTokenDone.toISOString(), ", nothing to do"));
                                return [2 , false];
                            }
                            this.oneTimeLoginByAccessTokenDone = new Date();
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this._methods.loginByAccessToken(accessToken, this.options.rememberMe)];
                        case 2: return [2 , _a.sent()];
                        case 3:
                            err_3 = _a.sent();
                            this._log.error("Unable to login", err_3);
                            errorLoginProfile = { status: LoginProfileStatus.RETRY, logged: false, username: this.username };
                            error = ErrorResolver.login(err_3);
                            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_3;
                        case 4: return [2 ];
                    }
                });
            });
        };
        WebapiClient.version = LIB_VERSION$1;
        return WebapiClient;
    }());
    var WebapiClientLogConfigurator =  (function (_super) {
        __extends$3(WebapiClientLogConfigurator, _super);
        function WebapiClientLogConfigurator(
        client) {
            var _this = _super.call(this) || this;
            _this.client = client;
            var enableValue = _this.config.prefix ? _this.config.prefix + "*" : "*";
            var enabled = WebapiClientLogConfigurator.disableNamespace();
            if (enabled) {
                if (enabled !== "*" && _this.config.prefix && enabled.indexOf(_this.config.prefix) < 0) {
                    enabled += "," + enableValue;
                }
            }
            else {
                enabled = enableValue;
            }
            WebapiClientLogConfigurator.enableNamespace(enabled);
            return _this;
        }
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "config", {
            get: function () {
                return this.client.options.logConfig;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "enabled", {
            get: function () {
                return this.config.enabled;
            },
            set: function (enabled) {
                this.config.enabled = enabled;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "objectToJson", {
            get: function () {
                return this.config.objectToJson;
            },
            set: function (objectToJson) {
                this.config.objectToJson = !!objectToJson;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "instanceIdLogged", {
            get: function () {
                return this.config.instanceIdLogged;
            },
            set: function (instanceIdLogged) {
                this.config.instanceIdLogged = !!instanceIdLogged;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "logLevel", {
            get: function () {
                return this.enabled ? this.config.logLevel : LogLevel.None;
            },
            set: function (logLevel) {
                if (logLevel && logLevel >= LogLevel.Verbose && logLevel <= LogLevel.None) {
                    this.config.logLevel = logLevel;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "prefix", {
            get: function () {
                return this.config.prefix;
            },
            set: function (prefix) {
                this.config.prefix = prefix;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebapiClientLogConfigurator.prototype, "timestamp", {
            get: function () {
                return this.config.timestamp;
            },
            set: function (timestamp) {
                this.config.timestamp = !!timestamp;
            },
            enumerable: false,
            configurable: true
        });
        WebapiClientLogConfigurator.enableNamespace = function (namespace) {
            debug$1.enable(namespace);
        };
        WebapiClientLogConfigurator.disableNamespace = function () {
            return debug$1.disable();
        };
        return WebapiClientLogConfigurator;
    }(LogConfigurator));
    console.info("WebAPIclient loaded version ".concat(LIB_VERSION$1, " - Browser ").concat(JSON.stringify(browser)));

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

    var LocalMediaConfiguration =  (function () {
        function LocalMediaConfiguration(config, prefix) {
            this.audio = new LocalMediaConfigurationConstraints();
            this.video = new LocalMediaConfigurationConstraints();
            this.audio.bandwidth = 32;
            this.audio.constraints = {};
            this.video.bandwidth = 256;
            this.video.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: function (config, destination, prefix) { return new LocalMediaConfigurationConstraints(objectCheck(config), arrayConcat(prefix, ["audio"])); },
                video: function (config, destination, prefix) { return new LocalMediaConfigurationConstraints(objectCheck(config), arrayConcat(prefix, ["video"])); },
            },
        };
        return LocalMediaConfiguration;
    }());

    var RemoteMediaConfiguration =  (function () {
        function RemoteMediaConfiguration(config, prefix) {
            var local = new LocalMediaConfiguration();
            this.audio = { bandwidth: local.audio.bandwidth };
            this.video = { bandwidth: local.video.bandwidth };
            if (!config)
                return;
            loadConfig(prefix, RemoteMediaConfiguration.CHECK_OPTIONS, this, config);
        }
        RemoteMediaConfiguration.CHECK_OPTIONS = {
            mandatory: {},
            optional: {
                audio: function (options, destination, prefix) {
                    for (var opt in options) {
                        if (opt != "bandwidth") {
                            throw ConfigurationError.newInstance(arrayConcat(prefix, ["audio"]).join("."), options[opt], new Error("".concat(opt, " is not valid remote media audio options")));
                        }
                    }
                    var value = options.bandwidth ? numberCheck(options.bandwidth) : null;
                    return value ? options : value;
                },
                video: function (options, destination, prefix) {
                    for (var opt in options) {
                        if (opt != "bandwidth") {
                            throw ConfigurationError.newInstance(arrayConcat(prefix, ["video"]).join("."), options[opt], new Error("".concat(opt, " is not valid remote media video options")));
                        }
                    }
                    var value = options.bandwidth ? numberCheck(options.bandwidth) : null;
                    return value ? options : value;
                },
            },
        };
        return RemoteMediaConfiguration;
    }());

    var MediaConfiguration =  (function () {
        function MediaConfiguration(config, prefix) {
            this.local = new LocalMediaConfiguration();
            this.remote = new RemoteMediaConfiguration();
            this.audioLevelUpdateIntervalInMS = 50;
            delete this.remote.audio.constraints;
            delete this.remote.video.constraints;
            if (!config)
                return;
            loadConfig(prefix, MediaConfiguration.CHECK_OPTIONS, this, config);
        }
        MediaConfiguration.CHECK_OPTIONS = {
            mandatory: {},
            optional: {
                local: function (config, destination, prefix) { return new LocalMediaConfiguration(objectCheck(config), arrayConcat(prefix, ["local"])); },
                remote: function (config, destination, prefix) { return new RemoteMediaConfiguration(objectCheck(config), arrayConcat(prefix, ["remote"])); },
                audioLevelUpdateIntervalInMS: numberCheck,
            },
        };
        return MediaConfiguration;
    }());

    var WebRTCFieldSession =  (function () {
        function WebRTCFieldSession(answer, session) {
            this.answer = answer;
            this.session = session;
        }
        WebRTCFieldSession.fromObject = function (data) {
            if (data) {
                var 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;
            }
        };
        WebRTCFieldSession.prototype.toObject = function () {
            return this.session ? { session: this.session.toJson() } : null;
        };
        WebRTCFieldSession.prototype.isAnswer = function () {
            return this.answer;
        };
        return WebRTCFieldSession;
    }());
    var WebRTCFieldCandidate =  (function () {
        function WebRTCFieldCandidate(candidate, last) {
            this.candidate = candidate;
            this.last = last;
        }
        WebRTCFieldCandidate.fromObject = function (data) {
            var _a;
            if (data) {
                var candidate = null;
                if (data.candidate && data.candidate.length > 0) {
                    candidate = [];
                    for (var 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;
            }
        };
        WebRTCFieldCandidate.prototype.toObject = function () {
            var _a;
            var result = { last: (_a = this.last) !== null && _a !== void 0 ? _a : false };
            if (this.candidate && this.candidate.length) {
                result.candidate = this.candidate.map(function (candidate) { return candidate.toJson(); });
            }
            return result;
        };
        return WebRTCFieldCandidate;
    }());
    var WebRTCFieldAutoanswer =  (function () {
        function WebRTCFieldAutoanswer(after, media) {
            this.after = after;
            this.media = media;
            if (isNaN(after)) {
                this.after = null;
            }
            if (!media || Object.keys(media).length == 0) {
                this.media = null;
            }
        }
        WebRTCFieldAutoanswer.fromObject = function (data) {
            var _a;
            if (data) {
                var media_1 = null;
                if (data.media && data.media.length) {
                    media_1 = new MediaParamImpl();
                    data.media.forEach(function (e) { return (media_1[e] = true); });
                }
                var result = new WebRTCFieldAutoanswer((_a = data.after) !== null && _a !== void 0 ? _a : null, media_1);
                if (result.after == null && result.media == null) {
                    return null;
                }
                else {
                    return result;
                }
            }
            else {
                return null;
            }
        };
        WebRTCFieldAutoanswer.prototype.toObject = function () {
            if (this.after == null && this.media == null) {
                return null;
            }
            else {
                var result = {};
                if (this.after !== null) {
                    result.after = this.after;
                }
                if (this.media) {
                    result.media = MediaParam.toCallMedia(this.media);
                }
                return result;
            }
        };
        return WebRTCFieldAutoanswer;
    }());
    var WebRTCField =  (function () {
        function WebRTCField(clientid, sessionDescription, candidate, autoanswer, ring) {
            this.clientid = clientid;
            this.sessionDescription = sessionDescription;
            this.candidate = candidate;
            this.autoanswer = autoanswer;
            this.ring = ring;
        }
        WebRTCField.fromObject = function (data) {
            if (data) {
                var 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;
            }
        };
        WebRTCField.prototype.toObject = function () {
            var _a, _b;
            var 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;
        };
        return WebRTCField;
    }());

    var WebrtcConfig =  (function () {
        function WebrtcConfig(options, prefix) {
            this.enabled = false;
            this.enabledOnChannel = [ChannelType.PhoneCall, ChannelType.Video];
            this.trickleIcePolicy = TrickleIcePolicy.FullTrickle;
            this.iceGatherPolicy = ["host", "srflx", "relay"];
            this.audioDeviceInput = null;
            this.videoDeviceInput = null;
            this.audioDeviceOutput = null;
            this.audioDeviceSignalOutput = 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,
                enabledOnChannel: function (channels) {
                    if (channels) {
                        if (Array.isArray(channels)) {
                            for (var i = 0; i < channels.length; i++) {
                                if (channelTypeToId(channels[i]) === null) {
                                    return undefined;
                                }
                            }
                        }
                        else {
                            return undefined;
                        }
                    }
                    return channels;
                },
                iceServers: function (iceServers) {
                    if (Array.isArray(iceServers)) {
                        return iceServers;
                    }
                    else {
                        return undefined;
                    }
                },
                trickleIcePolicy: function (trickleIcePolicy) {
                    var 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: function (iceGatherPolicy) {
                    var value = objectCheck(iceGatherPolicy);
                    if (value && value.length) {
                        var mappedValue = value
                            .filter(function (item, pos, self) { return self.indexOf(item) == pos; })
                            .map(function (item) { return item.trim().toLowerCase(); })
                            .filter(function (item) { return item === "host" || item === "srflx" || item === "relay"; });
                        return mappedValue.length ? mappedValue : undefined;
                    }
                    else {
                        return undefined;
                    }
                },
                audioDeviceInput: function (device) {
                    if (device && device.hasOwnProperty("deviceId")) {
                        return device;
                    }
                    else {
                        return undefined;
                    }
                },
                videoDeviceInput: function (device) {
                    if (device && device.hasOwnProperty("deviceId")) {
                        return device;
                    }
                    else {
                        return undefined;
                    }
                },
                audioDeviceOutput: function (device) {
                    if (device && device.hasOwnProperty("deviceId")) {
                        return device;
                    }
                    else {
                        return undefined;
                    }
                },
                audioDeviceSignalOutput: function (device) {
                    if (device && device.hasOwnProperty("deviceId")) {
                        return device;
                    }
                    else {
                        return undefined;
                    }
                },
                videoStreamInOffer: booleanCheck,
                immediateRingback: booleanCheck,
                connectionTimeout: numberCheck,
                deadStreamTimeout: numberCheck,
                mediaConfiguration: function (mediaConfiguration, destination, prefix) {
                    var value = objectCheck(mediaConfiguration);
                    return value ? new MediaConfiguration(value, arrayConcat(prefix, ["mediaConfiguration"])) : value;
                },
                notifyAvailableMedia: booleanCheck,
                notifyMediaFeature: booleanCheck,
                mediaSignal: function (mediaSignal, destination, prefix) {
                    var value = objectCheck(mediaSignal);
                    return value ? new WebRTCMediaSignal(value, arrayConcat(prefix, ["mediaSignal"])) : value;
                },
            },
        };
        return WebrtcConfig;
    }());
    var TrickleIcePolicy;
    (function (TrickleIcePolicy) {
        TrickleIcePolicy["NotSupported"] = "NotSupported";
        TrickleIcePolicy["FullTrickle"] = "FullTrickle";
        TrickleIcePolicy["HalfTrickle"] = "HalfTrickle";
    })(TrickleIcePolicy || (TrickleIcePolicy = {}));

    var __extends$2 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 = (undefined && undefined.__assign) || function () {
        __assign = Object.assign || function(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);
    };
    var __awaiter$3 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$3 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var Call$1 =  (function () {
        function Call(_manager, _controlMessageNotifier, _callConnectionState, _callId, _channelType, _isOffer, state, realState) {
            var _this = this;
            this._manager = _manager;
            this._controlMessageNotifier = _controlMessageNotifier;
            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._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(function (connectionState) {
                    return {
                        callId: _this._callId,
                        connectionState: connectionState,
                    };
                }))
                    .subscribe(function (data) { return _callConnectionState === null || _callConnectionState === void 0 ? void 0 : _callConnectionState.next(data); });
            }
            this.setSignalingState(state, realState, false);
            this._controlMessageSubscription = _controlMessageNotifier.pipe(filter(function (message) { return message && message.callId === _this.callId; })).subscribe(function (controlMessage) {
                _this._lastControlMessage = controlMessage;
                if (!_this._device && controlMessage.device && controlMessage.deviceType === ExtenType.WEBRTC) {
                    _this._device = controlMessage.device;
                }
            });
            this._updateFields
                .pipe(debounceTime(10), throttle(function (action) { return _this.updateWebRTCFields(action.sendUpdate).toPromise(); }, { leading: false, trailing: true }), catchError(function (err) {
                _this._log.error("Error on updateWebRTCFields", err);
                return of(false);
            }))
                .subscribe();
            this._mediaEnabled = false;
        }
        Call.prototype.canDoAction = function () {
            return this.managedCall && !this.callIsForApp && this.mediaOwnedByCurrentInstance;
        };
        Object.defineProperty(Call.prototype, "callIsForApp", {
            get: function () {
                return this.channelType === ChannelType.PhoneCall && this._deviceIsApp;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "managedCall", {
            get: function () {
                return this._manager.client.phoneManagerActive;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "mediaOwnedByCurrentInstance", {
            get: function () {
                return this._mediaOwnerId === this._manager.client.instanceId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "mediaOwnerId", {
            set: function (mediaOwnerId) {
                this._mediaOwnerId = mediaOwnerId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "manager", {
            get: function () {
                return this._manager;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "layoutManager", {
            get: function () {
                return this._layoutManager;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "remoteMedia", {
            get: function () {
                return this._remoteMedia;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "remoteDescription", {
            get: function () {
                var _a;
                return (_a = this._remoteDescription) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "localDescription", {
            get: function () {
                var _a;
                return (_a = this._localDescription) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "channelType", {
            get: function () {
                return this._channelType;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "dialParams", {
            get: function () {
                return this._dialParams;
            },
            set: function (params) {
                this._dialParams = params;
                if (params && params.params.fromDevice) {
                    this._deviceIsApp = params.isForApp();
                    if (this.callIsForApp || !this.managedCall) {
                        this._toneSignalEnabled = false;
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "mediaEnabled", {
            set: function (mediaEnabled) {
                this._mediaEnabled = mediaEnabled;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "remoteWebrtcfield", {
            set: function (webrtcfield) {
                this._remoteWebrtcfield = webrtcfield;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "callId", {
            get: function () {
                return this._callId;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "deviceIsApp", {
            get: function () {
                return this._deviceIsApp;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "remoteCallMedia", {
            get: function () {
                return this._remoteCallMedia;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "localCallMedia", {
            get: function () {
                return this._localCallMedia;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "localMedia", {
            get: function () {
                return this._localMedia;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "connection", {
            get: function () {
                return this._connection;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "waitForAnswer", {
            get: function () {
                return this._waitForAnswer;
            },
            set: function (waitForAnswer) {
                this._waitForAnswer = waitForAnswer;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "signalingState", {
            get: function () {
                return this._signalingState;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "realState", {
            get: function () {
                return this._isRealState;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "autoanswer", {
            get: function () {
                return this._autoanswer;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "isOffer", {
            get: function () {
                return this._isOffer;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "videoContainer", {
            get: function () {
                var _a;
                return (_a = this.layoutManager) === null || _a === void 0 ? void 0 : _a.container;
            },
            set: function (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;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "toneSignalEnabled", {
            get: function () {
                return this._toneSignalEnabled;
            },
            set: function (toneSignalEnabled) {
                this._toneSignalEnabled = toneSignalEnabled;
            },
            enumerable: false,
            configurable: true
        });
        Call.prototype.connectionActionQueue = function (action) {
            return __awaiter$3(this, void 0, void 0, function () {
                var logPrefix, result;
                var _this = this;
                return __generator$3(this, function (_a) {
                    logPrefix = "connection queue - ".concat(this.callId, " - ").concat(this._connectionActionQueueId++, " -");
                    this._log.debug("".concat(logPrefix, " request to execute action"));
                    result = this._connectionActionQueue
                        .then(function () { return __awaiter$3(_this, void 0, void 0, function () {
                        return __generator$3(this, function (_a) {
                            this._log.debug("".concat(logPrefix, " execute action"));
                            return [2 , action()];
                        });
                    }); })
                        .then(function (result) {
                        _this._log.debug("".concat(logPrefix, " action ended"));
                        return result;
                    });
                    this._connectionActionQueue = result.catch(function (err) {
                        _this._log.debug("".concat(logPrefix, " action error"), err);
                    });
                    return [2 , result];
                });
            });
        };
        Call.prototype.setSignalingState = function (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();
            }
        };
        Call.prototype.markAsClosedLocal = function () {
            this._closedLocal = true;
        };
        Call.prototype.isClosedLocal = function () {
            return this._closedLocal;
        };
        Call.prototype.getLocalAudioLevel = function () {
            return this.canDoAction() ? this._localAudioLevel.start() : EMPTY;
        };
        Call.prototype.getRemoteAudioLevel = function () {
            return this.canDoAction() ? this._remoteAudioLevel.start() : EMPTY;
        };
        Call.prototype.getLocalVideoFrame = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    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 [2 , 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");
                        }
                    }
                    return [2 ];
                });
            });
        };
        Call.prototype.getRemoteVideoFrame = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    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 [2 , 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");
                        }
                    }
                    return [2 ];
                });
            });
        };
        Call.prototype.generateLocalWebRTCField = function () {
            var localSessionDescription = null;
            var localCandidate = null;
            if (this.canDoAction()) {
                var 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);
        };
        Call.prototype.localDescriptionIsNotified = function () {
            this._localDescriptionToSend = null;
        };
        Call.prototype.initTlinkConnection = function () {
            var _a, _b;
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (!(!this.managedCall || this.callIsForApp || !this._mediaEnabled || !this.mediaOwnedByCurrentInstance)) return [3 , 1];
                            return [2 , this];
                        case 1: return [4 , this.createTlinkConnection()];
                        case 2:
                            _c.sent();
                            return [4 , this.updateRemoteWebrtcFields()];
                        case 3:
                            _c.sent();
                            if (!this.sessionDescriptionChange(this._remoteDescription, (_b = (_a = this._connection) === null || _a === void 0 ? void 0 : _a.remoteDescription) !== null && _b !== void 0 ? _b : null)) return [3 , 5];
                            return [4 , this._connection.setRemoteDescription(this._remoteDescription)];
                        case 4:
                            _c.sent();
                            _c.label = 5;
                        case 5: return [4 , this.createAndSetLocalDescription(false)];
                        case 6:
                            _c.sent();
                            return [4 , this.notifyConnectionState()];
                        case 7:
                            _c.sent();
                            if (this._signalingState === CallState.CONNECTED && this._connectionStateConnected) {
                                this._connectionState.next(this._connectionStateConnected);
                                delete this._connectionStateConnected;
                            }
                            return [2 , this];
                    }
                });
            });
        };
        Call.prototype.tryAutoanswer = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var answerAfter, mediaOfAnswer_1, video_1, devices, e_1;
                var _this = this;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this.managedCall && !this.callIsForApp && this._remoteWebrtcfield && this._remoteWebrtcfield.autoanswer && !this._autoanswer)) return [3 , 7];
                            answerAfter = this._remoteWebrtcfield.autoanswer.after;
                            mediaOfAnswer_1 = this._remoteWebrtcfield.autoanswer.media;
                            if (!(answerAfter != null && mediaOfAnswer_1 && Object.keys(mediaOfAnswer_1).length)) return [3 , 5];
                            video_1 = mediaOfAnswer_1.video;
                            this._autoanswer = true;
                            this._log.info("Call ".concat(this._callId, " is in autoanswer, answer after ").concat(answerAfter, " with media ").concat(Array.from(MediaParam.toCallMedia(mediaOfAnswer_1)).join("-")));
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this._manager.device.status.pipe(timeout(100), first()).toPromise()];
                        case 2:
                            devices = _a.sent();
                            video_1 = video_1 && !!devices.devices.videoInput && !!devices.devices.videoInput.length;
                            return [3 , 4];
                        case 3:
                            e_1 = _a.sent();
                            this._log.error("error on getMediaDeviceStatus for autoanswer", e_1);
                            return [3 , 4];
                        case 4:
                            setTimeout(function () { return __awaiter$3(_this, void 0, void 0, function () {
                                var answerResult, err_1;
                                return __generator$3(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            if (!(this._signalingState === CallState.NEW_INBOUND)) return [3 , 6];
                                            this._log.info("Call ".concat(this._callId, " autoanswer start"));
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 4, , 5]);
                                            answerResult = this._manager.methods.answer(this._channelType, this._callId, new MediaParamImpl(__assign(__assign({}, mediaOfAnswer_1), { video: video_1 })));
                                            if (!answerResult) return [3 , 3];
                                            return [4 , answerResult.toPromise()];
                                        case 2:
                                            _a.sent();
                                            _a.label = 3;
                                        case 3:
                                            this._log.info("Call ".concat(this._callId, " - autoanswer end"));
                                            return [3 , 5];
                                        case 4:
                                            err_1 = _a.sent();
                                            this._log.info("Call ".concat(this._callId, " - autoanswer failed"), err_1);
                                            return [3 , 5];
                                        case 5: return [3 , 7];
                                        case 6:
                                            this._log.info("Call ".concat(this._callId, " - cannot start autoanswer, call state is ").concat(this._signalingState, ", expected NEW_INBOUND"));
                                            _a.label = 7;
                                        case 7: return [2 ];
                                    }
                                });
                            }); }, 200 + (answerAfter < 0 ? 0 : answerAfter) * 1000);
                            return [3 , 6];
                        case 5:
                            this._log.info("Call ".concat(this._callId, " is in autoanswer but 'after' and 'media' is not set"));
                            _a.label = 6;
                        case 6:
                            delete this._remoteWebrtcfield.autoanswer;
                            _a.label = 7;
                        case 7: return [2 ];
                    }
                });
            });
        };
        Call.prototype.sendDTMF = function (dtmf, playTone, dtmfDuration, dtmfInterToneGap) {
            if (dtmfDuration === void 0) { dtmfDuration = this._manager.options.mediaSignal.dtmfDuration; }
            if (dtmfInterToneGap === void 0) { dtmfInterToneGap = this._manager.options.mediaSignal.dtmfInterToneGap; }
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!playTone) return [3 , 2];
                            return [4 , this._manager.phoneSignal.playDTMF(this.callId, dtmf, dtmfDuration, dtmfInterToneGap)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            if (this.connection) {
                                try {
                                    this.connection.insertDTMF(dtmf, dtmfDuration, dtmfInterToneGap);
                                    return [2 , true];
                                }
                                catch (err) {
                                    this._log.debug("Call non support dtmf mode rfc2833, notify with action");
                                    return [2 , false];
                                }
                            }
                            else {
                                return [2 , false];
                            }
                            return [2 ];
                    }
                });
            });
        };
        Call.prototype.isTrickleIcePolicyOneOf = function () {
            var policyToCheck = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                policyToCheck[_i] = arguments[_i];
            }
            if (policyToCheck) {
                while (policyToCheck.length) {
                    if (this._manager.trickleIcePolicy === policyToCheck.pop()) {
                        return true;
                    }
                }
            }
            return false;
        };
        Call.prototype.retriveCallMediaFromSessionDescription = function (sessionDescription) {
            var 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;
        };
        Call.prototype.signallingWebRTCFields = function (sendUpdate) {
            if (this.mediaOwnedByCurrentInstance) {
                this._updateFields.next({ sendUpdate: sendUpdate });
            }
        };
        Call.prototype.updateWebRTCFields = function (sendUpdate) {
            var _this = this;
            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(function (onServer) { return onServer; }), take(1), timeout(5000), map(function () { return _this.generateLocalWebRTCField(); }), switchMap(function (webrtcField) {
                        if (webrtcField.candidate || webrtcField.sessionDescription) {
                            var result = _this._manager.methods.updateWebRTCFields(_this._callId, _this._localCallMedia, webrtcField);
                            _this._localDescriptionToSend = null;
                            _this._localCandidateToSend.length = 0;
                            return result;
                        }
                        else {
                            return of(false);
                        }
                    }));
                }
                else {
                    return of(false);
                }
            }
            else {
                return of(false);
            }
        };
        Call.prototype.sessionDescriptionChange = function (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());
        };
        Call.prototype.createOfferOptions = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    return [2 , this._offerOptions];
                });
            });
        };
        Call.prototype.createAnswerOption = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    return [2 , this._answerOptions];
                });
            });
        };
        Call.prototype.createAndSetLocalDescription = function (force) {
            var _a;
            return __awaiter$3(this, void 0, void 0, function () {
                var createOffer, createAnswer, sessionDescription, _b, _c, _d, _e, _f, e_2, e_3;
                return __generator$3(this, function (_g) {
                    switch (_g.label) {
                        case 0:
                            if (!(this._mediaEnabled && this.mediaOwnedByCurrentInstance && this._connection && (force || !this._localDescription))) return [3 , 14];
                            createOffer = false;
                            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)) return [3 , 12];
                            sessionDescription = null;
                            _g.label = 1;
                        case 1:
                            _g.trys.push([1, 7, , 8]);
                            if (!createOffer) return [3 , 3];
                            _d = (_c = this._connection).createOffer;
                            return [4 , this.createOfferOptions()];
                        case 2:
                            _b = _d.apply(_c, [_g.sent()]);
                            return [3 , 5];
                        case 3:
                            _f = (_e = this._connection).createAnswer;
                            return [4 , this.createAnswerOption()];
                        case 4:
                            _b = _f.apply(_e, [_g.sent()]);
                            _g.label = 5;
                        case 5: return [4 , (_b)];
                        case 6:
                            sessionDescription = _g.sent();
                            return [3 , 8];
                        case 7:
                            e_2 = _g.sent();
                            this._log.warn("error on ".concat(createOffer ? "createOffer" : "createAnswer"), e_2);
                            throw e_2;
                        case 8:
                            _g.trys.push([8, 10, , 11]);
                            return [4 , this._connection.setLocalDescription(sessionDescription)];
                        case 9: return [2 , _g.sent()];
                        case 10:
                            e_3 = _g.sent();
                            this._log.warn("error on setLocalDescription", e_3);
                            throw e_3;
                        case 11: return [3 , 13];
                        case 12: return [2 , this._localDescription];
                        case 13: return [3 , 15];
                        case 14: return [2 , this._localDescription];
                        case 15: return [2 ];
                    }
                });
            });
        };
        Call.prototype.setAudioOutputDevice = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var audioOutputDevice, err_2;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.mediaOwnedByCurrentInstance) return [3 , 4];
                            audioOutputDevice = this._manager.device.audioOutput;
                            if (!(audioOutputDevice && audioOutputDevice != this._remoteMedia.audioOutput)) return [3 , 4];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this._remoteMedia.setAudioOutput(audioOutputDevice)];
                        case 2:
                            _a.sent();
                            this._log.debug("Audio Output Device set to ".concat(JSON.stringify(audioOutputDevice)));
                            return [3 , 4];
                        case 3:
                            err_2 = _a.sent();
                            this._log.error("Error on changeAudioSinkOutput", err_2);
                            return [3 , 4];
                        case 4: return [2 ];
                    }
                });
            });
        };
        Call.prototype.createTlinkConnection = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var _a, _b, defaultTimeout_1, defaultDeadStreamTimeout_1, trickeIceDisabled;
                var _c;
                var _this = this;
                return __generator$3(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 3];
                            if (!(this._connection === undefined || this._connection.state === Connection.State.Closed)) {
                                return [2 , this];
                            }
                            _a = this;
                            _b = Connection.bind;
                            _c = {};
                            return [4 , this._manager.getIceServers()];
                        case 1:
                            _a._connection = new (_b.apply(Connection, [void 0, (_c.iceServers = _d.sent(), _c), this._localMedia, this._remoteMedia]))();
                            this._connection.id = this._callId;
                            defaultTimeout_1 = this._manager.options.connectionTimeout ? this._manager.options.connectionTimeout : this._connection.timeout;
                            defaultDeadStreamTimeout_1 = this._manager.options.deadStreamTimeout ? this._manager.options.deadStreamTimeout : this._connection.deadStreamTimeout;
                            trickeIceDisabled = this.isTrickleIcePolicyOneOf(Connection.TrickleIcePolicy.NotSupported, Connection.TrickleIcePolicy.HalfTrickle);
                            this._connection.timeout = trickeIceDisabled ? 7200000 : defaultTimeout_1;
                            this._connection.deadStreamTimeout = trickeIceDisabled ? 7200000 : defaultDeadStreamTimeout_1;
                            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", function (candidate) {
                                _this._localCandidateToSend.push(candidate);
                                _this.signallingWebRTCFields(false);
                            });
                            this._connection.on("localDescription", function (sessionDescription) {
                                var origin = sessionDescription.sdp.origin;
                                if (origin)
                                    origin.username = "WebAPIclient-".concat(LIB_VERSION$1);
                                _this.manageBandwidth(false, sessionDescription);
                                _this._localDescriptionToSend = sessionDescription;
                                _this._localDescription = sessionDescription;
                                _this.signallingWebRTCFields(false);
                            });
                            this._connection.on("remoteDescription", function (sessionDescription) {
                                _this.manageBandwidth(true, sessionDescription);
                                _this._remoteDescription = sessionDescription;
                            });
                            if (this.isTrickleIcePolicyOneOf(Connection.TrickleIcePolicy.FullTrickle, Connection.TrickleIcePolicy.HalfTrickle)) {
                                this._connection.on("gatheringStateChange", function (state) {
                                    if (state === Connection.IceGatheringState.Complete) {
                                        _this.signallingWebRTCFields(true);
                                    }
                                });
                            }
                            this._connection.on("sendDtmfToneChange", function (tone) {
                                _this._log.info("".concat(_this._callId, " - Sender's DTMF tone is changing: ").concat(tone));
                            });
                            this._connection.on("stateChange", function (connectionState) {
                                var _a, _b;
                                var connectionError = !!_this._connection.error;
                                if (connectionError) {
                                    _this._log.info("".concat(_this._callId, " - Connection state is ").concat(connectionState, "."), _this._connection.error.getException());
                                }
                                else {
                                    _this._log.info("".concat(_this._callId, " - Connection state is ").concat(connectionState, "."));
                                }
                                var connectionStateNotification = {
                                    callId: _this._callId,
                                    state: connectionState,
                                    error: connectionError ? _this._connection.error : null,
                                };
                                switch (connectionState) {
                                    case Connection.State.Connecting:
                                        setTimeout(function () { return _this.setAudioOutputDevice(); });
                                        break;
                                    case Connection.State.Connected:
                                        _this.startConnectionStats();
                                        _this._connection.timeout = defaultTimeout_1;
                                        _this._connection.deadStreamTimeout = defaultDeadStreamTimeout_1;
                                        _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);
                                }
                            });
                            return [4 , this._connection.start()];
                        case 2:
                            _d.sent();
                            _d.label = 3;
                        case 3: return [2 , this];
                    }
                });
            });
        };
        Call.prototype.manageBandwidth = function (local, sessionDescription) {
            var _this = this;
            var audioData = { callMedia: CallMedia.audio, maxBandwidth: 0 };
            var videoData = { callMedia: CallMedia.video, maxBandwidth: 0 };
            var 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(function (data) {
                try {
                    var media = sessionDescription.extractMedia(data.callMedia.toString());
                    if (media && media.length && data.maxBandwidth) {
                        media.forEach(function (m) {
                            var addAttribute = data.callMedia === CallMedia.video;
                            if (!addAttribute || data.callMedia === CallMedia.audio) {
                                addAttribute = !!m.rtp.find(function (rtpMapAttribute) { return 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);
                }
            });
        };
        Call.prototype.notifyConnectionState = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var _this = this;
                return __generator$3(this, function (_a) {
                    if (this.canDoAction() && this._isRealState) {
                        if (this._connectionStates.length) {
                            this._connectionStates.forEach(function (state) { return _this._connectionState.next(state); });
                            this._connectionStates.length = 0;
                        }
                        if (this._localDescriptionToSend || this._localCandidateToSend.length) {
                            this.signallingWebRTCFields(true);
                        }
                    }
                    return [2 ];
                });
            });
        };
        Call.prototype.updateRemoteWebrtcFields = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var webrtcfields, webrtcFieldsWithSdp, remoteDescriptionHasChanged, receivedValidSdp, e_4;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            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)))) return [3 , 8];
                            webrtcfields = __assign({}, this._remoteWebrtcfield);
                            webrtcFieldsWithSdp = !!(webrtcfields.sessionDescription && webrtcfields.sessionDescription.session);
                            remoteDescriptionHasChanged = webrtcFieldsWithSdp && (!this._remoteDescription || this.sessionDescriptionChange(this._remoteDescription, webrtcfields.sessionDescription.session));
                            this._remoteWebrtcfield = null;
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 7, , 8]);
                            receivedValidSdp = webrtcFieldsWithSdp && remoteDescriptionHasChanged;
                            if (!(this._connection.state !== Connection.State.Connected && receivedValidSdp)) return [3 , 3];
                            return [4 , this._connection.setRemoteDescription(webrtcfields.sessionDescription.session)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [4 , this.createAndSetLocalDescription(false)];
                        case 4:
                            _a.sent();
                            if (!(webrtcfields.candidate && webrtcfields.candidate.candidate && webrtcfields.candidate.candidate.length)) return [3 , 6];
                            return [4 , this._connection.addRemoteCandidates(webrtcfields.candidate.candidate)];
                        case 5:
                            _a.sent();
                            _a.label = 6;
                        case 6: return [3 , 8];
                        case 7:
                            e_4 = _a.sent();
                            this._log.error("error on updateWebrtcFields", e_4);
                            return [3 , 8];
                        case 8: return [2 ];
                    }
                });
            });
        };
        Call.prototype.close = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this.managedCall && !this.callIsForApp)) return [3 , 2];
                            return [4 , this._manager.phoneSignal.stop(this._callId, false)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            this.closeConnection();
                            this._controlMessageSubscription.unsubscribe();
                            this._updateFields.complete();
                            this._callIsOnServer.complete();
                            this._localAudioLevel.end();
                            this._remoteAudioLevel.end();
                            this._connectionState.complete();
                            return [2 ];
                    }
                });
            });
        };
        Call.prototype.closeConnection = function () {
            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();
        };
        Call.prototype.toggleAudioMute = function (mute, notifyMediaFeature) {
            if (notifyMediaFeature === void 0) { notifyMediaFeature = true; }
            return __awaiter$3(this, void 0, void 0, function () {
                var result, err_3;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 8];
                            result = this.toggleMediaTrackMuted(this._localMedia, true, mute);
                            if (!this._localMedia) return [3 , 7];
                            if (!notifyMediaFeature) return [3 , 7];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 5, , 7]);
                            return [4 , this.notifyCallMediaState({ audio: true })];
                        case 2:
                            result = _a.sent();
                            if (!!result) return [3 , 4];
                            return [4 , this.toggleAudioMute(!mute, false)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [3 , 7];
                        case 5:
                            err_3 = _a.sent();
                            return [4 , this.toggleAudioMute(!mute, false)];
                        case 6:
                            _a.sent();
                            throw err_3;
                        case 7: return [2 , result];
                        case 8: return [2 , false];
                    }
                });
            });
        };
        Call.prototype.toggleVideoMute = function (mute, notifyMediaFeature) {
            if (notifyMediaFeature === void 0) { notifyMediaFeature = true; }
            return __awaiter$3(this, void 0, void 0, function () {
                var result, err_4;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 8];
                            result = this.toggleMediaTrackMuted(this._localMedia, false, mute);
                            if (!this._localMedia) return [3 , 7];
                            if (!notifyMediaFeature) return [3 , 7];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 5, , 7]);
                            return [4 , this.notifyCallMediaState(new MediaParamImpl({ video: true }))];
                        case 2:
                            result = _a.sent();
                            if (!!result) return [3 , 4];
                            return [4 , this.toggleVideoMute(!mute, false)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [3 , 7];
                        case 5:
                            err_4 = _a.sent();
                            return [4 , this.toggleVideoMute(!mute, false)];
                        case 6:
                            _a.sent();
                            throw err_4;
                        case 7: return [2 , result];
                        case 8: return [2 , false];
                    }
                });
            });
        };
        Call.prototype.toggleRemoteAudioMute = function (mute) {
            return __awaiter$3(this, void 0, void 0, function () {
                var result;
                return __generator$3(this, function (_a) {
                    if (this.canDoAction()) {
                        result = this.toggleMediaTrackMuted(this._remoteMedia, true, mute);
                        if (this._remoteMedia && this._remoteMedia.stream) {
                            this.publishLastCallInfo();
                        }
                        return [2 , result];
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        Call.prototype.toggleRemoteVideoMute = function (mute) {
            return __awaiter$3(this, void 0, void 0, function () {
                var result;
                return __generator$3(this, function (_a) {
                    if (this.canDoAction()) {
                        result = this.toggleMediaTrackMuted(this._remoteMedia, false, mute);
                        if (this._remoteMedia && this._remoteMedia.stream) {
                            this.publishLastCallInfo();
                        }
                        return [2 , result];
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        Call.prototype.isAudioEnabled = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    if (this.canDoAction()) {
                        return [2 , this._remoteDescription ? !!this.retriveCallMediaFromSessionDescription(this._remoteDescription).audio : true];
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        Call.prototype.isVideoEnabled = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    if (this.canDoAction()) {
                        return [2 , this._remoteDescription ? !!this.retriveCallMediaFromSessionDescription(this._remoteDescription).video : true];
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        Call.prototype.startAudio = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var newMedia;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 8];
                            return [4 , this.isAudioEnabled()];
                        case 1:
                            if (!_a.sent()) return [3 , 6];
                            if (!this._localMedia) return [3 , 5];
                            if (!!this._localCallMedia.audio) return [3 , 4];
                            newMedia = new MediaParamImpl(__assign({}, this._localCallMedia));
                            newMedia.audio = true;
                            return [4 , this.setLocalMedia(newMedia, this._mediaConstraints)];
                        case 2:
                            _a.sent();
                            return [4 , this.toggleAudioMute(false, false)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4: return [2 , true];
                        case 5: return [2 , false];
                        case 6: throw new Error("Unable to start audio, remote peer is not supporting");
                        case 7: return [3 , 9];
                        case 8: return [2 , false];
                        case 9: return [2 ];
                    }
                });
            });
        };
        Call.prototype.stopAudio = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var newMedia;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 5];
                            return [4 , this.toggleAudioMute(true, false)];
                        case 1:
                            _a.sent();
                            if (!this._localMedia) return [3 , 4];
                            if (!this._localCallMedia.audio) return [3 , 3];
                            newMedia = new MediaParamImpl(__assign({}, this._localCallMedia));
                            newMedia.audio = false;
                            return [4 , this.setLocalMedia(newMedia, this._mediaConstraints)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [2 , true];
                        case 4: return [2 , false];
                        case 5: return [2 , false];
                    }
                });
            });
        };
        Object.defineProperty(Call.prototype, "audioLinkStatus", {
            get: function () {
                if (this.canDoAction()) {
                    return this._localMedia && this._localMedia.stream ? (this._localMedia.audioLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
                }
                else {
                    return null;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "audioRemoteLinkStatus", {
            get: function () {
                if (this.canDoAction()) {
                    return this._remoteMedia && this._remoteMedia.stream ? (this._remoteMedia.audioLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
                }
                else {
                    return null;
                }
            },
            enumerable: false,
            configurable: true
        });
        Call.prototype.startVideo = function (mediaConstraints, videoContainer) {
            return __awaiter$3(this, void 0, void 0, function () {
                var newMedia;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 8];
                            return [4 , this.isVideoEnabled()];
                        case 1:
                            if (!_a.sent()) return [3 , 6];
                            if (!(this._localMedia && !this._localCallMedia.video)) return [3 , 4];
                            if (videoContainer) {
                                this.videoContainer = videoContainer;
                            }
                            if (mediaConstraints && this._mediaConstraints) {
                                this._mediaConstraints.local.video = new LocalMediaConfigurationConstraints(mediaConstraints);
                            }
                            newMedia = new MediaParamImpl(__assign({}, this._localCallMedia));
                            newMedia.video = true;
                            return [4 , this.setLocalMedia(newMedia, this._mediaConstraints)];
                        case 2:
                            _a.sent();
                            return [4 , this.toggleVideoMute(false, false)];
                        case 3:
                            _a.sent();
                            return [2 , this.notifyVideoStartOrStop()];
                        case 4: return [2 , false];
                        case 5: return [3 , 7];
                        case 6: throw new Error("Unable to start video, remote peer is not supporting");
                        case 7: return [3 , 9];
                        case 8: return [2 , false];
                        case 9: return [2 ];
                    }
                });
            });
        };
        Call.prototype.stopVideo = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                var newMedia;
                return __generator$3(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 5];
                            return [4 , this.toggleVideoMute(true, false)];
                        case 1:
                            _a.sent();
                            if (!(this._localMedia && this._localCallMedia.video)) return [3 , 3];
                            newMedia = new MediaParamImpl(__assign({}, this._localCallMedia));
                            newMedia.video = false;
                            return [4 , this.setLocalMedia(newMedia, this._mediaConstraints)];
                        case 2:
                            _a.sent();
                            return [2 , this.notifyVideoStartOrStop()];
                        case 3: return [2 , false];
                        case 4: return [3 , 6];
                        case 5: return [2 , false];
                        case 6: return [2 ];
                    }
                });
            });
        };
        Object.defineProperty(Call.prototype, "videoLinkStatus", {
            get: function () {
                if (this.canDoAction()) {
                    return this._localMedia && this._localMedia.stream ? (this._localMedia.videoLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
                }
                else {
                    return null;
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Call.prototype, "videoRemoteLinkStatus", {
            get: function () {
                if (this.canDoAction()) {
                    return this._remoteMedia && this._remoteMedia.stream ? (this._remoteMedia.videoLinkStatus === WebRtcMedia.LinkStatus.MUTE ? CallMediaLinkStatus.MUTE : CallMediaLinkStatus.UNMUTE) : null;
                }
                else {
                    return null;
                }
            },
            enumerable: false,
            configurable: true
        });
        Call.prototype.toggleMediaTrackMuted = function (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;
            }
        };
        Call.prototype.stopConnectionStats = function () {
            this._connectionStats.stop();
            this._localAudioLevel.stop();
            this._remoteAudioLevel.stop();
        };
        Call.prototype.startConnectionStats = function () {
            if (this.canDoAction()) {
                this._connectionStats.active = true;
            }
        };
        Call.prototype.getConnectionStats = function () {
            return this._connectionStats.start();
        };
        Call.prototype.changeLocalMedia = function (media, mediaConfiguration) {
            var _a, _b;
            return __awaiter$3(this, void 0, void 0, function () {
                var mediaConstraints, audioEnable, desktopEnable, audioInput, videoInput;
                return __generator$3(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 5];
                            return [4 , this.mediaConfigurationToLocalMediaConstraints(mediaConfiguration)];
                        case 1:
                            mediaConstraints = _c.sent();
                            return [4 , ((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.changeConstraints(mediaConstraints))];
                        case 2:
                            _c.sent();
                            audioEnable = !!this._localCallMedia.audio;
                            desktopEnable = !!this._localCallMedia.desktop;
                            !!this._localCallMedia.video;
                            audioInput = void 0;
                            if (audioEnable && this._manager.device.audioInput) {
                                audioInput = this._manager.device.audioInput;
                            }
                            videoInput = void 0;
                            if (mediaConstraints.video && !desktopEnable && typeof this._manager.device.videoInput !== "boolean" && this._manager.device.videoInput) {
                                videoInput = this._manager.device.videoInput;
                            }
                            if (!(audioInput || videoInput)) return [3 , 4];
                            return [4 , ((_b = this._localMedia) === null || _b === void 0 ? void 0 : _b.changeAudioVideoInput(audioInput, videoInput))];
                        case 3:
                            _c.sent();
                            _c.label = 4;
                        case 4: return [2 , true];
                        case 5: return [2 , false];
                    }
                });
            });
        };
        Call.prototype.mediaConfigurationToLocalMediaConstraints = function (mediaConfiguration) {
            return __awaiter$3(this, void 0, void 0, function () {
                var audioEnable, videoEnable, desktopEnable, audioConfig, videoConfig, constraints, _a;
                return __generator$3(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            this._mediaConstraints = new MediaConfiguration(mediaConfiguration);
                            audioEnable = !!this._localCallMedia.audio;
                            videoEnable = !!this._localCallMedia.video;
                            desktopEnable = !!this._localCallMedia.desktop;
                            audioConfig = audioEnable;
                            videoConfig = videoEnable || desktopEnable ? {} : false;
                            if (!!(this._mediaConstraints || null) && this._mediaConstraints.local) {
                                constraints = this._mediaConstraints.local;
                                if (audioConfig && constraints.audio && constraints.audio.constraints) {
                                    if (Object.keys(constraints.audio.constraints).length > 0) {
                                        audioConfig = __assign({}, constraints.audio.constraints);
                                    }
                                }
                                if (videoConfig && constraints.video && constraints.video.constraints) {
                                    if (Object.keys(constraints.video.constraints).length > 0) {
                                        videoConfig = __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 ".concat(JSON.stringify(audioConfig, MapOrSet_toJSON)));
                            }
                            if (!!videoConfig && !desktopEnable) {
                                this._log.info("local video is enabled - constraints ".concat(JSON.stringify(videoConfig, MapOrSet_toJSON)));
                            }
                            _a = videoConfig;
                            if (!_a) return [3 , 2];
                            return [4 , this._manager.device.getMediaDevice(false, false, true)];
                        case 1:
                            _a = !(_b.sent()).videoInputEnabled;
                            _b.label = 2;
                        case 2:
                            if (_a) {
                                videoConfig = false;
                            }
                            return [2 , { audio: audioConfig, video: videoConfig }];
                    }
                });
            });
        };
        Call.prototype.setLocalMedia = function (media, mediaConfiguration) {
            var _a;
            return __awaiter$3(this, void 0, void 0, function () {
                var mediaImpl, mdiff, m, m, audioEnable, desktopEnable, mediaConstraints, audioInput, videoInput;
                return __generator$3(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!this.canDoAction()) return [3 , 7];
                            if (!this._mediaEnabled) {
                                return [2 , this];
                            }
                            mediaImpl = new MediaParamImpl(media);
                            if (!this._localMedia) return [3 , 3];
                            mdiff = 0;
                            for (m in this.localCallMedia) {
                                if (!mediaImpl[m]) {
                                    mdiff++;
                                }
                            }
                            if (mdiff === 0) {
                                for (m in mediaImpl) {
                                    if (!this._localCallMedia[m]) {
                                        mdiff++;
                                    }
                                }
                            }
                            if (!(mdiff > 0)) return [3 , 2];
                            return [4 , this.changeLocalMedia(mediaImpl, mediaConfiguration)];
                        case 1:
                            _b.sent();
                            _b.label = 2;
                        case 2: return [3 , 7];
                        case 3:
                            this._localCallMedia = mediaImpl;
                            if (!this.mediaOwnedByCurrentInstance) return [3 , 7];
                            if (!this._localCallMedia._hasMedia()) {
                                throw new Error("Parameter error, audio or video or desktop must be set");
                            }
                            audioEnable = !!this._localCallMedia.audio;
                            desktopEnable = !!this._localCallMedia.desktop;
                            return [4 , this.mediaConfigurationToLocalMediaConstraints(mediaConfiguration)];
                        case 4:
                            mediaConstraints = _b.sent();
                            this._localMedia = new LocalMedia(mediaConstraints);
                            this._localAudioLevel._activate();
                            audioInput = void 0;
                            if (audioEnable && this._manager.device.audioInput) {
                                audioInput = this._manager.device.audioInput;
                            }
                            videoInput = void 0;
                            if (mediaConstraints.video && !desktopEnable && typeof this._manager.device.videoInput !== "boolean" && this._manager.device.videoInput) {
                                videoInput = this._manager.device.videoInput;
                            }
                            if (!(audioInput || videoInput)) return [3 , 6];
                            return [4 , ((_a = this._localMedia) === null || _a === void 0 ? void 0 : _a.changeAudioVideoInput(audioInput, videoInput))];
                        case 5:
                            _b.sent();
                            _b.label = 6;
                        case 6:
                            if (this._layoutManager) {
                                this._layoutManager.localMedia = this._localMedia;
                            }
                            _b.label = 7;
                        case 7: return [2 , this];
                    }
                });
            });
        };
        Call.prototype.notifyLastControlMessage = function (cleanMedia) {
            var _this = this;
            var _a;
            var 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(function () { return _this._controlMessageNotifier.next(controlMessage); });
        };
        Call.prototype.notifyVideoStartOrStop = function () {
            return __awaiter$3(this, void 0, void 0, function () {
                return __generator$3(this, function (_a) {
                    if (this.canDoAction()) {
                        if (this.channelType === ChannelType.Video) {
                            this.notifyLastControlMessage(true);
                            return [2 , true];
                        }
                        else {
                            if (this._localCallMedia.video) {
                                return [2 , this._manager.methods.startVideoOnCall(this._callId).toPromise()];
                            }
                            else {
                                return [2 , this._manager.methods.stopVideoOnCall(this._callId).toPromise()];
                            }
                        }
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        Call.prototype.notifyCallMediaState = function (media) {
            var _a, _b;
            return __awaiter$3(this, void 0, void 0, function () {
                var mediaImpl, mediaMapMuted_1, m, muted, mediaParam, response;
                var _this = this;
                return __generator$3(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            mediaImpl = new MediaParamImpl(media);
                            if (!(this.canDoAction() && mediaImpl._hasMedia())) return [3 , 5];
                            if (!this._manager.options.notifyMediaFeature) return [3 , 4];
                            if (!(this.channelType === ChannelType.Video)) return [3 , 1];
                            this.notifyLastControlMessage(true);
                            return [2 , true];
                        case 1:
                            mediaMapMuted_1 = new Map();
                            for (m in mediaImpl) {
                                if (m && this._localCallMedia[m]) {
                                    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) {
                                        mediaParam = mediaMapMuted_1.get(muted);
                                        if (!mediaParam) {
                                            mediaParam = {};
                                            mediaMapMuted_1.set(muted, mediaParam);
                                        }
                                        mediaParam[m] = true;
                                    }
                                }
                            }
                            return [4 , Promise.all([
                                    (function () { return __awaiter$3(_this, void 0, void 0, function () {
                                        var media;
                                        return __generator$3(this, function (_a) {
                                            media = mediaMapMuted_1.get(true);
                                            return [2 , media ? this._manager.methods.notifyMute(this._callId, media, undefined).toPromise() : true];
                                        });
                                    }); })(),
                                    (function () { return __awaiter$3(_this, void 0, void 0, function () {
                                        var media;
                                        return __generator$3(this, function (_a) {
                                            media = mediaMapMuted_1.get(false);
                                            return [2 , media ? this._manager.methods.notifyUnmute(this._callId, media, undefined).toPromise() : true];
                                        });
                                    }); })(),
                                ])];
                        case 2:
                            response = _c.sent();
                            return [2 , response[0] && response[1]];
                        case 3: return [3 , 5];
                        case 4: return [2 , true];
                        case 5: return [2 , false];
                    }
                });
            });
        };
        Call.prototype.publishLastCallInfo = function () {
            var callInfo = Object.assign({}, this._lastControlMessage);
            callInfo._isFromServer = false;
            this._controlMessageNotifier.next(callInfo);
        };
        return Call;
    }());
    var MonitorAudioLevel =  (function () {
        function MonitorAudioLevel(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);
        }
        MonitorAudioLevel.prototype.start = function () {
            var _this = this;
            if (!this._audioLevelObservable) {
                this._log.info("start ".concat(this.id));
                this._audioLevelObservable = new Observable(function (publisher) {
                    if (_this._audioLevelObservable) {
                        _this._audioLevelPublisher = publisher;
                        _this._activate();
                    }
                    else {
                        publisher.error(new Error("".concat(_this.id, " monitorAudioLevel is ended")));
                    }
                    return function () { return _this.stop(); };
                }).pipe(share());
            }
            return this._audioLevelObservable;
        };
        MonitorAudioLevel.prototype.stop = function () {
            if (this._audioLevelSubscription !== Subscription.EMPTY)
                this._log.info("stop ".concat(this.id));
            this._audioLevelSubscription.unsubscribe();
            this._audioLevelSubscription = Subscription.EMPTY;
        };
        MonitorAudioLevel.prototype.end = function () {
            if (this._audioLevelObservable)
                this._log.info("end ".concat(this.id));
            this.stop();
            if (this._audioLevelPublisher) {
                this._audioLevelPublisher.complete();
                this._audioLevelPublisher = null;
            }
            this._audioLevelObservable = null;
        };
        MonitorAudioLevel.prototype._activate = function () {
            var _this = this;
            this.stop();
            var media = this.id === "local" ? this.call.localMedia : this.call.remoteMedia;
            if (media && this._audioLevelPublisher) {
                this._log.info("activate ".concat(this.id));
                this._audioLevelSubscription = media.audioLevel.subscribe(function (value) { return _this._audioLevelPublisher.next(value); }, function (err) { return _this._audioLevelPublisher.error(err); });
            }
        };
        return MonitorAudioLevel;
    }());
    var MonitorStats =  (function () {
        function MonitorStats(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);
        }
        Object.defineProperty(MonitorStats.prototype, "active", {
            set: function (active) {
                this._active = active;
                this.activate();
            },
            enumerable: false,
            configurable: true
        });
        MonitorStats.prototype.start = function () {
            var _this = this;
            if (!this._stats) {
                this._log.info("start");
                this._stats = new Observable(function (publisher) {
                    if (_this._stats) {
                        _this._statsPublisher = publisher;
                        _this.activate();
                    }
                    else {
                        publisher.error(new Error("monitorMediaStreamStats is ended"));
                    }
                    return function () { return _this.stop(); };
                }).pipe(share());
            }
            return this._stats;
        };
        MonitorStats.prototype.stop = function () {
            if (this._statsSubscription !== Subscription.EMPTY)
                this._log.info("stop");
            this._statsSubscription.unsubscribe();
            this._statsSubscription = Subscription.EMPTY;
        };
        MonitorStats.prototype.end = function () {
            if (this._stats)
                this._log.info("end");
            this.stop();
            if (this._statsPublisher) {
                this._statsPublisher.complete();
                this._statsPublisher = null;
            }
            this._stats = null;
        };
        MonitorStats.prototype.activate = function () {
            var _this = this;
            this.stop();
            if (this._active && this._statsPublisher && this._statsSubscription === Subscription.EMPTY) {
                this._log.info("activate");
                this._statsSubscription = interval(1000).subscribe(function () { return __awaiter$3(_this, void 0, void 0, function () {
                    var connectionStats, err_5;
                    var _a;
                    return __generator$3(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                _b.trys.push([0, 2, , 3]);
                                return [4 , ((_a = this.call.connection) === null || _a === void 0 ? void 0 : _a.getStats())];
                            case 1:
                                connectionStats = _b.sent();
                                return [3 , 3];
                            case 2:
                                err_5 = _b.sent();
                                this._log.error("Error on retrive connection stats", err_5);
                                return [3 , 3];
                            case 3:
                                if (connectionStats) {
                                    try {
                                        this._statsPublisher.next(connectionStats);
                                    }
                                    catch (e) {
                                        this._log.error("Error on handle connection stats", e);
                                    }
                                }
                                return [2 ];
                        }
                    });
                }); });
            }
        };
        return MonitorStats;
    }());
    var CallChecker =  (function (_super) {
        __extends$2(CallChecker, _super);
        function CallChecker(manager, webrtcControlMessageNotifier, connectionState, callId, channelType, isOffer, state, realState) {
            var _this = _super.call(this, manager, webrtcControlMessageNotifier, connectionState, callId, channelType, isOffer, state, realState) || this;
            _this._toneSignalEnabled = false;
            return _this;
        }
        return CallChecker;
    }(Call$1));
    var CallOmnidesk =  (function (_super) {
        __extends$2(CallOmnidesk, _super);
        function CallOmnidesk(manager, webrtcControlMessageNotifier, callId, state) {
            return _super.call(this, manager, webrtcControlMessageNotifier, null, callId, ChannelType.Omnidesk, false, state, true) || this;
        }
        return CallOmnidesk;
    }(Call$1));

    var __extends$1 = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter$2 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$2 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var WebrtcDialParams =  (function (_super) {
        __extends$1(WebrtcDialParams, _super);
        function WebrtcDialParams(params) {
            return _super.call(this, params) || this;
        }
        WebrtcDialParams.prototype.toRequestParam = function (phoneManagerActive) {
            var result = _super.prototype.toRequestParams.call(this, phoneManagerActive);
            result[8] = this.webrtcFields ? this.webrtcFields.toObject() : null;
            return result;
        };
        return WebrtcDialParams;
    }(DialParams));
    var WebRTCMethods =  (function (_super) {
        __extends$1(WebRTCMethods, _super);
        function WebRTCMethods(
        client) {
            var _this = _super.call(this, client) || this;
            _this.client = client;
            return _this;
        }
        WebRTCMethods.prototype.isWebRTCCall = function (callId) {
            var _a;
            var call = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.retriveCall(callId);
            if (call) {
                return !call.deviceIsApp;
            }
            else {
                return false;
            }
        };
        WebRTCMethods.prototype.setWebRTCAvailableMedia = function (media) {
            return this.requestPromise("setWebRTCAvailableMedia", [MediaParam.toCallMedia(media)]);
        };
        WebRTCMethods.prototype.startVideoEchoTest = function (audio, video, videoContainer, mediaConfiguration) {
            var _this = this;
            var _a;
            if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                var webrtcDialParams_1 = new WebrtcDialParams({
                    fromDeviceType: ExtenType.WEBRTC,
                    media: { audio: audio, video: video },
                    privateCall: false,
                    channelId: ChannelType.Video,
                    serviceCode: "dummy",
                });
                return from(this.client.webrtc.generateWebrtcFieldsForDial(webrtcDialParams_1, mediaConfiguration, videoContainer)).pipe(switchMap(function (webrtcFields) {
                    webrtcDialParams_1.webrtcFields = webrtcFields;
                    return _this.requestPromise("startVideoEchoTest", [webrtcDialParams_1.webrtcFields.clientid, MediaParam.toCallMedia(webrtcDialParams_1.params.media), webrtcDialParams_1.webrtcFields.toObject()]).pipe(catchError(function (err) { return __awaiter$2(_this, void 0, void 0, function () {
                        var webrtcFields;
                        return __generator$2(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    webrtcFields = webrtcDialParams_1.webrtcFields;
                                    if (!(webrtcFields && webrtcFields.clientid)) return [3 , 2];
                                    return [4 , this.client.webrtc.destroyCall(webrtcFields.clientid)];
                                case 1:
                                    _a.sent();
                                    _a.label = 2;
                                case 2: throw err;
                            }
                        });
                    }); }));
                }));
            }
            else {
                return throwError(new Error("Webrtc is not enable, call webrtc.start() before startVideoEchoTest"));
            }
        };
        WebRTCMethods.prototype.echoTestConnectivityCheck = function (media, mediaConfiguration, videoContainer) {
            var _a;
            if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                return this.client.webrtc.generateWebrtcFieldsForConnectivityCheck(ChannelType.PhoneCall, media, mediaConfiguration, videoContainer);
            }
            else {
                return Promise.reject(new Error("Webrtc is not enable, call webrtc.start() before echoTestConnectivityCheck"));
            }
        };
        WebRTCMethods.prototype.stopEchoTestConnectivityCheck = function (id) {
            return this.cancel(id, true, false);
        };
        WebRTCMethods.prototype.dial = function (dialParams, videoContainer, mediaConstraints, userInteractionAction) {
            var _this = this;
            var _a;
            if (ExtenType.WEBRTC === dialParams.params.fromDeviceType && ChannelType.PhoneCall === dialParams.params.channelId ) {
                var callMedia = dialParams.params.media;
                this.log.debug("Webrtc dial is requested - contact: ".concat(dialParams.params.contact.value, " - audio: ").concat(!!callMedia.audio, " - video: ").concat(!!callMedia.video, " - desktop: ").concat(!!callMedia.desktop, " - data: ").concat(!!callMedia.data));
                var webrtcDialParams_2 = new WebrtcDialParams(dialParams.params);
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    return from(this.client.webrtc.generateWebrtcFieldsForDial(webrtcDialParams_2, mediaConstraints, videoContainer, userInteractionAction)).pipe(switchMap(function (webrtcFields) {
                        webrtcDialParams_2.webrtcFields = webrtcFields;
                        return _this.requestPromise("dial", webrtcDialParams_2.toRequestParam(_this.client.phoneManagerActive)).pipe(map(function (result) {
                            return result ? webrtcDialParams_2.webrtcFields.clientid : null;
                        }));
                    }), catchError(function (err) { return __awaiter$2(_this, void 0, void 0, function () {
                        return __generator$2(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (!(webrtcDialParams_2.webrtcFields && webrtcDialParams_2.webrtcFields.clientid)) return [3 , 2];
                                    return [4 , this.client.webrtc.destroyCall(webrtcDialParams_2.webrtcFields.clientid, dialParams, err)];
                                case 1:
                                    _a.sent();
                                    _a.label = 2;
                                case 2: throw err;
                            }
                        });
                    }); }));
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before dial"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.answer = function (channelId, callId, media, videoContainer, mediaConfiguration) {
            var _this = this;
            var _a;
            if (channelId === void 0) { channelId = ChannelType.PhoneCall; }
            if (this.isWebRTCCall(callId)) {
                this.log.debug("Webrtc answer is requested - callId: ".concat(callId, " - audio: ").concat(!!media.audio, " - video: ").concat(!!media.video, " - desktop: ").concat(!!media.desktop, " - data: ").concat(!!media.data));
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    var execAnswer = true;
                    var call = this.client.webrtc.retriveCall(callId);
                    if (call) {
                        execAnswer = call.signalingState === CallState.NEW_INBOUND && call.waitForAnswer;
                    }
                    if (execAnswer) {
                        return from(this.client.webrtc.generateWebrtcFieldsForAnswer(channelId, callId, media, mediaConfiguration, videoContainer)).pipe(switchMap(function (webrtcFields) { return _this.requestPromise("answer", [callId, MediaParam.toCallMedia(media), webrtcFields.toObject()]); }), catchError(function (err) { return __awaiter$2(_this, void 0, void 0, function () {
                            return __generator$2(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 , this.client.webrtc.destroyCall(callId)];
                                    case 1:
                                        _a.sent();
                                        throw err;
                                }
                            });
                        }); }));
                    }
                    else {
                        var msg = "Answer was previous requested, wait or cancel call";
                        this.log.error(msg);
                        return throwError(new Error(msg));
                    }
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before answer"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.hold = function (callId) {
            var _a;
            if (this.isWebRTCCall(callId)) {
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    return from(this.client.webrtc.toggleHold(callId));
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before toggleHold"));
                }
            }
            return of(true);
        };
        WebRTCMethods.prototype.unhold = function (callId) {
            return this.hold(callId);
        };
        WebRTCMethods.prototype.attendedTransfer = function (callId, heldCallId, media, fields) {
            var _this = this;
            var _a;
            if (this.isWebRTCCall(callId)) {
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    var call_1 = this.client.webrtc.retriveCall(callId);
                    if (call_1 && (!media || Object.keys(media).length === 0)) {
                        media = call_1.localCallMedia;
                    }
                    if (call_1 && !fields && call_1.localMedia) {
                        fields = new WebRTCField(null, new WebRTCFieldSession(call_1.isOffer, call_1.localDescription), null, null, null).toObject();
                    }
                    return this.requestPromise("attendedTransfer", [callId, heldCallId, MediaParam.toCallMedia(media), fields]).pipe(tap(function (response) {
                        if (response && (call_1 === null || call_1 === void 0 ? void 0 : call_1.signalingState) === CallState.NEW_OUTBOUND) {
                            _this.log.debug("stopping tone signals for attendedTransfer in ring state");
                            call_1.toneSignalEnabled = false;
                        }
                    }));
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before attendedTransfer"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.blindTransfer = function (callId, accessCode, number, data) {
            return this.requestPromise("blindTransfer", [callId, accessCode, number, data]);
        };
        WebRTCMethods.prototype.sendDTMF = function (callId, dtmf, playTone, dtmfDuration, dtmfInterToneGap) {
            var _this = this;
            var _a;
            if (playTone === void 0) { playTone = true; }
            if (this.isWebRTCCall(callId)) {
                dtmf = (dtmf || "").split("").reduce(function (d1, d2) { return (dtmfValidator.test(d2) ? d1 + d2 : d1); }, "");
                if (dtmf) {
                    var call = (_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.retriveCall(callId);
                    if (call) {
                        return from(call.sendDTMF(dtmf, playTone, dtmfDuration, dtmfInterToneGap)).pipe(switchMap(function (isSentInband) {
                            if (isSentInband) {
                                return of(true);
                            }
                            else {
                                return _this.requestPromise("sendDTMF", [callId, dtmf]);
                            }
                        }));
                    }
                    else {
                        return throwError(new Error("no call to sendDTMF"));
                    }
                }
                else {
                    return throwError(new Error("Invalid DTMF"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.forceCancel = function (callId) {
            return this.requestPromise("cancel", [callId]);
        };
        WebRTCMethods.prototype.cancel = function (callId, storeAction, execWebapiRequest) {
            var _a;
            if (this.isWebRTCCall(callId)) {
                this.log.debug("Webrtc cancel is requested - callId: ".concat(callId));
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    if (storeAction) {
                        this.client.webrtc.cancelCallRequest(callId);
                    }
                    if (execWebapiRequest) {
                        return this.forceCancel(callId);
                    }
                    else {
                        return of(true);
                    }
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before cancel"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.createUserInteraction = function (createUserInteraction) {
            return this.requestPromise("createUserInteraction", [createUserInteraction]);
        };
        WebRTCMethods.prototype.removeCallFromUserInteraction = function (callId) {
            return this.requestPromise("removeCallFromUserInteraction", [callId]);
        };
        WebRTCMethods.prototype.updateWebRTCFields = function (callId, media, fields) {
            return this.requestPromise("updateWebRTCFields", [callId, MediaParam.toCallMedia(media), fields ? fields.toObject() : null]);
        };
        WebRTCMethods.prototype.getWebrtcConfiguration = function () {
            return this.requestPromise("getWebrtcConfiguration", []);
        };
        WebRTCMethods.prototype.mute = function (callId, media) {
            var _a;
            if (this.isWebRTCCall(callId)) {
                this.log.debug("Webrtc MUTE is requested - callId: ".concat(callId, " - ") + "audio: ".concat(!!(media && media.audio), " - ") + "video: ".concat(!!(media && media.video), " - ") + "desktop: ".concat(!!(media && media.desktop), " - ") + "data: ".concat(!!media && media.data));
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    if (media && Object.keys(media).length) {
                        var call_2 = this.client.webrtc.retriveCall(callId);
                        if (call_2) {
                            var result = of(false);
                            if (media.audio) {
                                result = result.pipe(switchMap(function () { return call_2.toggleAudioMute(true, false); }));
                            }
                            if (media.video) {
                                result = result.pipe(switchMap(function () { return call_2.toggleVideoMute(true, false); }));
                            }
                            return result.pipe(switchMap(function () { return call_2.notifyCallMediaState(media); }));
                        }
                        else {
                            var msg = "Webrtc MUTE - call is unavailable";
                            this.log.error(msg);
                            return throwError(new Error(msg));
                        }
                    }
                    else {
                        return throwError(new Error("Webrtc MUTE is called with any media to mute"));
                    }
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before mute"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.unmute = function (callId, media) {
            var _a;
            if (this.isWebRTCCall(callId)) {
                this.log.debug("Webrtc UNMUTE is requested - callId: ".concat(callId, " - ") + "audio: ".concat(!!(media && media.audio), " - ") + "video: ".concat(!!(media && media.video), " - ") + "desktop: ".concat(!!(media && media.desktop), " - ") + "data: ".concat(!!media && media.data));
                if ((_a = this.client.webrtc) === null || _a === void 0 ? void 0 : _a.enable) {
                    if (media && Object.keys(media).length) {
                        var call_3 = this.client.webrtc.retriveCall(callId);
                        if (call_3) {
                            var result = of(false);
                            if (media.audio) {
                                result = result.pipe(switchMap(function () { return call_3.toggleAudioMute(false, false); }));
                            }
                            if (media.video) {
                                result = result.pipe(switchMap(function () { return call_3.toggleVideoMute(false, false); }));
                            }
                            return result.pipe(switchMap(function () { return call_3.notifyCallMediaState(media); }));
                        }
                        else {
                            var msg = "Webrtc UNMUTE - call is unavailable";
                            this.log.error(msg);
                            return throwError(new Error(msg));
                        }
                    }
                    else {
                        return throwError(new Error("Webrtc UNMUTE is called with any media to unmute"));
                    }
                }
                else {
                    return throwError(new Error("Webrtc is not enable, call webrtc.start() before unmute"));
                }
            }
            else {
                return null;
            }
        };
        WebRTCMethods.prototype.notifyMute = function (callId, media, fields) {
            return this.requestPromise("mute", [callId, MediaParam.toCallMedia(media), fields ? fields.toObject() : null]);
        };
        WebRTCMethods.prototype.notifyUnmute = function (callId, media, fields) {
            return this.requestPromise("unmute", [callId, MediaParam.toCallMedia(media), fields ? fields.toObject() : null]);
        };
        WebRTCMethods.prototype.startVideoOnCall = function (callId, fields) {
            return this.requestPromise("startVideoOnCall", [callId, fields ? fields.toObject() : null]);
        };
        WebRTCMethods.prototype.stopVideoOnCall = function (callId, fields) {
            return this.requestPromise("stopVideoOnCall", [callId, fields ? fields.toObject() : null]);
        };
        return WebRTCMethods;
    }(Methods));

    var __awaiter$1 = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator$1 = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    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 MediaDeviceNotification =  (function () {
        function MediaDeviceNotification(devices, status) {
            this.devices = devices;
            this.status = status;
        }
        return MediaDeviceNotification;
    }());
    var MediaDeviceStatus =  (function () {
        function MediaDeviceStatus(lastMediaDevice, currentMediaDevice) {
            var _this = this;
            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(function (_a) {
                var prev = _a[0], curr = _a[1];
                var previousDevices = __spreadArray([], prev, true);
                curr.forEach(function (newDevice) {
                    var previousDeviceIndex = previousDevices.findIndex(function (previousDevice) { return previousDevice.deviceId === newDevice.deviceId; });
                    if (previousDeviceIndex > -1) {
                        previousDevices.splice(previousDeviceIndex, 1);
                        _this.none._addDevice(newDevice);
                    }
                    else {
                        _this.added._addDevice(newDevice);
                    }
                });
                previousDevices.forEach(function (previousDevice) {
                    _this.deleted._addDevice(previousDevice);
                });
            });
        }
        return MediaDeviceStatus;
    }());
    var DEVICE_CHANGE = DeviceManager.deviceChange.pipe(filter(function (mediaDevice) { return !!mediaDevice; }), pairwise(), skip(1), map(function (_a) {
        var lastMediaDevice = _a[0], currentMediaDevice = _a[1];
        return new MediaDeviceNotification(currentMediaDevice, new MediaDeviceStatus(lastMediaDevice, currentMediaDevice));
    }));
    var MEDIA_AVAILABLE = DeviceManager.mediaAvailable;
    var MediaDeviceTest =  (function () {
        function MediaDeviceTest(localMedia, videoContainer) {
            this.localMedia = localMedia;
            this.localMedia.sink.audioSink.muted = false;
            this.layoutManager = new LayoutManager(videoContainer);
            this.layoutManager.localMedia = localMedia;
        }
        Object.defineProperty(MediaDeviceTest.prototype, "audioLevel", {
            get: function () {
                return this.localMedia.audioLevel;
            },
            enumerable: false,
            configurable: true
        });
        MediaDeviceTest.prototype.start = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!!this.localMedia.started) return [3 , 2];
                            return [4 , this.localMedia.start()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 ];
                    }
                });
            });
        };
        MediaDeviceTest.prototype.stop = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.localMedia.started) return [3 , 2];
                            return [4 , this.localMedia.stop()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 ];
                    }
                });
            });
        };
        MediaDeviceTest.prototype.changeAudioVideoInput = function (audioInput, videoInput) {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    return [2 , this.localMedia.changeAudioVideoInput(audioInput, videoInput)];
                });
            });
        };
        MediaDeviceTest.prototype.changeAudioOutput = function (audioOutput) {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    this.localMedia.changeAudioOutput(audioOutput);
                    return [2 ];
                });
            });
        };
        return MediaDeviceTest;
    }());
    var WebrtDeviceManager =  (function () {
        function WebrtDeviceManager(
        manager) {
            var _this = this;
            this.manager = manager;
            this._execNotifyAvailableMedia = new Subject();
            this._mediaNotified = new MediaParamImpl();
            this._loaded = false;
            this._log = Log$1.of("webrtc:device", manager.client);
            this._deviceSelected = {};
            this.status
                .pipe(tap(function (deviceNotification) { return _this._log.info("Media device change", deviceNotification); }), map(function (deviceNotification) { return deviceNotification.devices; }), filter(function (mediaDevice) { return mediaDevice.retrivedWithUserAuthorization; }), concatMap(function (mediaDevice) { return _this.checkSelectedMediaDevice(mediaDevice); }), catchError(function (err, obs) {
                _this._log.error(err);
                return obs;
            }))
                .subscribe();
            combineLatest([this.manager.client.loginProfileLoggedOnNewSession, MEDIA_AVAILABLE, this._execNotifyAvailableMedia.pipe(throttleTime(200, asyncScheduler, { leading: false, trailing: true }))])
                .pipe(filter(function (_a) {
                var loginProfile = _a[0], mediaInputAvailable = _a[1];
                return _this.manager.enable && loginProfile && !!mediaInputAvailable;
            }), map(function (_a) {
                _a[0]; var mediaInputAvailable = _a[1];
                return new MediaParamImpl({ audio: mediaInputAvailable.audio, video: mediaInputAvailable.video && (typeof _this.videoInput === "boolean" ? _this.videoInput : true), desktop: true, data: false });
            }), filter(function (mediaNotified) { return _this._mediaNotified.audio !== mediaNotified.audio || _this._mediaNotified.video !== mediaNotified.video || _this._mediaNotified.desktop !== mediaNotified.desktop || _this._mediaNotified.data !== mediaNotified.data; }), concatMap(function (mediaNotified) {
                _this._mediaNotified = mediaNotified;
                if (_this.manager.options.notifyAvailableMedia) {
                    _this._log.debug("Notify available media");
                    return _this.manager.methods.setWebRTCAvailableMedia(_this._mediaNotified).pipe(tap(function (response) {
                        if (response) {
                            _this._log.debug("Available media notified");
                        }
                        else {
                            _this._log.error("Available media notified but have unexpected response");
                        }
                    }), catchError(function (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();
        }
        Object.defineProperty(WebrtDeviceManager.prototype, "audioInput", {
            get: function () {
                var _a;
                return (_a = this._deviceSelected.audioInput) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebrtDeviceManager.prototype, "videoInput", {
            get: function () {
                var _a;
                return (_a = this._deviceSelected.videoInput) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebrtDeviceManager.prototype, "audioOutput", {
            get: function () {
                var _a;
                return (_a = this._deviceSelected.audioOutput) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebrtDeviceManager.prototype, "audioSignalOutput", {
            get: function () {
                var _a;
                return (_a = this._deviceSelected.audioSignalOutput) !== null && _a !== void 0 ? _a : null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebrtDeviceManager.prototype, "status", {
            get: function () {
                return DEVICE_CHANGE;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebrtDeviceManager.prototype, "callMediaNotified", {
            get: function () {
                return this._mediaNotified;
            },
            enumerable: false,
            configurable: true
        });
        WebrtDeviceManager.prototype.init = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var e_1;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(!this._loaded && this.manager.enable)) return [3 , 6];
                            this._loaded = true;
                            return [4 , this.setMediaDevice(this.manager.options.audioDeviceInput || this._deviceSelected.audioInput || null,
                                this.manager.options.videoDeviceInput || this._deviceSelected.videoInput || null,
                                this.manager.options.audioDeviceOutput || this._deviceSelected.audioOutput || null,
                                this.manager.options.audioDeviceSignalOutput || this._deviceSelected.audioSignalOutput || null)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 4, , 5]);
                            return [4 , DeviceManager.getMediaDevice(false, true, true)];
                        case 3:
                            _a.sent();
                            return [3 , 5];
                        case 4:
                            e_1 = _a.sent();
                            this._log.error("Error on retrive media devices", e_1);
                            return [3 , 5];
                        case 5:
                            if (!Object.keys(this._mediaNotified).length) {
                                this.notifyAvailableMedia();
                            }
                            _a.label = 6;
                        case 6: return [2 ];
                    }
                });
            });
        };
        WebrtDeviceManager.prototype.notifyAvailableMedia = function () {
            this._execNotifyAvailableMedia.next();
            return true;
        };
        WebrtDeviceManager.prototype.setMediaDevice = function (audio_input, video_input, audio_output, audio_signal_output) {
            return __awaiter$1(this, void 0, void 0, function () {
                var deviceSelectedAudioInput, deviceSelectedVideoInput, deviceSelectedAudioOutput, deviceSelectedAudioSignalOutput, _a, err_1;
                return __generator$1(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            deviceSelectedAudioInput = audio_input ? audio_input : null;
                            deviceSelectedVideoInput = typeof video_input === "boolean" ? video_input : video_input === null || !!video_input ? video_input : false;
                            deviceSelectedAudioOutput = audio_output ? audio_output : null;
                            deviceSelectedAudioSignalOutput = audio_signal_output ? audio_signal_output : null;
                            if (!(this._deviceSelected.audioInput !== deviceSelectedAudioInput || this._deviceSelected.videoInput !== deviceSelectedVideoInput || this._deviceSelected.audioOutput !== deviceSelectedAudioOutput || this._deviceSelected.audioSignalOutput !== deviceSelectedAudioSignalOutput)) return [3 , 5];
                            this._deviceSelected.audioInput = deviceSelectedAudioInput;
                            this._deviceSelected.videoInput = deviceSelectedVideoInput;
                            this._deviceSelected.audioOutput = deviceSelectedAudioOutput;
                            this._deviceSelected.audioSignalOutput = deviceSelectedAudioSignalOutput;
                            if (!(this._deviceSelected.audioInput || this._deviceSelected.videoInput || this._deviceSelected.audioOutput || this._deviceSelected.audioSignalOutput)) return [3 , 5];
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 4, , 5]);
                            _a = this.checkSelectedMediaDevice;
                            return [4 , DeviceManager.getMediaDevice(false, true, true)];
                        case 2: return [4 , _a.apply(this, [_b.sent()])];
                        case 3:
                            _b.sent();
                            return [3 , 5];
                        case 4:
                            err_1 = _b.sent();
                            this._log.error(err_1);
                            return [3 , 5];
                        case 5:
                            this.notifyAvailableMedia();
                            this.manager.deviceChanged();
                            return [2 ];
                    }
                });
            });
        };
        WebrtDeviceManager.prototype.getMediaDevice = function (startMedia, acquireAudio, acquireVideo) {
            if (acquireAudio === void 0) { acquireAudio = true; }
            if (acquireVideo === void 0) { acquireVideo = true; }
            return DeviceManager.getMediaDevice(startMedia, acquireAudio, acquireVideo);
        };
        WebrtDeviceManager.prototype.checkDevicePermission = function (permission) {
            return __awaiter$1(this, void 0, void 0, function () {
                var localStream;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            localStream = new LocalMedia({ audio: !!permission.audio, video: !!permission.video });
                            return [4 , localStream.start()];
                        case 1:
                            _a.sent();
                            return [4 , localStream.stop()];
                        case 2:
                            _a.sent();
                            return [2 , { audio: !!permission.audio, video: !!permission.video }];
                    }
                });
            });
        };
        WebrtDeviceManager.prototype.testMediaDevice = function (audioInput, videoInput, audioOutput, videoContainer) {
            var _a, _b;
            return __awaiter$1(this, void 0, void 0, function () {
                var localMedia, e_4;
                return __generator$1(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            _c.trys.push([0, 10, , 11]);
                            return [4 , ((_a = this.mediaDeviceTest) === null || _a === void 0 ? void 0 : _a.stop())];
                        case 1:
                            _c.sent();
                            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);
                            _c.label = 2;
                        case 2:
                            _c.trys.push([2, 4, , 5]);
                            return [4 , this.mediaDeviceTest.start()];
                        case 3:
                            _c.sent();
                            return [3 , 5];
                        case 4:
                            _c.sent();
                            this._log.warn("Error on start localMedia for testMediaDevice", { audioInput: audioInput, videoInput: videoInput });
                            return [3 , 5];
                        case 5:
                            if (!audioOutput) return [3 , 9];
                            _c.label = 6;
                        case 6:
                            _c.trys.push([6, 8, , 9]);
                            return [4 , localMedia.changeAudioOutput(audioOutput)];
                        case 7:
                            _c.sent();
                            return [3 , 9];
                        case 8:
                            _c.sent();
                            this._log.warn("Error on changeAudioOutput for testMediaDevice", { audioOutput: audioOutput });
                            return [3 , 9];
                        case 9: return [2 , this.mediaDeviceTest];
                        case 10:
                            e_4 = _c.sent();
                            (_b = this.mediaDeviceTest) === null || _b === void 0 ? void 0 : _b.stop();
                            throw e_4;
                        case 11: return [2 ];
                    }
                });
            });
        };
        WebrtDeviceManager.prototype.checkSelectedMediaDevice = function (currentMediaDevice) {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    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;
                    }
                    return [2 , currentMediaDevice];
                });
            });
        };
        return WebrtDeviceManager;
    }());

    var __extends = (undefined && undefined.__extends) || (function () {
        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);
        };
        return function (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 __awaiter = (undefined && undefined.__awaiter) || function (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());
        });
    };
    var __generator = (undefined && undefined.__generator) || function (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 (_) 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 };
        }
    };
    var WebRTCManager =  (function () {
        function WebRTCManager(options) {
            if (options === void 0) { options = new WebrtcConfig(); }
            this._callIdToRemove = new Set();
            this._controlMessageNotifierSubscription = Subscription.EMPTY;
            this._connectionStateSubscription = Subscription.EMPTY;
            this._loadedOptions = new WebrtcConfig(options);
            this.applyOptions();
        }
        Object.defineProperty(WebRTCManager.prototype, "client", {
            get: function () {
                return this._client;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "log", {
            get: function () {
                return this._log;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "enable", {
            get: function () {
                return !!this._enabled;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "options", {
            get: function () {
                return this._loadedOptions;
            },
            set: function (options) {
                this._loadedOptions = new WebrtcConfig(options);
                this.applyOptions();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "methods", {
            get: function () {
                return this._apiMethods;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "callConnectionState", {
            get: function () {
                return this._callConnectionStateSubject.asObservable();
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "trickleIcePolicy", {
            get: function () {
                return this.options.trickleIcePolicy || Connection.TrickleIcePolicy.NotSupported;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "phoneSignal", {
            get: function () {
                return this._phoneSignalManager;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(WebRTCManager.prototype, "device", {
            get: function () {
                return this._deviceManager;
            },
            enumerable: false,
            configurable: true
        });
        WebRTCManager.prototype.attachToClient = function (client) {
            var 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._apiMethods = new WebRTCMethods(client);
                if (!client.webrtc || (prevClient && prevClient.instanceId != client.instanceId)) {
                    client.webrtc = this;
                }
            }
        };
        WebRTCManager.prototype.initFromClient = function (controlMessageNotifier) {
            if (controlMessageNotifier) {
                this._controlMessageNotifier = controlMessageNotifier;
                this.init();
            }
        };
        WebRTCManager.prototype.init = function () {
            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();
            }
        };
        WebRTCManager.prototype.applyOptions = function () {
            var options = this._loadedOptions;
            if (options.iceServers) {
                this._iceServers = options.iceServers.map(function (iceServer) {
                    return iceServer.username
                        ? {
                            urls: iceServer.url,
                            username: iceServer.username,
                            credential: iceServer.password,
                            credentialType: "password",
                        }
                        : { urls: iceServer.url };
                });
            }
            else {
                this._iceServers = null;
            }
        };
        WebRTCManager.prototype.deviceChanged = function () {
            var _this = this;
            this._connections.forEach(function (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);
            });
        };
        WebRTCManager.prototype.getIceServers = function () {
            return __awaiter(this, void 0, void 0, function () {
                var response, e_1;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(!this._iceServers || this._iceServers.length === 0)) return [3 , 4];
                            this._iceServers = [];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 , this._apiMethods.getWebrtcConfiguration().toPromise()];
                        case 2:
                            response = _a.sent();
                            if (response) {
                                if (response.iceServers && response.iceServers.length) {
                                    response.iceServers.forEach(function (s) {
                                        if (s && s.url) {
                                            try {
                                                var iceServer = { urls: s.url };
                                                if (s.hasOwnProperty("username")) {
                                                    iceServer.username = s.username;
                                                    iceServer.credential = s.password || "";
                                                    iceServer.credentialType = "password";
                                                }
                                                _this._iceServers.push(iceServer);
                                            }
                                            catch (e) {
                                                _this._log.error("Error on create IceServer", e);
                                            }
                                        }
                                    });
                                }
                            }
                            return [3 , 4];
                        case 3:
                            e_1 = _a.sent();
                            this._log.error("Error on getWebrtcConfiguration", e_1);
                            return [3 , 4];
                        case 4: return [2 , this._iceServers];
                    }
                });
            });
        };
        WebRTCManager.prototype.setEnabledOnChannel = function (channels) {
            if (channels) {
                this._loadedOptions.enabledOnChannel.length = 0;
                this._loadedOptions.enabledOnChannel.push.apply(this._loadedOptions.enabledOnChannel, channels);
                this._log.debug("Enabled on channels ".concat(this._loadedOptions.enabledOnChannel.join(",")));
            }
        };
        WebRTCManager.prototype.start = function () {
            return __awaiter(this, void 0, void 0, function () {
                var uniqueId;
                var _this = this;
                return __generator(this, function (_a) {
                    if (!this._enabled && this._client) {
                        registerProvider(this._tLinkLogger);
                        this._enabled = true;
                        uniqueId = 0;
                        this._log.debug("Enabled on channels ".concat(this._loadedOptions.enabledOnChannel.join(",")));
                        this._controlMessageNotifierSubscription.unsubscribe();
                        this._controlMessageNotifierSubscription = this._controlMessageNotifier
                            .pipe(tap(function (data) {
                            data.internalId = ++uniqueId;
                            _this._log.debug("ControlMessageManager - Receiving message ".concat(data.internalId), data);
                        }), concatMap(function (data) {
                            _this._log.debug("ControlMessageManager - Start manage message ".concat(data.internalId, " - ").concat(data.state, " - ").concat(data.callId));
                            return _this.controlMessageHandler(data).catch(function (err) {
                                _this._log.error("ControlMessageManager - Error on manage message ".concat(err.controlMessage.internalId), err);
                                return err.controlMessage;
                            });
                        }))
                            .subscribe(function (data) {
                            _this._log.debug("ControlMessageManager - End manage message ".concat(data.internalId, " - ").concat(data.state, " - ").concat(data.callId));
                        });
                        this._client.loginProfileLoggedOnNewSession.subscribe(function () { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                try {
                                    this.getIceServers();
                                }
                                catch (e) { }
                                return [2 ];
                            });
                        }); });
                        this._connectionStateSubscription.unsubscribe();
                        this._connectionStateSubscription = this._client.connectionEvent.subscribe(function (event) {
                            if (event.connected) {
                                _this.cleanPendingCall();
                            }
                        });
                        return [2 , this.device.init()];
                    }
                    return [2 ];
                });
            });
        };
        WebRTCManager.prototype.stop = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    if (this._enabled) {
                        this._controlMessageNotifierSubscription.unsubscribe();
                        this._connectionStateSubscription.unsubscribe();
                        this._enabled = false;
                        this._connections.forEach(function (call) {
                            _this.methods.cancel(call.callId, true, true);
                        });
                    }
                    return [2 ];
                });
            });
        };
        WebRTCManager.prototype.checkUniqueCallBeforeDial = function (dialParam) {
            this._connections.forEach(function (call) {
                if (call.isOffer) {
                    var callDialParams = call.dialParams;
                    if (callDialParams && callDialParams.equals(dialParam)) {
                        throw CallInProgress.newInstance(call.callId);
                    }
                }
            });
        };
        WebRTCManager.prototype.generateWebrtcFieldsForDial = function (dialParam, mediaConfiguration, videoContainer, userInteractionAction) {
            return __awaiter(this, void 0, void 0, function () {
                var callId, call, fromDevice, contact, media, createUserInteraction, e_2;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.checkUniqueCallBeforeDial(dialParam);
                            callId = uuidv4();
                            call = this.createCall(callId, ChannelType.PhoneCall, true, CallState.NEW_OUTBOUND, false, true, dialParam);
                            fromDevice = dialParam.params.fromDevice;
                            contact = dialParam.params.contact;
                            media = dialParam.params.media;
                            createUserInteraction = !(dialParam.params.serviceCode || dialParam.params.abandonedCallId || dialParam.params.callbackRequestId);
                            if (createUserInteraction) {
                                this._apiMethods
                                    .createUserInteraction({
                                    action: userInteractionAction,
                                    contact: contact,
                                    callId: callId,
                                    type: UserInteractionType.call,
                                })
                                    .subscribe(function (userInteractionId) {
                                    if (!call || (call.isOffer && !call.signalingState)) {
                                        _this._log.debug("createUserInteraction response before dial for call ".concat(callId, ", emit dummy NEW_OUTBOUND event"));
                                        _this._controlMessageNotifier.next({
                                            callId: callId,
                                            device: fromDevice,
                                            direction: CallDirection.outbound,
                                            state: CallState.NEW_OUTBOUND,
                                            features: [CallFeature.CANCEL],
                                            _isFromServer: false,
                                            _channelType: dialParam.params.channelId,
                                            _realChannelType: dialParam.params.channelId,
                                        });
                                    }
                                }, function (error) {
                                    _this._log.error("createUserInteraction error", error);
                                });
                            }
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 5, , 6]);
                            if (!call.deviceIsApp) return [3 , 2];
                            return [2 , this.generateWebrtcFieldsForApp(callId, false, media, mediaConfiguration, videoContainer)];
                        case 2: return [4 , this.generateWebrtcFields(call, false, media, mediaConfiguration, videoContainer)];
                        case 3: return [2 , _a.sent()];
                        case 4: return [3 , 6];
                        case 5:
                            e_2 = _a.sent();
                            if (createUserInteraction && call && call.signalingState && call.signalingState === CallState.NEW_OUTBOUND && !call.realState) {
                                this._controlMessageNotifier.next({
                                    callId: callId,
                                    device: fromDevice,
                                    direction: CallDirection.outbound,
                                    state: CallState.IDLE,
                                    _isFromServer: false,
                                    _channelType: dialParam.params.channelId,
                                    _realChannelType: dialParam.params.channelId,
                                });
                            }
                            throw e_2;
                        case 6: return [2 ];
                    }
                });
            });
        };
        WebRTCManager.prototype.generateWebrtcFieldsForCallChannel = function (call, answer, media, mediaConfiguration) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 , this.generateWebrtcFields(call, answer, media, mediaConfiguration)];
                });
            });
        };
        WebRTCManager.prototype.generateWebrtcFieldsForAnswer = function (channelId, callId, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function () {
                var answer, offer, call, result;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            answer = true;
                            offer = false;
                            if (channelId && channelId === ChannelType.Video) {
                                answer = false;
                                offer = true;
                            }
                            call = this.createCall(callId, channelId, offer, CallState.NEW_INBOUND, false, true);
                            return [4 , this.phoneSignal.stop(call.callId, false)];
                        case 1:
                            _a.sent();
                            return [4 , this.generateWebrtcFields(call, answer, media, mediaConfiguration, videoContainer)];
                        case 2:
                            result = _a.sent();
                            call.waitForAnswer = false;
                            return [2 , result];
                    }
                });
            });
        };
        WebRTCManager.prototype.generateWebrtcFieldsForConnectivityCheck = function (channelType, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.createCall(uuidv4(), channelType, true, CallState.CONNECTED, true, true);
                    return [2 , this.generateWebrtcFields(call, false, media, mediaConfiguration, videoContainer)];
                });
            });
        };
        WebRTCManager.prototype.generateWebrtcFieldsForApp = function (callId, answer, media, mediaConfiguration, videoContainer) {
            return new WebRTCField(answer ? null : callId, new WebRTCFieldSession(answer, null), null, null, null);
        };
        WebRTCManager.prototype.generateWebrtcFields = function (call, answer, media, mediaConfiguration, videoContainer) {
            return __awaiter(this, void 0, void 0, function () {
                var mediaParam;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            call.mediaEnabled = true;
                            if (videoContainer) {
                                call.videoContainer = videoContainer;
                            }
                            mediaParam = MediaParam.of(media);
                            if (!mediaParam._hasMedia()) return [3 , 3];
                            if (!!answer) return [3 , 2];
                            return [4 , this.phoneSignal.play(call.callId, MediaSignal.dialtone)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 , call.connectionActionQueue(function () { return __awaiter(_this, void 0, void 0, function () {
                                var err_1, err_2, webrtcField;
                                var _a;
                                return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0:
                                            _b.trys.push([0, 2, , 3]);
                                            return [4 , call.setLocalMedia(mediaParam, mediaConfiguration)];
                                        case 1:
                                            _b.sent();
                                            return [3 , 3];
                                        case 2:
                                            err_1 = _b.sent();
                                            this._log.error("error on generateWebrtcFields.setLocalMedia", err_1);
                                            throw err_1;
                                        case 3:
                                            _b.trys.push([3, 5, , 6]);
                                            return [4 , ((_a = call.localMedia) === null || _a === void 0 ? void 0 : _a.start())];
                                        case 4:
                                            _b.sent();
                                            return [3 , 6];
                                        case 5:
                                            err_2 = _b.sent();
                                            this._log.error("error on generateWebrtcFields.startLocalMedia", err_2);
                                            throw err_2;
                                        case 6: return [4 , call.initTlinkConnection()];
                                        case 7:
                                            _b.sent();
                                            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 [2 , webrtcField];
                                    }
                                });
                            }); })];
                        case 3: return [2 , new WebRTCField(answer ? null : call.callId, new WebRTCFieldSession(answer, null), null, null, null)];
                    }
                });
            });
        };
        WebRTCManager.prototype.toggleHold = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call, callIsHold;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    if (call) {
                        callIsHold = call.signalingState == CallState.HOLD;
                        call.setSignalingState(callIsHold ? CallState.CONNECTED : CallState.HOLD, null);
                        return [2 , call.toggleRemoteAudioMute(!callIsHold)];
                    }
                    else {
                        return [2 , false];
                    }
                });
            });
        };
        WebRTCManager.prototype.setLocalMedia = function (callId, media, mediaConfiguration) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            call = this.retriveCall(callId);
                            if (!call) return [3 , 2];
                            return [4 , call.setLocalMedia(new MediaParamImpl(media), mediaConfiguration)];
                        case 1:
                            _a.sent();
                            return [2 , this];
                        case 2: throw new Error("idCall is invalid");
                    }
                });
            });
        };
        WebRTCManager.prototype.toggleAudioMute = function (callId, mute) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.toggleAudioMute(mute, true) : false];
                });
            });
        };
        WebRTCManager.prototype.toggleVideoMute = function (callId, mute) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.toggleVideoMute(mute, true) : false];
                });
            });
        };
        WebRTCManager.prototype.toggleRemoteAudioMute = function (callId, mute) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.toggleRemoteAudioMute(mute) : false];
                });
            });
        };
        WebRTCManager.prototype.toggleRemoteVideoMute = function (callId, mute) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.toggleRemoteVideoMute(mute) : false];
                });
            });
        };
        WebRTCManager.prototype.isVideoEnabled = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.isVideoEnabled() : false];
                });
            });
        };
        WebRTCManager.prototype.startAudio = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.startAudio() : false];
                });
            });
        };
        WebRTCManager.prototype.stopAudio = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.stopAudio() : false];
                });
            });
        };
        WebRTCManager.prototype.startVideo = function (callId, constraints, videoContainer) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.startVideo(constraints, videoContainer) : false];
                });
            });
        };
        WebRTCManager.prototype.stopVideo = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    return [2 , call ? call.stopVideo() : false];
                });
            });
        };
        WebRTCManager.prototype.getLocalVideoFrame = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    if (call) {
                        return [2 , call.getLocalVideoFrame()];
                    }
                    else {
                        throw new Error("Call ".concat(callId, " is not defined"));
                    }
                });
            });
        };
        WebRTCManager.prototype.getRemoteVideoFrame = function (callId) {
            return __awaiter(this, void 0, void 0, function () {
                var call;
                return __generator(this, function (_a) {
                    call = this.retriveCall(callId);
                    if (call) {
                        return [2 , call.getRemoteVideoFrame()];
                    }
                    else {
                        throw new Error("Call ".concat(callId, " is not defined"));
                    }
                });
            });
        };
        WebRTCManager.prototype.setVideoContainer = function (callId, videoContainer) {
            var call = this.retriveCall(callId);
            if (call) {
                call.videoContainer = videoContainer;
            }
        };
        WebRTCManager.prototype.getRemoteAudioLevel = function (callId) {
            var call = this.retriveCall(callId);
            return call ? call.getRemoteAudioLevel() : EMPTY;
        };
        WebRTCManager.prototype.getLocalAudioLevel = function (callId) {
            var call = this.retriveCall(callId);
            return call ? call.getLocalAudioLevel() : EMPTY;
        };
        WebRTCManager.prototype.getConnectionStats = function (callId) {
            var call = this.retriveCall(callId);
            return call ? call.getConnectionStats() : EMPTY;
        };
        WebRTCManager.prototype.omnideskControlMessageHandler = function (_webrtcControlMessage) {
            return __awaiter(this, void 0, void 0, function () {
                var callInfo, call, deviceIsApp, realEvent, _a, currentPlay;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            callInfo = _webrtcControlMessage;
                            call = this.retriveCall(callInfo.callId);
                            deviceIsApp = (call && call.deviceIsApp) || (callInfo.device && callInfo.device.startsWith("_app_"));
                            realEvent = callInfo._isFromServer;
                            _a = callInfo.state;
                            switch (_a) {
                                case CallState.NEW_INBOUND: return [3 , 1];
                                case CallState.IDLE: return [3 , 4];
                                case CallState.CONNECTED: return [3 , 14];
                            }
                            return [3 , 15];
                        case 1:
                            if (!call && !deviceIsApp) {
                                call = this.createCall(callInfo.callId, callInfo._channelType, false, callInfo.state, realEvent, false);
                            }
                            if (!call) return [3 , 3];
                            return [4 , this.phoneSignal.play(call.callId, this._connections.size > 1 ? MediaSignal.ringAdvertising : MediaSignal.ring)];
                        case 2:
                            _b.sent();
                            _b.label = 3;
                        case 3: return [3 , 15];
                        case 4:
                            if (!call) return [3 , 11];
                            if (realEvent) {
                                this._callIdToRemove.delete(call.callId);
                            }
                            else {
                                call.markAsClosedLocal();
                            }
                            currentPlay = this.phoneSignal.getCurrentPlay(call.callId);
                            if (!(call.signalingState === CallState.NEW_INBOUND)) return [3 , 5];
                            this.phoneSignal.stop(call.callId, true);
                            return [3 , 10];
                        case 5:
                            if (!currentPlay) return [3 , 8];
                            if (!(currentPlay !== MediaSignal.hold)) return [3 , 7];
                            if (!!call.isClosedLocal()) return [3 , 7];
                            this.phoneSignal.stop(call.callId, true);
                            return [4 , this.phoneSignal.play(call.callId, currentPlay === MediaSignal.ringback ? MediaSignal.congestion : MediaSignal.busy)];
                        case 6:
                            _b.sent();
                            _b.label = 7;
                        case 7: return [3 , 10];
                        case 8:
                            if (!(!call.isClosedLocal() && callInfo.idleReason && callInfo.idleReason !== IdleReason.HANGUP)) return [3 , 10];
                            return [4 , this.phoneSignal.play(call.callId, callInfo.idleReason === IdleReason.CONGESTION ? MediaSignal.congestion : MediaSignal.busy)];
                        case 9:
                            _b.sent();
                            _b.label = 10;
                        case 10: return [3 , 12];
                        case 11:
                            if (realEvent) {
                                this._callIdToRemove.delete(callInfo.callId);
                            }
                            _b.label = 12;
                        case 12: return [4 , this.destroyCall(callInfo.callId)];
                        case 13:
                            if (_b.sent()) {
                                call = null;
                            }
                            return [3 , 15];
                        case 14:
                            if (call) {
                                call.waitForAnswer = false;
                                this.phoneSignal.stop(call.callId, true);
                            }
                            return [3 , 15];
                        case 15:
                            if (call) {
                                call.setSignalingState(callInfo.state, realEvent, true);
                            }
                            else {
                                if (callInfo.state !== CallState.IDLE) {
                                    throw new Error("No call");
                                }
                            }
                            return [2 , _webrtcControlMessage];
                    }
                });
            });
        };
        WebRTCManager.prototype.controlMessageHandler = function (_webrtcControlMessage) {
            return __awaiter(this, void 0, void 0, function () {
                var callInfo_1, call_1, deviceIsApp_1, webrtcfields_1, localMediaFeature_1, realEvent_1, media, applyAction, err_3;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 7, , 8]);
                            if (!_webrtcControlMessage) {
                                throw new Error("controlMessageHandler - message is invalid");
                            }
                            if (!(_webrtcControlMessage._channelType === ChannelType.Omnidesk)) return [3 , 2];
                            return [4 , this.omnideskControlMessageHandler(_webrtcControlMessage)];
                        case 1: return [2 , _a.sent()];
                        case 2:
                            callInfo_1 = _webrtcControlMessage;
                            if (this._loadedOptions.enabledOnChannel.indexOf(callInfo_1._channelType) < 0) {
                                throw new Error("controlMessageHandler - Channel ".concat(callInfo_1._channelType, " not enabled for webrtc"));
                            }
                            call_1 = this.retriveCall(callInfo_1.callId);
                            deviceIsApp_1 = (call_1 && call_1.deviceIsApp) || (callInfo_1.device && callInfo_1.device.startsWith("_app_"));
                            webrtcfields_1 = callInfo_1.fields ? WebRTCField.fromObject(callInfo_1.fields) : null;
                            localMediaFeature_1 = {};
                            realEvent_1 = callInfo_1._isFromServer;
                            if (callInfo_1.media_feature && callInfo_1.media_feature.local) {
                                for (media in callInfo_1.media_feature.local) {
                                    localMediaFeature_1[media] = new Set(callInfo_1.media_feature.local[media] ? callInfo_1.media_feature.local[media] : []);
                                }
                            }
                            applyAction = function () { return __awaiter(_this, void 0, void 0, function () {
                                var _a, offer, playringback, currentPlay, offer_1;
                                var _b;
                                return __generator(this, function (_c) {
                                    switch (_c.label) {
                                        case 0:
                                            _a = callInfo_1.state;
                                            switch (_a) {
                                                case CallState.NEW_INBOUND: return [3 , 1];
                                                case CallState.NEW_OUTBOUND: return [3 , 10];
                                                case CallState.IDLE: return [3 , 19];
                                                case CallState.CONNECTED: return [3 , 31];
                                                case CallState.HOLD: return [3 , 45];
                                            }
                                            return [3 , 52];
                                        case 1:
                                            offer = callInfo_1._channelType === ChannelType.Video;
                                            if (!call_1 && !deviceIsApp_1) {
                                                call_1 = this.createCall(callInfo_1.callId, callInfo_1._channelType, offer, callInfo_1.state, realEvent_1, false);
                                            }
                                            if (!call_1) return [3 , 9];
                                            if (!webrtcfields_1) return [3 , 3];
                                            call_1.remoteWebrtcfield = webrtcfields_1;
                                            return [4 , call_1.tryAutoanswer()];
                                        case 2:
                                            _c.sent();
                                            _c.label = 3;
                                        case 3:
                                            if (callInfo_1.remote_media_status) {
                                                call_1.remoteCallMedia.audio = !!callInfo_1.remote_media_status.audio;
                                                call_1.remoteCallMedia.video = !!callInfo_1.remote_media_status.video;
                                                call_1.remoteCallMedia.desktop = !!callInfo_1.remote_media_status.desktop;
                                                call_1.remoteCallMedia.data = !!callInfo_1.remote_media_status.data;
                                            }
                                            if (!(!localMediaFeature_1.audio || !localMediaFeature_1.audio.has(CallMediaFeature.START))) return [3 , 5];
                                            return [4 , call_1.toggleAudioMute(true, false)];
                                        case 4:
                                            _c.sent();
                                            _c.label = 5;
                                        case 5:
                                            if (!(!localMediaFeature_1.video || !localMediaFeature_1.video.has(CallMediaFeature.START))) return [3 , 7];
                                            return [4 , call_1.toggleVideoMute(true, false)];
                                        case 6:
                                            _c.sent();
                                            _c.label = 7;
                                        case 7:
                                            if (!(!call_1.autoanswer && call_1.waitForAnswer)) return [3 , 9];
                                            return [4 , this.phoneSignal.play(call_1.callId, this._connections.size > 1 ? MediaSignal.ringAdvertising : MediaSignal.ring)];
                                        case 8:
                                            _c.sent();
                                            _c.label = 9;
                                        case 9: return [3 , 52];
                                        case 10:
                                            if (!call_1 && !deviceIsApp_1 && callInfo_1._channelType === ChannelType.PhoneCall) {
                                                call_1 = this.createCall(callInfo_1.callId, callInfo_1._channelType, true, callInfo_1.state, realEvent_1, false);
                                            }
                                            if (!call_1) return [3 , 18];
                                            call_1.waitForAnswer = false;
                                            playringback = call_1.realState && call_1.signalingState != CallState.NEW_INBOUND && call_1.signalingState != CallState.CONNECTED;
                                            if (!playringback) return [3 , 13];
                                            return [4 , call_1.toggleAudioMute(true, false)];
                                        case 11:
                                            _c.sent();
                                            return [4 , call_1.toggleVideoMute(true, false)];
                                        case 12:
                                            _c.sent();
                                            _c.label = 13;
                                        case 13:
                                            if (!webrtcfields_1) return [3 , 16];
                                            call_1.remoteWebrtcfield = webrtcfields_1;
                                            if (!(webrtcfields_1.sessionDescription && webrtcfields_1.sessionDescription.session)) return [3 , 15];
                                            return [4 , this.phoneSignal.stop(call_1.callId, true)];
                                        case 14:
                                            _c.sent();
                                            playringback = false;
                                            _c.label = 15;
                                        case 15:
                                            if (!this.options.immediateRingback && playringback && !webrtcfields_1.ring) {
                                                playringback = false;
                                            }
                                            _c.label = 16;
                                        case 16:
                                            if (!playringback) return [3 , 18];
                                            return [4 , this.phoneSignal.play(call_1.callId, MediaSignal.ringback)];
                                        case 17:
                                            _c.sent();
                                            _c.label = 18;
                                        case 18: return [3 , 52];
                                        case 19:
                                            if (!call_1) return [3 , 28];
                                            if (realEvent_1) {
                                                this._callIdToRemove.delete(call_1.callId);
                                            }
                                            else {
                                                call_1.markAsClosedLocal();
                                            }
                                            currentPlay = this.phoneSignal.getCurrentPlay(call_1.callId);
                                            if (!(call_1.signalingState === CallState.NEW_INBOUND)) return [3 , 21];
                                            return [4 , this.phoneSignal.stop(call_1.callId, true)];
                                        case 20:
                                            _c.sent();
                                            return [3 , 27];
                                        case 21:
                                            if (!currentPlay) return [3 , 25];
                                            if (!(currentPlay !== MediaSignal.hold)) return [3 , 24];
                                            if (!!call_1.isClosedLocal()) return [3 , 24];
                                            return [4 , this.phoneSignal.stop(call_1.callId, true)];
                                        case 22:
                                            _c.sent();
                                            return [4 , this.phoneSignal.play(call_1.callId, currentPlay === MediaSignal.ringback ? MediaSignal.congestion : MediaSignal.busy)];
                                        case 23:
                                            _c.sent();
                                            _c.label = 24;
                                        case 24: return [3 , 27];
                                        case 25:
                                            if (!(!call_1.isClosedLocal() && callInfo_1.idleReason && callInfo_1.idleReason !== IdleReason.HANGUP)) return [3 , 27];
                                            return [4 , this.phoneSignal.play(call_1.callId, callInfo_1.idleReason === IdleReason.CONGESTION ? MediaSignal.congestion : MediaSignal.busy)];
                                        case 26:
                                            _c.sent();
                                            _c.label = 27;
                                        case 27:
                                            call_1.closeConnection();
                                            call_1.remoteWebrtcfield = null;
                                            return [3 , 29];
                                        case 28:
                                            if (realEvent_1) {
                                                this._callIdToRemove.delete(callInfo_1.callId);
                                            }
                                            _c.label = 29;
                                        case 29: return [4 , this.destroyCall(callInfo_1.callId)];
                                        case 30:
                                            if (_c.sent()) {
                                                call_1 = null;
                                            }
                                            return [3 , 52];
                                        case 31:
                                            if (!call_1) return [3 , 43];
                                            call_1.waitForAnswer = false;
                                            call_1.remoteWebrtcfield = webrtcfields_1;
                                            call_1.setSignalingState(callInfo_1.state, realEvent_1);
                                            return [4 , this.phoneSignal.stop(call_1.callId, true)];
                                        case 32:
                                            _c.sent();
                                            if (!call_1.localMedia) return [3 , 33];
                                            return [3 , 36];
                                        case 33:
                                            if (!localMediaFeature_1) return [3 , 35];
                                            return [4 , call_1.setLocalMedia(new MediaParamImpl({
                                                    audio: localMediaFeature_1.audio && (localMediaFeature_1.audio.has(CallMediaFeature.UNMUTE) || localMediaFeature_1.audio.has(CallMediaFeature.START)),
                                                    video: localMediaFeature_1.video && (localMediaFeature_1.video.has(CallMediaFeature.UNMUTE) || localMediaFeature_1.video.has(CallMediaFeature.START)),
                                                    desktop: localMediaFeature_1.desktop && (localMediaFeature_1.desktop.has(CallMediaFeature.UNMUTE) || localMediaFeature_1.desktop.has(CallMediaFeature.START)),
                                                    data: localMediaFeature_1.data && (localMediaFeature_1.data.has(CallMediaFeature.UNMUTE) || localMediaFeature_1.data.has(CallMediaFeature.START)),
                                                }), this._loadedOptions.mediaConfiguration)];
                                        case 34:
                                            _c.sent();
                                            return [3 , 36];
                                        case 35: throw new Error("No media defined");
                                        case 36: return [4 , ((_b = call_1.localMedia) === null || _b === void 0 ? void 0 : _b.start())];
                                        case 37:
                                            _c.sent();
                                            if (!call_1.mediaOwnedByCurrentInstance) return [3 , 42];
                                            return [4 , call_1.initTlinkConnection()];
                                        case 38:
                                            _c.sent();
                                            if (!(call_1.audioLinkStatus === CallMediaLinkStatus.MUTE && localMediaFeature_1.audio && localMediaFeature_1.audio.has(CallMediaFeature.MUTE))) return [3 , 40];
                                            return [4 , call_1.toggleAudioMute(false, false)];
                                        case 39:
                                            _c.sent();
                                            _c.label = 40;
                                        case 40:
                                            if (!(call_1.videoLinkStatus === CallMediaLinkStatus.MUTE && localMediaFeature_1.video && localMediaFeature_1.video.has(CallMediaFeature.MUTE))) return [3 , 42];
                                            return [4 , call_1.toggleVideoMute(false, false)];
                                        case 41:
                                            _c.sent();
                                            _c.label = 42;
                                        case 42: return [3 , 44];
                                        case 43:
                                            if (!deviceIsApp_1) {
                                                offer_1 = callInfo_1._channelType === ChannelType.Video;
                                                call_1 = this.createCall(callInfo_1.callId, callInfo_1._channelType, offer_1, callInfo_1.state, realEvent_1, false);
                                            }
                                            if (call_1) {
                                                if (webrtcfields_1) {
                                                    call_1.remoteWebrtcfield = webrtcfields_1;
                                                }
                                                if (callInfo_1.remote_media_status) {
                                                    call_1.remoteCallMedia.audio = !!callInfo_1.remote_media_status.audio;
                                                    call_1.remoteCallMedia.video = !!callInfo_1.remote_media_status.video;
                                                    call_1.remoteCallMedia.desktop = !!callInfo_1.remote_media_status.desktop;
                                                    call_1.remoteCallMedia.data = !!callInfo_1.remote_media_status.data;
                                                }
                                            }
                                            _c.label = 44;
                                        case 44: return [3 , 52];
                                        case 45:
                                            if (!call_1) return [3 , 51];
                                            call_1.remoteWebrtcfield = webrtcfields_1;
                                            if (!call_1.mediaOwnedByCurrentInstance) return [3 , 51];
                                            if (!(call_1.audioLinkStatus === CallMediaLinkStatus.UNMUTE)) return [3 , 47];
                                            return [4 , call_1.toggleAudioMute(true, false)];
                                        case 46:
                                            _c.sent();
                                            _c.label = 47;
                                        case 47:
                                            if (!(call_1.videoLinkStatus === CallMediaLinkStatus.UNMUTE)) return [3 , 49];
                                            return [4 , call_1.toggleVideoMute(true, false)];
                                        case 48:
                                            _c.sent();
                                            _c.label = 49;
                                        case 49:
                                            if (!(CallState.HOLD !== call_1.signalingState)) return [3 , 51];
                                            return [4 , this.phoneSignal.play(call_1.callId, MediaSignal.hold)];
                                        case 50:
                                            _c.sent();
                                            _c.label = 51;
                                        case 51: return [3 , 52];
                                        case 52:
                                            if (!call_1) return [3 , 54];
                                            call_1.setSignalingState(callInfo_1.state, realEvent_1, true);
                                            return [4 , call_1.updateRemoteWebrtcFields()];
                                        case 53:
                                            _c.sent();
                                            return [3 , 55];
                                        case 54:
                                            if (callInfo_1.state !== CallState.IDLE) {
                                                throw new Error("No call");
                                            }
                                            _c.label = 55;
                                        case 55: return [2 , _webrtcControlMessage];
                                    }
                                });
                            }); };
                            if (!call_1) return [3 , 4];
                            return [4 , call_1.connectionActionQueue(applyAction)];
                        case 3: return [2 , _a.sent()];
                        case 4: return [4 , applyAction()];
                        case 5: return [2 , _a.sent()];
                        case 6: return [3 , 8];
                        case 7:
                            err_3 = _a.sent();
                            err_3.controlMessage = _webrtcControlMessage;
                            throw err_3;
                        case 8: return [2 ];
                    }
                });
            });
        };
        WebRTCManager.prototype.createCall = function (callId, channelType, offer, state, realState, markOwner, dialParam, callChecker) {
            var call = this.retriveCall(callId);
            if (!call) {
                if (channelType === ChannelType.Omnidesk) {
                    call = new CallOmnidesk(this, this._controlMessageNotifier, callId, state);
                }
                else {
                    if (callChecker) {
                        call = new CallChecker(this, this._controlMessageNotifier, this._callConnectionStateSubject, callId, channelType, offer, state, realState);
                    }
                    else {
                        call = new Call$1(this, this._controlMessageNotifier, 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;
        };
        WebRTCManager.prototype.retriveCall = function (callId) {
            var _a;
            return (callId !== null && callId !== void 0 ? callId : null) !== null ? (_a = this._connections.get(callId)) !== null && _a !== void 0 ? _a : null : null;
        };
        WebRTCManager.prototype.cleanPendingCall = function () {
            var _this = this;
            if (this._callIdToRemove.size > 0) {
                new Set(this._callIdToRemove).forEach(function (callId) {
                    _this._log.info("Cancel pending call ".concat(callId));
                    _this._apiMethods.forceCancel(callId).subscribe(function () {
                        _this._callIdToRemove.delete(callId);
                    }, function (err) {
                        _this._log.error("Error on cancel pending call ".concat(callId), err);
                    });
                    _this._apiMethods.removeCallFromUserInteraction(callId).subscribe({
                        error: function (err) {
                            _this._log.error("Error on removeCallFromUserInteraction of pending call ".concat(callId), err);
                        },
                    });
                });
            }
        };
        WebRTCManager.prototype.cancelCallRequest = function (callId) {
            var _this = this;
            var _a;
            if (this._connections.has(callId)) {
                this._callIdToRemove.add(callId);
                setTimeout(function (channelType) {
                    _this._controlMessageNotifier.next({
                        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;
            }
        };
        WebRTCManager.prototype.destroyCall = function (callId, dialParam, error) {
            return __awaiter(this, void 0, void 0, function () {
                var call, deviceIsApp;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            call = this.retriveCall(callId);
                            deviceIsApp = (call && call.deviceIsApp) || (dialParam && dialParam.isForApp());
                            if (!(call || deviceIsApp)) return [3 , 3];
                            if (dialParam && error && error instanceof WebAPI) {
                                setTimeout(function () {
                                    if (deviceIsApp || (call && call.signalingState && call.signalingState === CallState.NEW_OUTBOUND && !call.realState)) {
                                        _this._controlMessageNotifier.next({
                                            callId: callId,
                                            device: dialParam.params.fromDevice,
                                            direction: CallDirection.outbound,
                                            state: CallState.IDLE,
                                            _isFromServer: false,
                                            _channelType: dialParam.params.channelId,
                                            _realChannelType: dialParam.params.channelId,
                                        });
                                    }
                                });
                            }
                            if (!call) return [3 , 2];
                            return [4 , call.close()];
                        case 1:
                            _a.sent();
                            this._connections.delete(callId);
                            _a.label = 2;
                        case 2:
                            if (deviceIsApp || (call && call.channelType === ChannelType.PhoneCall && !(call instanceof CallChecker))) {
                                this._apiMethods.removeCallFromUserInteraction(callId).subscribe({
                                    error: function (err) {
                                        _this._log.error("Error on removeCallFromUserInteraction", err);
                                    },
                                });
                            }
                            if (this._connections.size === 1) {
                                this.phoneSignal.convertRingAdvertisingToRingIfNeedle();
                            }
                            return [2 , true];
                        case 3: return [2 , false];
                    }
                });
            });
        };
        return WebRTCManager;
    }());
    var TLinkLogger =  (function (_super) {
        __extends(TLinkLogger, _super);
        function TLinkLogger(manager) {
            var _this = _super.call(this) || this;
            _this.manager = manager;
            _this._logger = Log$1.of("webrtc:tlink", manager.client);
            return _this;
        }
        Object.defineProperty(TLinkLogger.prototype, "logLevel", {
            get: function () {
                return this.manager.client.logConfigurator.logLevel;
            },
            enumerable: false,
            configurable: true
        });
        TLinkLogger.prototype.log = function (logItem) {
            this._logger.logWithTimestamp(logItem.level, logItem.timestamp, logItem.message);
        };
        return TLinkLogger;
    }(LogProvider));

    const logPrefix = "TVoxClientSdk:";
    const DEFAULT_LOG_CONFIGURATOR = new DefaultLogConfigurator(new LogConfig({ prefix: logPrefix }));
    class Log {
        constructor(
        _pkg,
        _instanceId,
        _config) {
            this._pkg = _pkg;
            this._instanceId = _instanceId;
            this._config = _config;
            this.verbose = (...args) => this.log(Log.LogLevel.Verbose, args);
            this.debug = (...args) => this.log(Log.LogLevel.Debug, null, args);
            this.info = (...args) => this.log(Log.LogLevel.Info, null, args);
            this.warn = (...args) => this.log(Log.LogLevel.Warn, null, args);
            this.error = (...args) => this.log(Log.LogLevel.Error, null, args);
            this.fatal = (...args) => this.log(Log.LogLevel.Fatal, null, args);
            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.logConfigurator);
        }
        get config() {
            var _a;
            return (_a = this._config) !== null && _a !== void 0 ? _a : DEFAULT_LOG_CONFIGURATOR;
        }
        log(level, ...args) {
            this.logWithTimestamp(level, null, args);
        }
        logWithTimestamp(level, timestamp, ...args) {
            this._apiLog.logWithTimestamp(level, timestamp, args);
        }
    }
    Log.verbose = (...args) => DEFAULT_LOGGER.verbose(args);
    Log.debug = (...args) => DEFAULT_LOGGER.debug(args);
    Log.info = (...args) => DEFAULT_LOGGER.info(args);
    Log.warn = (...args) => DEFAULT_LOGGER.warn(args);
    Log.error = (...args) => DEFAULT_LOGGER.error(args);
    Log.fatal = (...args) => DEFAULT_LOGGER.fatal(args);
    const DEFAULT_LOGGER = Log.of("");
    (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,
                })
                : new LogConfig({ prefix: logPrefix });
        }
        Log.toWebapiConfig = toWebapiConfig;
        class LogConfigurator {
            constructor() { }
        }
        Log.LogConfigurator = LogConfigurator;
    })(Log || (Log = {}));

    var eventemitter3 = createCommonjsModule(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;
    }
    });

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

    function isString(value) {
        return typeof value === "string" || value instanceof String;
    }
    function emptyStringValue(value) {
        return value == null || value == "" ? undefined : value;
    }
    class SearchResult extends eventemitter3.EventEmitter {
        constructor() {
            super();
        }
    }
    SearchResult.data = "data";
    SearchResult.error = "error";
    SearchResult.complete = "complete";

    exports.CallHistory = void 0;
    (function (CallHistory) {
        class CallHistoryResult extends SearchResult {
            constructor(options) {
                super();
                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 User extends eventemitter3.EventEmitter {
        constructor(client) {
            super();
            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.requestUserStatus.bind(this));
            this.handleEvents();
        }
        get state() {
            return this._state;
        }
        set state(status) {
            this._state = status;
        }
        get statusMonitor() {
            return this._statusMonitor;
        }
        requestUserStatus() {
            return __awaiter$n(this, void 0, void 0, function* () {
                yield this.canDoRequest();
                if (this.info.username) {
                    return this.client.api.methods.getUserContactStatus(this.info.username);
                }
                else {
                    throw "username to request contact status is unavailable";
                }
            });
        }
        handleEvents() {
            this.client.on("ready", () => (this._loadUserProfileInProgress = false));
            this.client.api.loginProfile.subscribe((data) => __awaiter$n(this, void 0, void 0, function* () {
                const prevstate = this.state;
                this.state = data.logged ? User.State.LOGGED : User.State.NOTLOGGED;
                this.info.username = data.username;
                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.initializeApiAfterLogin();
                                }
                                break;
                            case Client.ClientState.LOGIN_IN_PROGRESS:
                                if (data.logged) {
                                    if (prevstate !== this.state) {
                                        this.client.emit("logged_in", this);
                                        this.initializeApiAfterLogin();
                                    }
                                }
                                else if (data.status === LoginProfileStatus.SOCKET_CLOSED_REQUEST_FORCE) {
                                    setTimeout(() => {
                                        this.client.api.methods.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$n(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$n(this, void 0, void 0, function* () {
                            yield this.loadUserDetail(userDetail);
                            yield this.client.api.methods.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$n(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 === User.ProfileType.UC)) !== null && _b !== void 0 ? _b : this.availableProfile.find((p) => p.type === User.ProfileType.AG)) !== null && _c !== void 0 ? _c : this.availableProfile[0];
            }
        }
        loadUserDetail(userDetail) {
            return __awaiter$n(this, void 0, void 0, function* () {
                if (userDetail.profiles) {
                    const availableProfile = userDetail.profiles
                        .filter((p) => p.clientLoginEnable)
                        .map((p) => new User.Profile(p.id, p.label, p.type))
                        .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();
                return userDetail;
            });
        }
        loadUserDetailUpdate(userDetail) {
            return __awaiter$n(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 = new User.Profile(profile.id, profile.label, profile.type);
                            this.availableProfile.push(profileAdded);
                            isProfileAdded = true;
                            this.emit("profile_added", profileAdded);
                        }
                    });
                }
                this.loadDefaultConfiguration(userDetail.loggedProfileId);
                if (isProfileAdded || isProfileRemoved) {
                    yield this.useProfile();
                }
            });
        }
        useProfile(profile) {
            return __awaiter$n(this, void 0, void 0, function* () {
                const result = this.useProfileChain
                    .catch((err) => null)
                    .then(() => __awaiter$n(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$n(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(profile.id, this.client.phone.device.type === C.LineType.SIP ? ExtenType.SIP : ExtenType.WEBRTC, this.client.phone.device.exten, false);
                        }
                        else {
                            useProfileRequest = this.client.api.methods.useProfile(profile.id, null, null, 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) => {
                            profile.detail = profileDetail;
                        });
                        this.useProfileSubscription.add(useProfileRequest.notification.subscribe((profileDetail) => {
                            var _a;
                            profile.detail = Object.assign(Object.assign({}, ((_a = profile.detail) !== null && _a !== void 0 ? _a : {})), profileDetail);
                        }));
                        yield useProfileResult.pipe(first()).toPromise();
                        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");
                }
            });
        }
        canDoRequest() {
            return __awaiter$n(this, void 0, void 0, function* () {
                if (Client.ClientState.READY === this.client.state) {
                    return;
                }
                else {
                    throw "Client is not ready to request data";
                }
            });
        }
        searchContact(options) {
            var _a, _b;
            return __awaiter$n(this, void 0, void 0, function* () {
                yield this.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 response = new Contact.SearchContactResult(options);
                const request = this.client.api.methods.searchUsersExtended(addressbooktype, [
                    { exclusive: true, key: AddressBookFieldKey.N, mode, type, value: [options.toSearch] },
                    { exclusive: true, key: AddressBookFieldKey.TEL, mode, type, value: [options.toSearch] },
                    { exclusive: true, key: AddressBookFieldKey.ORG, mode, type, value: [options.toSearch] },
                ], 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(data.data), data.i, data.tot);
                    },
                    error: (err) => {
                        response.emit("error", err);
                    },
                    complete: () => {
                        response.emit("complete");
                        request.stopNotification();
                    },
                });
                return response;
            });
        }
        getContact(id) {
            return __awaiter$n(this, void 0, void 0, function* () {
                yield this.canDoRequest();
                return Contact.from(yield this.client.api.methods.getAddressBookContactByUuid(id));
            });
        }
        getCallHistory(options) {
            var _a, _b;
            return __awaiter$n(this, void 0, void 0, function* () {
                yield this.canDoRequest();
                const response = new exports.CallHistory.CallHistoryResult(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)
                    .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) {
        (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 = {}));
        (function (ProfileType) {
            ProfileType["UC"] = "UC";
            ProfileType["AG"] = "AG";
            ProfileType["AG_EXTERNAL"] = "AG_EXTERNAL";
            ProfileType["AG_REMOTE"] = "AG_REMOTE";
            ProfileType["TQM"] = "TQM";
        })(User.ProfileType || (User.ProfileType = {}));
        class Profile {
            constructor(id, _label, type) {
                this.id = id;
                this._label = _label;
                this.type = type;
            }
            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);
            }
        }
        User.Profile = Profile;
    })(User || (User = {}));
    class UserStatusMonitor extends eventemitter3.EventEmitter {
        constructor(doRequest) {
            super();
            this.doRequest = doRequest;
            this.requestSubscription = Subscription.EMPTY;
            this._lastValue = new UserStatusMonitor.Value(null);
            this._started = false;
        }
        start() {
            return __awaiter$n(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),
                        concatMap(() => EMPTY)), request.notification)
                            .pipe(map((contactStatus) => new UserStatusMonitor.Value(contactStatus)))
                            .subscribe((userStatusValue) => {
                            if (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$n(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();
            }
        }
        UserStatusMonitor.PhoneChannelStatus = PhoneChannelStatus;
        class PresenceStatus {
            constructor(status, message) {
                this.status = status;
                this.message = message;
            }
            equals(status) {
                return this.status === status.status && this.message === status.message;
            }
        }
        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) {
                        this.presenceStatus = new PresenceStatus(presenceStatusValue, emptyStringValue(userContact.presenceMessage));
                    }
                }
            }
        }
        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(data) {
            if (isUserContact(data)) {
                return new InternalUserContact(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(data) {
            super(data, Contact.Type.INTERNAL, Contact.InternalSubType.USER);
            this.data = data;
        }
        get statusMonitor() {
            if (!this._statusMonitor) {
                this._statusMonitor = new UserStatusMonitor(() => {
                    throw new Error("InternalUserContact statusMonitor not implemented");
                });
            }
            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) {
        class SearchContactResult extends SearchResult {
            constructor(requestOptions) {
                super();
                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 = {}));

    class Call extends eventemitter3.EventEmitter {
        constructor(_device, callId, direction) {
            super();
            this._device = _device;
            this.callId = callId;
            this.direction = direction;
            this._lastApiMessage = null;
            this.lookup = new Call.Lookup();
            this._startTime = new Date();
        }
        get device() {
            return this._device;
        }
        get id() {
            return this._uniqueId || this.callId;
        }
        get startTime() {
            return this._startTime;
        }
        get endTime() {
            return this._endTime;
        }
        get duration() {
            return this._duration;
        }
        get service() {
            return this._service;
        }
        get features() {
            return this._lastApiMessage ? (this._lastApiMessage.features ? this._lastApiMessage.features : []) : [];
        }
        get lastUpdateMessageDate() {
            var _a, _b;
            if ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.time) {
                return new Date((_b = this._lastApiMessage) === null || _b === void 0 ? void 0 : _b.time);
            }
            else {
                return null;
            }
        }
        updateFromApi(data, emitEvent = true) {
            var _a, _b, _c;
            return __awaiter$n(this, void 0, void 0, function* () {
                const previouseFeatures = [...this.features];
                this._lastApiMessage = data;
                if (data.cdrid && this._uniqueId !== data.cdrid) {
                    this._uniqueId = data.cdrid;
                }
                if (data.duration && this._duration !== data.duration) {
                    this._duration = data.duration;
                }
                if (data.service) {
                    this._service = {
                        code: data.service,
                        description: (_c = (_b = (_a = this._device.client.user.info.profile) === null || _a === void 0 ? void 0 : _a.getServiceByCode(data.service)) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : data.service,
                    };
                }
                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);
                }
                if (data.start) {
                    try {
                        const startDate = new Date(data.start);
                        this._startTime = startDate;
                    }
                    catch (e) { }
                }
                this.lookup.updateFromApi(data);
            });
        }
        hasFeature(feature) {
            var _a, _b, _c;
            return ((_c = (_b = (_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.indexOf(feature)) !== null && _c !== void 0 ? _c : -1) > -1;
        }
    }
    (function (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["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 = {}));
        class Lookup extends eventemitter3.EventEmitter {
            constructor() {
                super();
                this._status = "progress";
                this.display = {};
            }
            get contact() {
                return this._contact;
            }
            get status() {
                return this._status;
            }
            get result() {
                return this._result;
            }
            updateFromApi(data) {
                return __awaiter$n(this, void 0, void 0, function* () {
                    let emitDisplay = false;
                    if (this.display.company != data.lookup_display_company) {
                        this.display.company = data.lookup_display_company;
                        emitDisplay = true;
                    }
                    if (this.display.name != data.lookup_display_name) {
                        this.display.name = data.lookup_display_name;
                        emitDisplay = true;
                    }
                    const lookup_display_number = data.lookup_display_number || data.remoteNumber;
                    if (this.display.number != lookup_display_number && !!lookup_display_number) {
                        this.display.number = lookup_display_number;
                        emitDisplay = true;
                    }
                    if (emitDisplay) {
                        this.emit("update_display", this.display, this);
                    }
                    if (data.lookup_addressbook_type) {
                        const contact = Contact.from({ type: data.lookup_addressbook_type, id: data.lookup_addressbook_uid, username: data.lookup_addressbook_username, photo: data.lookup_addressbook_photo });
                        if (contact) {
                            this._contact = contact;
                            this.emit("update_contact", this.contact, this);
                        }
                    }
                    if (data.lookup_finished) {
                        this._status = "end";
                        this._result = data.lookup_display_result;
                        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 = {}));
    })(Call || (Call = {}));

    class CallSip extends Call {
        constructor(device, callId, direction) {
            super(device, callId, direction);
            this.type = C.LineType.SIP;
            this._hold = false;
        }
        get callSipForTransferInstance() {
            return this._callSipForTransferInstance;
        }
        updateFromApi(data, emitEvent = true) {
            const _super = Object.create(null, {
                updateFromApi: { get: () => super.updateFromApi }
            });
            var _a, _b, _c;
            return __awaiter$n(this, void 0, void 0, function* () {
                let eventToEmit;
                if (!this._lastApiMessage) {
                    yield _super.updateFromApi.call(this, data);
                    eventToEmit = "connecting";
                }
                else if (((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === data.state) {
                    eventToEmit = "progress";
                }
                else {
                    switch (data.state) {
                        case CallState.CONNECTED:
                            (_b = this.callSipForTransferInstance) === null || _b === void 0 ? void 0 : _b.setEnded(emitEvent);
                            eventToEmit = "accepted";
                            break;
                        case CallState.IDLE:
                            this._endTime = new Date();
                            this._duration = data.duration;
                            (_c = this.callSipForTransferInstance) === null || _c === void 0 ? void 0 : _c.setEnded(emitEvent);
                            eventToEmit = "ended";
                            break;
                    }
                }
                if (this._lastApiMessage !== data) {
                    _super.updateFromApi.call(this, data);
                }
                if (emitEvent && eventToEmit) {
                    this.emit(eventToEmit);
                }
            });
        }
        featureChange(features, previousFeatures) {
            this.emit("change_features", features, previousFeatures);
        }
        isInProgress() {
            var _a, _b;
            return ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.NEW_INBOUND || ((_b = this._lastApiMessage) === null || _b === void 0 ? void 0 : _b.state) === CallState.NEW_OUTBOUND;
        }
        isEstablished() {
            var _a;
            return !this.isInProgress() && ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) !== CallState.IDLE;
        }
        isEnded() {
            var _a;
            return ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.IDLE;
        }
        isOnHold() {
            var _a, _b;
            return this._hold || ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.HOLD || ((_b = this._lastApiMessage) === null || _b === void 0 ? void 0 : _b.state) === CallState.HOLD_PENDING_SIP;
        }
        answer() {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.device.client.api.methods.answerOnChannel(ChannelType.PhoneCall, this.callId, null);
            });
        }
        terminate() {
            return __awaiter$n(this, void 0, void 0, function* () {
                if (this.hasFeature(Call.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$n(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() {
            return __awaiter$n(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;
                        this.emit("hold");
                    }
                    else {
                        this._hold = false;
                    }
                    return response;
                }
                return false;
            });
        }
        unhold() {
            return __awaiter$n(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;
                        this.emit("unhold");
                    }
                    else {
                        this._hold = true;
                    }
                    return response;
                }
                else {
                    return false;
                }
            });
        }
        isDialForTransferEnabled() {
            return this.hasFeature(Call.CallFeature.DIAL_ATXFER);
        }
        dialForTransfer(phoneNumber, param) {
            var _a;
            return __awaiter$n(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$n(this, void 0, void 0, function* () {
                return this.transfer(number);
            });
        }
        transferToCall(call) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.transfer(call);
            });
        }
        transfer(target) {
            return __awaiter$n(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.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 eventemitter3.EventEmitter {
        constructor(device, _callSip) {
            super();
            this.device = device;
            this._callSip = _callSip;
            this._ended = false;
        }
        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$n(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.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$n(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.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 {
        constructor(device, id, direction) {
            super(device, id, direction);
            this.type = C.LineType.WEBRTC;
            this._hold = false;
            this._connectionManager = new CallWebrtc.ConnectionManager(this);
        }
        get connectionManager() {
            return this._connectionManager;
        }
        updateFromApi(data, emitEvent = true) {
            const _super = Object.create(null, {
                updateFromApi: { get: () => super.updateFromApi }
            });
            var _a;
            return __awaiter$n(this, void 0, void 0, function* () {
                let eventToEmit;
                if (!this._lastApiMessage) {
                    yield _super.updateFromApi.call(this, data);
                    eventToEmit = "connecting";
                }
                else if (((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === data.state) {
                    eventToEmit = "progress";
                }
                else {
                    switch (data.state) {
                        case CallState.CONNECTED:
                            eventToEmit = "accepted";
                            break;
                        case CallState.IDLE:
                            this._endTime = new Date();
                            this._duration = data.duration;
                            eventToEmit = "ended";
                            break;
                    }
                }
                if (this._lastApiMessage !== data) {
                    _super.updateFromApi.call(this, data);
                }
                if (emitEvent && eventToEmit) {
                    this.emit(eventToEmit);
                }
            });
        }
        featureChange(features, previousFeatures) {
            this.emit("change_features", features, previousFeatures);
        }
        isInProgress() {
            var _a, _b;
            return ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.NEW_INBOUND || ((_b = this._lastApiMessage) === null || _b === void 0 ? void 0 : _b.state) === CallState.NEW_OUTBOUND;
        }
        isEstablished() {
            var _a;
            return !this.isInProgress() && ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) !== CallState.IDLE;
        }
        isEnded() {
            var _a;
            return ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.IDLE;
        }
        isOnHold() {
            var _a;
            return this._hold || ((_a = this._lastApiMessage) === null || _a === void 0 ? void 0 : _a.state) === CallState.HOLD;
        }
        answerAudio() {
            return this.answer({ audio: true });
        }
        answerVideo(videoContainer) {
            return this.answer({ audio: true, video: true }, videoContainer);
        }
        answer(media, 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, 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() {
            return this.device.client.api.methods.hold(this.callId);
        }
        unhold() {
            return this.device.client.api.methods.unhold(this.callId);
        }
        transferToNunber(number, accessCode, data) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.transfer({ number, accessCode, data });
            });
        }
        transferToCall(target) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.transfer(target);
            });
        }
        transfer(target) {
            var _a, _b;
            return __awaiter$n(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);
        }
    }
    function isTargetNumber(target) {
        return target.hasOwnProperty("number") && isString(target.number);
    }
    (function (CallWebrtc) {
        class ConnectionManager extends eventemitter3.EventEmitter {
            constructor(call) {
                super();
                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);
                    }
                });
            }
            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.emit("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.emit("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.emit("stats", stats);
                });
            }
            stopConnectionStats() {
                var _a;
                (_a = this._subscriptions.connectionStats) === null || _a === void 0 ? void 0 : _a.unsubscribe();
                this._subscriptions.connectionStats = 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 = C.LineType.SIP;
        }
        get client() {
            return this._phone.client;
        }
        get phone() {
            return this._phone;
        }
        dial(phoneNumber, param) {
            var _a, _b, _c;
            return __awaiter$n(this, void 0, void 0, function* () {
                const contactIdentifier = {
                    type: AddressBookContactType.UNKNOWN,
                    value: phoneNumber,
                };
                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 DeviceWebrtc {
        constructor(_phone,
        label,
        exten) {
            this._phone = _phone;
            this.label = label;
            this.exten = exten;
            this.type = C.LineType.WEBRTC;
            this.configuration = new DeviceWebrtc.Configuration(this);
        }
        get client() {
            return this._phone.client;
        }
        get phone() {
            return this._phone;
        }
        dialAudio(phoneNumber, param) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.dial(phoneNumber, param, { media: { audio: true, video: false } });
            });
        }
        dialVideo(phoneNumber, param, videoContainer) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.dial(phoneNumber, param, { media: { audio: true, video: true } }, videoContainer);
            });
        }
        dial(phoneNumber, param, _dialParam, videoContainer) {
            var _a, _b, _c;
            return __awaiter$n(this, void 0, void 0, function* () {
                const contactIdentifier = {
                    type: AddressBookContactType.UNKNOWN,
                    value: phoneNumber,
                };
                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 eventemitter3.EventEmitter {
        constructor(_client) {
            super();
            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.callNotification.subscribe((() => {
                let callNotificationHandlerChain = Promise.resolve();
                return (callInfo) => __awaiter$n(this, void 0, void 0, function* () {
                    try {
                        yield callNotificationHandlerChain;
                    }
                    finally {
                        callNotificationHandlerChain = this.handleChannelNotification(callInfo);
                    }
                });
            })());
            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) {
                    console.warn("-- WARNING -- remote control of TVox Client may not work properly on browsers");
                }
                this.emit("tvoxclient_state_change", this._tvoxClientState, this._tvoxClientStateDetail);
            });
        }
        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$n(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$n(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 ? C.LineType.SIP : 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 === 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$n(this, void 0, void 0, function* () {
                if (type && device) {
                    const lineType = type === ExtenType.SIP ? C.LineType.SIP : 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;
                            if (previousDeviceByClient) {
                                this.emit("device_change", deviceByClient, previousDeviceByClient);
                            }
                        }
                    }
                }
            });
        }
        checkDeviceAfterApiData() {
            var _a, _b, _c;
            return __awaiter$n(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 === C.LineType.SIP)) !== null && _b !== void 0 ? _b : this.availableDevice.find((d) => d.type === C.LineType.WEBRTC)) !== null && _c !== void 0 ? _c : this.availableDevice[0]);
                    }
                }
                else {
                    this.device = null;
                    this.state = Phone.Status.ERROR_NO_DEVICE_AVAILABLE;
                }
            });
        }
        handleChannelNotification(data) {
            return __awaiter$n(this, void 0, void 0, function* () {
                if (ChannelType.PhoneCall !== channelIdToChannelType(data.channelid)) {
                    return;
                }
                let call = this.getCall(data.callId);
                if (call) {
                    yield call.updateFromApi(data);
                }
                else if (data.state === CallState.NEW_INBOUND || data.state === CallState.NEW_OUTBOUND) {
                    const direction = data.state === CallState.NEW_INBOUND ? Call.Direction.INBOUND : Call.Direction.OUTBOUND;
                    switch (data.deviceType) {
                        case ExtenType.SIP:
                            {
                                const deviceOfCall = this.availableDevice.find((d) => d.type === C.LineType.SIP && d.exten === data.device);
                                if (deviceOfCall) {
                                    call = new CallSip(deviceOfCall, data.callId, direction);
                                    this._calls.set(call.callId, call);
                                }
                            }
                            break;
                        case ExtenType.WEBRTC:
                            {
                                const deviceOfCall = this.availableDevice.find((d) => d.type === C.LineType.WEBRTC && d.exten === data.device);
                                if (deviceOfCall) {
                                    call = new CallWebrtc(deviceOfCall, data.callId, direction);
                                    this._calls.set(call.callId, call);
                                }
                            }
                            break;
                    }
                    if (call) {
                        call.updateFromApi(data, false);
                        this.emit("newcall", call);
                    }
                }
            });
        }
        useDevice(device) {
            return __awaiter$n(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 === 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) {
        (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 eventemitter3.EventEmitter {
        constructor(client) {
            super();
            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) {
        (function (Status) {
            Status["CONNECTED"] = "CONNECTED";
            Status["DISCONNECTED"] = "DISCONNECTED";
        })(Transport.Status || (Transport.Status = {}));
    })(Transport || (Transport = {}));

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

    class Client extends eventemitter3.EventEmitter {
        constructor(configuration) {
            super();
            this._state = Client.ClientState.LOGIN_REQUIRED;
            this.configuration = configuration;
            this.api = new WebapiClient(this.mapConfigurationToWebapiConfig());
            this._logConfigImpl = new Client.ClientLogConfigurator(this);
            this.api.webrtc = new WebRTCManager({ enabled: false, enabledOnChannel: [ChannelType.PhoneCall] });
            this.transport = new Transport(this);
            this.user = new User(this);
            this.phone = new Phone(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;
            });
        }
        get state() {
            return this._state;
        }
        set state(status) {
            this._state = status;
        }
        get logConfigurator() {
            return this._logConfigImpl;
        }
        get instanceId() {
            return this.api.instanceId;
        }
        mapConfigurationToWebapiConfig() {
            const configuration = this.configuration;
            return {
                url: configuration.url.endsWith("/clientproxy") ? configuration.url : `${configuration.url}/clientproxy`,
                userAgent: { type: "custom", version: SDK_VERSION, description: `TVox SDK ${SDK_VERSION} ${LIB_VERSION}` },
                phoneManagerActive: !(this.configuration.phoneManagedByTVoxClient || false),
                selfManagedLogin: false,
                multisession: true,
                logConfig: Log.toWebapiConfig(configuration.log),
                retryOptions: configuration.retryOptions,
            };
        }
        login(credential) {
            var _a;
            return __awaiter$n(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.methods.login(credential.username, credential.password, rememberMe);
                    }
                    else if (isBerearCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.methods.loginByAccessToken(credential.token, rememberMe);
                    }
                    else if (isExternalSessionIdCredential(credential)) {
                        this.emit("login_in_progress", this.user, credential);
                        loginProfile = yield this.api.methods.loginCustom(credential.externalSessionId, 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) {
                    throw "invalid response from login";
                }
            });
        }
        logout(reason, note) {
            return __awaiter$n(this, void 0, void 0, function* () {
                return this.api.methods.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;
            }
        }
    }
    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";
    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 (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 ClientLogConfigurator extends Log.LogConfigurator {
            constructor(
            client) {
                super();
                this.client = client;
                const enableValue = this.client.api.logConfigurator.prefix ? this.client.api.logConfigurator.prefix + "*" : "*";
                let enabled = ClientLogConfigurator.disableNamespace();
                if (enabled) {
                    if (enabled !== "*" && this.client.api.logConfigurator.prefix && enabled.indexOf(this.client.api.logConfigurator.prefix) < 0) {
                        enabled += "," + enableValue;
                    }
                }
                else {
                    enabled = enableValue;
                }
                ClientLogConfigurator.enableNamespace(enabled);
            }
            get enabled() {
                return this.client.api.logConfigurator.enabled;
            }
            set enabled(enabled) {
                this.client.api.logConfigurator.enabled = enabled;
            }
            get objectToJson() {
                return this.client.api.logConfigurator.objectToJson;
            }
            set objectToJson(objectToJson) {
                this.client.api.logConfigurator.objectToJson = !!objectToJson;
            }
            set instanceIdLogged(instanceIdLogged) {
                this.client.api.logConfigurator.instanceIdLogged = !!instanceIdLogged;
            }
            get instanceIdLogged() {
                return this.client.api.logConfigurator.instanceIdLogged;
            }
            set logLevel(logLevel) {
                if (logLevel && logLevel >= Log.LogLevel.Verbose && logLevel <= Log.LogLevel.None) {
                    this.client.api.logConfigurator.logLevel = logLevel;
                }
            }
            get logLevel() {
                return this.enabled ? this.client.api.logConfigurator.logLevel : Log.LogLevel.None;
            }
            get prefix() {
                return this.client.api.logConfigurator.prefix;
            }
            set prefix(prefix) {
                this.client.api.logConfigurator.prefix = prefix;
            }
            get timestamp() {
                return this.client.api.logConfigurator.timestamp;
            }
            set timestamp(timestamp) {
                this.client.api.logConfigurator.timestamp = !!timestamp;
            }
            static enableNamespace(namespace) {
                debug$1.enable(namespace);
            }
            static disableNamespace() {
                return debug$1.disable();
            }
        }
        Client.ClientLogConfigurator = ClientLogConfigurator;
    })(Client || (Client = {}));

    exports.Call = Call;
    exports.CallSip = CallSip;
    exports.CallSipForTransfer = CallSipForTransfer;
    exports.CallWebrtc = CallWebrtc;
    exports.Client = Client;
    exports.Contact = Contact;
    exports.DeviceSip = DeviceSip;
    exports.DeviceWebrtc = DeviceWebrtc;
    exports.ExternalItemContact = ExternalItemContact;
    exports.ExternalOrganizationContact = ExternalOrganizationContact;
    exports.InternalServiceContact = InternalServiceContact;
    exports.InternalShortNumberContact = InternalShortNumberContact;
    exports.InternalUserContact = InternalUserContact;
    exports.Log = Log;
    exports.PersonalContact = PersonalContact;
    exports.Phone = Phone;
    exports.SearchResult = SearchResult;
    exports.Transport = Transport;
    exports.User = User;
    exports.UserStatusMonitor = UserStatusMonitor;
    exports.emptyStringValue = emptyStringValue;
    exports.isContact = isContact;
    exports.isString = isString;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
